C++: Monte Carlo Methods

Bjarne-stroustrup
 


A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value and then makes a sort of “best guess.”

A simple Monte Carlo Simulation can be used to calculate the value for π. If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π/4.

So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π/4.

Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.

For software where the number π is not built-in, we give π to a couple of digits: 3.141592653589793238462643383280

#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<time.h>

using namespace std;
int main(){
	int jmax=1000; // maximum value of HIT number. (Length of output file)
	int imax=1000; // maximum value of random numbers for producing HITs.
	double x,y;    // Coordinates
	int hit;       // storage variable of number of HITs
	srand(time(0));
	for (int j=0;j<jmax;j++){
		hit=0;
		x=0; y=0;
		for(int i=0;i<imax;i++){
			x=double(rand())/double(RAND_MAX);
			y=double(rand())/double(RAND_MAX);
			if(y<=sqrt(1-pow(x,2))) hit+=1; }          //Choosing HITs according to analytic formula of circle
		cout<<""<<4*double(hit)/double(imax)<<endl; }  // Print out Pi number
}

SOURCE

Content is available under GNU Free Documentation License 1.2.