Estimate Pi with Java Program
Estimating Pi Using the Monte Carlo Method
Pi is an important mathematical constant, and it is often useful to estimate its value. The Monte Carlo method is a non-trivial way of doing this, and a Java program can be used to easily estimate Pi’s value with a fairly high degree of accuracy.
How Does It Work?
The idea behind the Monte Carlo method is relatively simple. We start by imagining a square (with sides of length 2 units) which contains a circle (with radius 1 unit). Because of the properties of circles, we know that the area of the circle will be π units2. Dividing the area of the circle by the area of the square gives us the following equation:
π/4 = (Area of the circle)/(Area of the square)
We can solve for π by simply multiplying both sides of the equation by 4. In the Monte Carlo method, we use random points to approximate the area of the circle and the area of the square. By randomly generating points inside the square, we can approximate the ratio of points inside the circle to points outside the circle, which is equivalent to the ratio of the area of the circle to the area of the square.
Creating a Java Program
To create a Java program that estimates Pi using the Monte Carlo method we need to start by creating a class. This class will contain all the necessary data and methods to generate the random points, and keep track of the points inside the circle. The code should look something like this:
public class MonteCarloPi {
// code goes here
}
Now that we have our class, we need to define two instance variables which will be used to store the number of points inside the circle and the number of points outside the circle. The code looks something like this:
public class MonteCarloPi {
private int insideCount;
private int outsideCount;
// code goes here
}
Now that we have our instance variables defined, we need to create a method that will generate the random points and keep track of the points inside the circle. This method should take two arguments which are the number of points to generate, and the radius of the circle. The code looks like this:
public void generateRandomPoints(int numPoints, double radius) {
for(int i = 0; i < numPoints; i++) {
// generate random point
double x = Math.random() * 2 - 1;
double y = Math.random() * 2 - 1;
// check if point is inside the circle
double d = Math.sqrt(x*x + y*y);
if(d <= radius) {
insideCount++;
} else {
outsideCount++;
}
}
}
And finally, we need to create a method that will compute the estimated value of Pi based on the points generated. This method should look something like this:
public double computePi() {
return 4.0 * (insideCount / (double) (insideCount + outsideCount));
}
With these pieces in place, we now have a complete Java program that can be used to estimate the value of Pi using the Monte Carlo method.