2017-03-13 172 views
0

我試圖計算積分-1到6 sinx dx,但下面給出了-1,14附近的結果,正確的解決方案是-0.41987。錯誤在哪裏?如何讓我的代碼看起來更好,更清晰?使用蒙特卡羅方法計算積分sinx dx?

float MonteCarlo (float a , float b, long long int N) // MonteCarlo(-1,6,200) integral -1 to 6 sinx dx 
                  //N number of random (x,y) 
{ 
    srand(time(NULL)); 
    float positive = 0; // number of points (x,y): 0<y<sinx 
    float negative = 0; // number of points (x,y): sinx<y<0 
    int i; 
    for(i=0;i<N;i++) 
    { 
     float x= ((float) rand())/(float) RAND_MAX*(b-a)+a; 
     float y= ((float) rand())/(float) RAND_MAX*2 -1 ; 
     if(sin(x)>0 && y<sin(x)) positive++; 
     if(sin(x)<0 && y>sin(x)) negative++; 

    } 

    positive=fabs(a-b)*2*(positive/ (float) N);//positive area 
    negative=fabs(a-b)*2*(negative/ (float) N);//negative area 
    return positive-negative; 
} 

回答

0

我想你可以使用MC-集成比較簡單的方法:你首先要計算你的樣品(= SUM/N)的期望,然後用(B-A)相乘。但在這種情況下,您需要許多(> 1e6)樣本才能獲得精確的結果。

試試這個:

// MonteCarlo(-1,6,200) integral -1 to 6 sinx dx     
float MonteCarlo (float a , float b, long long int N)  
{ 
    srand(time(NULL)); 
    int i; 
    float sum = 0; 
    for(i=0;i<N;i++) 
    { 
     x= (float) rand()*(b-a) + a; 
     sum = sum + sin(x); 
    } 

    return sum/N * (b-a); 
}