2017-07-29 85 views
1

蒙特卡洛方法我有應該進行粗略的π使用蒙特卡洛方法的程序,以及將碼是如下發現π:然而問題與使用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; 
} 

此,生成以下輸出,這看起來不合理: montecarloprogramoutput 這裏有什麼問題,爲什麼程序爲π生成這樣不準確的數字?我假設我的邏輯在中間的某個地方失敗了,但是我不知道在哪裏...... 在Code :: Blocks 16,C++ 0X標準中運行。

+0

你應該在你的程序開始時將'std :: srand()'精確*調用* seed *隨機數發生器。對於這樣的事情,通常使用當前時間就足夠了:'std :: srand(std :: time(0));'。爲了獲得更準確的結果,您應該考慮使用''功能。 – Galik

+1

你不需要sqrt()。當且僅當v <= 1時,sqrt(v)<= 1。不會修復錯誤,但會讓你錯誤更快! – Persixty

回答

6

四分之一圓的面積爲1/4平方的

inside = (pi*r^2)/4 

面積

total = r^2 

和 「外」

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

所以你得到的面積公式錯誤。做蒙特卡洛和要求的精度,你不應該使用rand()但設施您可以在<random>找到時

4* inside/total = pi 

順便說一句:你需要的總試驗和試驗比較裏面,不在外面/裏面。

+0

什麼是?它是一個圖書館嗎?我似乎沒有看到這樣的圖書館。 –

+0

@NamelessKing它自C++ 11以來的標準庫的一部分。它比rand()更適合使用,但是當你需要隨機數時,它完全值得看一看它。 – user463035818

+4

它實際上是''。 –