public class Pi { public static void main(String[] args) { int n = 1000000; int count = 0; for (int i = 0; i < n; ++i) { //random number >= 0.0 and < 1.0 final double x = Math.random(); final double y = Math.random(); final double distance = Math.hypot(x, y); //Could also say distance = Math.sqrt(x * x + y * y); if (distance < 1) { ++count; } } final double pi = 4.0 * count / n; System.out.println("count = " + count + " out of " + n); System.out.println("computed pi = " + pi); System.out.println("actual pi = " + Math.PI); System.out.println("error = " + Math.abs(Math.PI - pi)); } }