Tuesday, July 12, 2011

Value of PI(Monte Carlo Method)

The value of PI is fixed, it is defined in terms of accuracy by estimating depending upon our requirement of accuracy. So, the value of PI should be very accurate for astronomic calculations for planets while we may not need such accuracy for general purpose calculation like to calculate the surface area of football.

There are several methods to calculate the value of PI, but this time, I am quite impressed by the Monte Carlo Method which is clearly explained by my friend Nobal Niraula in his technical blog. So, I am gonna implement that method in java and I have written a sample java code for that.

/**SAMPLE JAVA IMPLEMENTATION FOR CALCULATION OF PI**/
float PI = 0;long hit = 0;long count = 0;
long throws=100000;/*Set how accurate value you need*/
Random random = new Random();
while (count <= throws) {
/* X coordinate*/
float x = random.nextFloat();
/* Y coordinate */
float y = random.nextFloat();
/*Check whether the point lies inside the arc*/
if (Math.sqrt(x * x + y * y) <= 1) {
hit++;
}
count++;
}
/*Calculate the value of PI*/
PI = 4 * (float) hit / count;

The calculation process is rather simple. We assume an inscribed circle inside a unit square, and then generate random number uniformly to get the x and y co-ordinates of the point lying inside the square. We count the number of points which are inside the inscribed circle. For calculation simplicity, we choose only 1/4th of the square and calculation will be as follows: