// This program computes an approximation to pi using what is known as a // "Monte Carlo technique." The program picks random points in the unit // square and counts how many are in the unit circle. The probability of // falling in the unit circle is pi/4, so we multiply the ratio by 4 to get // an approximation to pi. import java.util.*; public class ComputePi { public static void main(String[] args) { Scanner console = new Scanner(System.in); Random r = new Random(); System.out.print("times? "); int times = console.nextInt(); int count = 0; for (int i = 1; i <= times; i++) { double x = r.nextDouble(); double y = r.nextDouble(); if (x * x + y * y <= 1) { count++; } } double estimate = 4.0 * (double) count / (double) times; System.out.println("estimate = " + estimate); System.out.println("let's cheat, pi = " + Math.PI); } }