// CS 1538 Fall 2009 // Simple demonstration of Monte Carlo simulation to determine the area // of a circle. Looking at it another way, we could also use this // simulation to estimate the value of pi (since a unit circle is used). import java.util.*; public class Circle { public static void main(String [] args) { int iter = Integer.parseInt(args[0]); Random r = new Random(); int hits = 0; for (int i = 0; i < iter; i++) { double rX = 2*r.nextDouble() - 1.0; // Gen. random x double rY = 2*r.nextDouble() - 1.0; // Gen. random y double dist = Math.sqrt(rX*rX + rY*rY); // Get distance if (dist <= 1.0) // If distance is <= 1 from the origin hits++; // the point is within the circle } double ratio = (double)hits/iter; // Ratio of areas System.out.println("The ratio is " + ratio); double area = ratio * 4.0; // We know the area of the square is 4.0 System.out.println("The area is " + area); } }