我正在做一个蒙特卡洛实验来计算 PI 的近似值。来自 SICP:
蒙特卡洛方法包括从一个大集合中随机选择样本实验,然后根据从这些实验结果列表中估计的概率进行推断。例如,我们可以使用 6/pi^2 是随机选择的两个整数没有共同因子的概率来近似;也就是说,它们的最大公约数将是 1。为了获得 的近似值,我们进行了大量的实验。在每个实验中,我们随机选择两个整数并执行测试以查看它们的 GCD 是否为 1。通过测试的次数为我们提供了 6/pi^2 的估计值,由此我们获得了 pi 的近似值.
但是当我运行我的程序时,我会获得像 3.9 这样的值......
这是我的程序:
(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)))
我的解释器是 MIT/GNU 7.7.90
谢谢你的帮助。