To calculate value of π using Monte-Carlo simulations.
Pi is the famous circle number approximately given by 3.14159...
It is the area of the unit circle (i.e. the circle with radius 1) or half the perimeter of the unit circle.
Monte-Carlo Simulations are experiments or computational algorithms that rely on sampling of random numbers. An experiment or a simulation of random numbers is repeated a large number of times to estimate something that may be determined deterministically as well (such as π, as it is a deterministic number, i.e. it does not depend on randomness or chance).
Monte-Carlo Simulations are used whenever calculating something in a deterministic fashion is too computationally expensive or not feasible anymore. Or when you're just too lazy to compute something exactly. And sometimes it is not even necessary to use Monte-Carlo Simulations and the only reason to use them is to show how beautiful Math and Probabilities can be.
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<iomanip>
using namespace std;
int main()
{
cout.setf(ios::fixed);
cout<<"------------------------------------------------------------"<<endl;
cout<<"x"<<setw(15)<<"y"<<setw(14)<<"circle_pt"<<setw(12)<<"square_pt"<<setw(10)<<"pi"<<endl;
cout<<"------------------------------------------------------------"<<endl;
int i, intrval=1000;
int cr_pt=0, sq_pt=0;
double x,y,pi,r;
srand(time(NULL));
for (i=0; (i<intrval); i++)
{
x=double((1+rand()%intrval))/intrval;
y=double((1+rand()%intrval))/intrval;
r= x*x + y*y;
if (r<=1)
cr_pt++;
sq_pt++;
pi=double(4*cr_pt)/sq_pt;
cout<<x<<setw(10)<<y<<setw(10)<<cr_pt<<setw(10)<<sq_pt<<setw(15)<<pi<<endl;
}
return 0;
}
Take Observations from simulator and tabulate it for π and Interval.
Plot a graph also. (π vs Interval).
The value of π is ----> 3.14159265359
But, we take π approximately equal to 3.14.
Any result coming in range 3.13 to 3.15 may be considered as successful simulation of the method.