this exrcise was inspired from the one rahmu
posted
I'm taking introduction to programming at university, our professor gave us a similar exercice (approximate pi using monte carlo analysis)
this is the exercise:
Monte Carlo simulations are techniques that consist of choosing sample experiments at random from a large set and then making deductions on the basis of the probabilities estimated from the result of these experiments. In this problem, you are to implement a Monte Carlo method for estimating the value of π. Consider the first quadrant of a unit circle centered at (0,0). This quarter circle lies inside a unit square. A point with coordinates (x,y) is inside the quarter circle iff x2 + y2 <= 1. The area of the quarter circle region can be estimated by picking, at random, points (x,y) that lie in the unit square, and for each point determining whether the point lies in the region. The fraction of points that fall in the region should give an estimate of π/4 (ratio of the area of the region and the area of the enclosing unit square). Multiplying by 4 gives an estimate of π. Write a program that takes a command line integer parameter N and prints an estimate of π using N random points as described above.
my solution in C++:
#include <iostream>
#include <stdlib.h>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
float rand_x, rand_y;
int N, pointsRegion=0;
cout << "Enter number of points: ";
cin >> N;
for(int i=0; i<N; i++){
rand_x= rand() * 1.0 / RAND_MAX;
rand_y= rand() * 1.0 / RAND_MAX;
if((rand_x*rand_x+rand_y*rand_y)<=1)
{
pointsRegion++;
}
}
cout << "\n\nAn estimatimation of pi with " << N << " random points is: " << (pointsRegion*4.0/N) <<"\n\n";
return 0;
}