我有一个程序应该使用蒙特卡罗方法找到π的近似值,代码如下:
#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)
但是,这会产生以下输出,这似乎是不合理的:
这里有什么问题,为什么程序会为π生成这样不准确的数字?我假设我的逻辑在中间某处失败,但我无法弄清楚在哪里...运行Code :: Blocks 16,C++ 0X标准.