Friday, October 17, 2008

PI approximation with Monte Carlo Simulation

/**
*
* PI approximation using Monte Carlo Simulation. Draw a square of
* unit area on the ground, then inscribe a circle within it. Now, scatter some
* small objects (for example, grains of rice or sand) throughout the square. If
* the objects are scattered uniformly, then the proportion of objects within
* the circle vs objects within the square should be approximately PI/4, which
* is the ratio of the circle's area to the square's area. Thus, if we count the
* number of objects in the circle, multiply by four, and divide by the total
* number of objects in the square (including those in the circle), we get an
* approximation to PI. (
http://en.wikipedia.org/wiki/Monte_Carlo_method)
*
*/
public class PiEstimationWithMonteCarlo {

public double estimatePI(long numberSample) {
long numberInCircle = 0;
double pi = 0.0;

for (int i = 0; i < numberSample; i++) {
double x = generateRandomNumber();
double y = generateRandomNumber();
if (insideCircle(x, y))
numberInCircle++;
}
pi = (numberInCircle * 4) / ((double) numberSample);
return pi;
}

private boolean insideCircle(double x, double y) {
double distance = x * x + y * y;
if (distance > 1) {
// out of circle
return false;
}
return true;
}

private double generateRandomNumber() {
// between -1 and 1
return Math.random() * 2 - 1;
}

public static void main(String args[]) {
PiEstimationWithMonteCarlo piEstimator = new PiEstimationWithMonteCarlo();
double pi = piEstimator.estimatePI(5000000);
System.out.println("PI=" + pi);
}
}

No comments: