2017-03-13 13 views
0

Ich versuche, integral -1 bis 6 sinx dx zu berechnen, aber das folgende ergibt Ergebnis nahe -1,14 und die richtige Lösung ist -0,41987. Wo ist der Fehler? Wie kann ich meinen Code besser und klarer gestalten?Integral sinx dx mit Monte-Carlo-Methode berechnen?

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

Antwort

0

Ich denke, dass Sie einen einfacheren Ansatz für MC-Integration verwenden können: Sie müssen zuerst die Erwartung Ihrer Proben berechnen (= Summe/N) und multiplizieren sie dann mit (b-a). In diesem Fall benötigen Sie jedoch viele (> 1e6) Samples, um ein genaues Ergebnis zu erhalten.

Versuchen Sie folgendes:

// 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); 
} 
Verwandte Themen