// LoopsMonteCarlo Example // Module: montecarlo // Estimate the value of pi by generating // random pairs (x, y) where x and y in [0,1.0). // The probability of (x, y) lying in the circle // with center (0,5, 0,5) and radius 1 is pi/4. import java.util.Random; public class Main { // Define number of rolls. public final static int NUM_DART_THROWS = 10000000; public static void main(String[] args) { // Define random number generator Random rand = new Random( ); // Define variables. double x, y, dist; int numSuccesses = 0; // Throw darts. Count as success only throws // in the circle with center (0,5, 0,5) and radius 1. for(int i = 1; i <= NUM_DART_THROWS; i++) { x = rand.nextDouble( ); y = rand.nextDouble( ); dist = Math.sqrt(Math.pow(x - 0.5, 2.0) + Math.pow(y - 0.5, 2.0)); if (dist <= 0.5) { numSuccesses++; } } // Print result System.out.print("Estimate for pi: "); System.out.println(4.0 * ((double) numSuccesses) / NUM_DART_THROWS); } }