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.
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
usingnamespace 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