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