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