在 C++ 中使用 Monte Carlo 方法求 π 的问题

Problems with finding π using Monte Carlo method in C++

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

#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;
}

但是,这会生成以下输出,这似乎不合理: 这里的问题是什么,为什么程序会为 π 生成如此不准确的数字?我假设我的逻辑在中间某处失败了,但我不知道在哪里...... 运行 在 Code::Blocks 16,C++0X 标准中。

四分之一圆的面积是

inside = (pi*r^2)/4

四分之一正方形的面积是

total = r^2

和"outside"

的面积
outside = total - inside = r^2 - (pi*r^2)/4

所以你把公式弄错了。需要比较总的trials和里面的trials,不是outside/inside:

4* inside / total  = pi

顺便说一下,在执行 monte carlo 并要求精度时,您不应该使用 rand(),而是可以在 <random>.

中找到的设施