tags:

views:

409

answers:

3

I am doing a Monte Carlo experiment to calculate an approximation of PI. From SICP:

The Monte Carlo method consists of choosing sample experiments at random from a large set and then making deductions on the basis of the probabilities estimated from tabulating the results of those experiments. For example, we can approximate using the fact that 6/pi^2 is the probability that two integers chosen at random will have no factors in common; that is, that their greatest common divisor will be 1. To obtain the approximation to , we perform a large number of experiments. In each experiment we choose two integers at random and perform a test to see if their GCD is 1. The fraction of times that the test is passed gives us our estimate of 6/pi^2, and from this we obtain our approximation to pi.

But when I run my program I obtain values like 3.9...

Here is my program:

(define (calculate-pi trials)
  (define (this-time-have-common-factors?)
    (define (get-rand)
      (+ (random 9999999999999999999999999999999) 1))
    (= (gcd (get-rand) (get-rand)) 1))
  (define (execute-experiment n-times acc)
    (if (> n-times 0)
        (if (this-time-have-common-factors?)
            (execute-experiment (- n-times 1) acc)
            (execute-experiment (- n-times 1) (+ acc 1)))
        acc))
  (define n-success (execute-experiment trials 0))
  (define prob (/ n-success trials))
  (sqrt (/ 6 prob)))

My interpreter is MIT/GNU 7.7.90

Thanks for any help.

A: 

wrong answer removed.

abc
The best thing to do if you leave a bad answer is to delete it. There should be a delete link underneath your answer, above this comment.
John Fouhy
I see 'link | edit | flag' but not delete.
abc
+3  A: 

I find my error. Thanks to all. I was incrementing the successful cases in the wrong place.

The corrected code is:

(define (calculate-pi trials)
  (define (this-time-have-common-factors?)
    (define (get-rand)
      (+ (random 9999999) 1))
    (= (gcd (get-rand) (get-rand)) 1))
  (define (execute-experiment n-times acc)
    (if (> n-times 0)
        (if (this-time-have-common-factors?)
            (execute-experiment (- n-times 1) (+ acc 1))
            (execute-experiment (- n-times 1) acc))
        acc))
  (define n-success (execute-experiment trials 0))
  (define prob (/ n-success trials))
  (sqrt (/ 6 prob)))
Castro
yup, you got it!
Jason S
+10  A: 
Jason S
thanks for your reply and the additional info!
Castro
> How many times are you running it?(calculate-pi 99999999) 1 ]=> ;Value: 3.141544196485725
Castro