1  import java.util.Random;
  2  
  3  /**
  4     This program computes an estimate of pi by simulating dart throws onto a square.
  5  */
  6  public class MonteCarlo
  7  {
  8     public static void main(String[] args)
  9     {  
 10        final int TRIES = 10000;
 11        Random generator = new Random();
 12  
 13        int hits = 0;
 14        for (int i = 1; i <= TRIES; i++)
 15        {  
 16           // Generate two random numbers between -1 and 1
 17  
 18           double r = generator.nextDouble();
 19           double x = -1 + 2 * r; 
 20           r = generator.nextDouble();
 21           double y = -1 + 2 * r;         
 22  
 23           // Check whether the point lies in the unit circle
 24  
 25           if (x * x + y * y <= 1) { hits++; }
 26        }
 27  
 28        /*
 29           The ratio hits / tries is approximately the same as the ratio 
 30           circle area / square area = pi / 4
 31        */        
 32  
 33        double piEstimate = 4.0 * hits / TRIES;
 34        System.out.println("Estimate for pi: " + piEstimate);
 35     }
 36  }