Monte Carlo Problem

Solved.
Last edited on
It's estimating the integral of f(x) by Monte-Carlo methods.

The integral is the area under the curve, so as long as f(x) is always less than one and assuming all the points fall in the unit square (area 1.0), the integral can be estimated as the fraction of points which lie under the curve.

If your function is arcsin(x) / 2 as you have coded, then the exact answer should be
pi/4 - 1/2, or about 0.285398

See what Monte-Carlo simulation will give you. I'll leave you to compute the percentage errors.

Make sure you call srand (once) or you will get the same random numbers every time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;

double a = 0, b = 1;


double f( double x )
{
   return asin( x ) / 2.0;  // function to be integrated - must be less than or equal to 1
}


int main ( ) 
{    
    srand( time( 0 ) );

    int N;
    cout << "Number of simulation points: ";
    cin >> N;

    int counter = 0;
    for ( int n = 1; n <= N; n++)
    {
       double x = a + ( b - a ) * rand() / ( RAND_MAX + 1.0 );
       double y = a + ( b - a ) * rand() / ( RAND_MAX + 1.0 );
       if ( y < f(x) ) counter++;
    }

    cout << "Estimate of integral is " << counter / ( double ) N;
}
}

Number of simulation points: 10000
Estimate of integral is 0.2855
Last edited on
@zelotic,
Please reinstate your original post. People will be disinclined to help you in future if you simply pull down material.

Hmm - it appears you do this a lot.
Last edited on
Topic archived. No new replies allowed.