首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我在这个计算PI的方案程序中找不到我的错误

我在这个计算PI的方案程序中找不到我的错误
EN

Stack Overflow用户
提问于 2009-08-23 14:09:17
回答 1查看 2.3K关注 0票数 3

我正在做一个蒙特卡罗实验来计算PI的近似。来自国际预防犯罪中心:

蒙特卡罗方法包括从一个大集合中随机选择样本实验,然后根据这些实验结果表估计的概率进行推导。例如,我们可以用6/pi^2是随机选择的两个整数不存在共同因子的概率来近似,即它们的最大公因子为1,为了得到这个近似,我们进行了大量的实验。在每个实验中,我们随机选择两个整数,并进行检验,看看它们的GCD是否为1。测试通过的次数给出了我们对6/ pi ^2的估计,并由此得到了我们对pi的逼近。

但是当我运行我的程序时,我得到了3.9的值.

这是我的节目:

代码语言:javascript
复制
(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

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2009-08-23 16:37:05

我发现了我的错误。多亏了所有人。我在错误的地方增加了成功的案例。

修正后的代码是:

代码语言:javascript
复制
(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)))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1318664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档