蒙特卡洛方法我有應該進行粗略的π使用蒙特卡洛方法的程序,以及將碼是如下發現π:然而問題與使用C++
#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標準中運行。
你應該在你的程序開始時將'std :: srand()'精確*調用* seed *隨機數發生器。對於這樣的事情,通常使用當前時間就足夠了:'std :: srand(std :: time(0));'。爲了獲得更準確的結果,您應該考慮使用''功能。 –
Galik
你不需要sqrt()。當且僅當v <= 1時,sqrt(v)<= 1。不會修復錯誤,但會讓你錯誤更快! – Persixty