我正在做一个蒙特卡罗实验来计算PI的近似。来自国际预防犯罪中心:
蒙特卡罗方法包括从一个大集合中随机选择样本实验,然后根据这些实验结果表估计的概率进行推导。例如,我们可以用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
谢谢你的帮助。
发布于 2009-08-23 16:37:05
我发现了我的错误。多亏了所有人。我在错误的地方增加了成功的案例。
修正后的代码是:
(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)))https://stackoverflow.com/questions/1318664
复制相似问题