在C++中使用蒙特卡罗方法找到π的问题

Nam*_*ing 1 c++ algorithm codeblocks montecarlo

我有一个程序应该使用蒙特卡罗方法找到π的近似值,代码如下:

#include <iostream>
#include <cstdlib>
#include <cmath>

int main()
{
    double x=0, y=0, piEstimate=0, precision=0;
    int N;
    int nIn=0, nOut=0;
    std::cout << "Please enter the seed number." <<std::endl;
    std::cin >> N;
    for(int i=0;i<=N;i++){
        x=(double)rand()/(double)RAND_MAX;
        y=(double)rand()/(double)RAND_MAX;
        if(sqrt(x*x+y*y)>1){
            nOut++;
        }else if(sqrt(x*x+y*y)<1){
            nIn++;
        }
    }
    piEstimate=4*(nOut/nIn);
    std::cout<<"The estimate of pi with "<<N<<" seeds is "<<4.0*(nOut/nIn)<<"."<<std::endl;
    std::cout<<"Error percentage at "<<abs(100.0-piEstimate/3.1415926)<<"."<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是,这会产生以下输出,这似乎是不合理的: montecarloprogramoutput 这里有什么问题,为什么程序会为π生成这样不准确的数字?我假设我的逻辑在中间某处失败,但我无法弄清楚在哪里...运行Code :: Blocks 16,C++ 0X标准.

for*_*818 6

四分之一圈的面积是

inside = (pi*r^2)/4
Run Code Online (Sandbox Code Playgroud)

四分之一广场的面积是

total = r^2
Run Code Online (Sandbox Code Playgroud)

和"外面"的区域

outside = total - inside = r^2 - (pi*r^2)/4
Run Code Online (Sandbox Code Playgroud)

所以你的公式错了.您需要比较总体试验和内部试验,而不是外部/内部:

4* inside / total  = pi
Run Code Online (Sandbox Code Playgroud)

顺便说一下做monte carlo并要求精确度你不应该使用rand()你可以找到的设施<random>.

  • 它实际上是"<random>". (4认同)
  • @MatteoItalia afaik rand()随机性很差.计算圆圈只是蒙特卡罗的一个介绍性例子,有更快,更准确的方法来估计pi,没有人会用MC来做到这一点.因此,即使它对圆圈无关紧要,我们也应该注意使用正确的工具作为基本示例 (2认同)