/* A Monte Carlo method to compute the value of the mathematical constant pi. Simulate by "throwing darts" at quarter circle of radius 1.0. Invoke the program as follows java ComputePi 100 where 100 is the number of trials. */ import java.util.Random; public final class ComputePi2 { private static final Random RNG = new Random (Long.getLong ("seed", System.nanoTime())); public static void main (final String[] args) { final int trials = Integer.parseInt (args[0]); // number of trials int count=0; for (int t=0; t<trials; t++) { // Select a point in the unit square with uniform probablity. final double x = RNG.nextDouble(); // 0.0 to 1.0 final double y = RNG.nextDouble(); // 0.0 to 1.0 // Remember if the point falls in the quarter circle. } /* The ratio of the area of the quarter circle to the unit square is count/trials -- the probability the "dart" lands in the quarter cirle. This ratio is pi/4.0 */ final double pi = /* */ System.out.printf ("estimate=%8.6f pi=%8.6f; trials=%d%n", pi, Math.PI, trials); } }