// Compute pi by dropping balls onto a unit square and counting // the number that land in the inscribe square. public class Pi { public static void main (String[] args) { final long NUM_BALLS = (long)1.0E11; // could read this in long inside = 0; // number in circle double x, y; System.out.println(" Dropped Inside Estimate of pi"); for (long dropped=1; dropped<=NUM_BALLS; dropped++) { x = Math.random(); y = Math.random(); if (dist(x,y,0.5,0.5)<0.5) inside++; if (interesting(dropped)) System.out.printf("%12d%12d%14.10f\n", dropped,inside,estimate(dropped,inside)); } } public static double dist(double x1, double y1, double x2, double y2) { return Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); } public static double estimate(long dropped, long inside) { return 4.0*((double)inside / (double)dropped); } public static boolean interesting(long x) { double l10 = Math.log10(x); // Powers of 10 = l10 an integer return Math.abs(l10 - Math.rint(l10)) < 1.0E-14; } } // Local Variables: // c-basic-offset: 2 // indent-tabs-mode: nil // compile-command: "javac Pi.java && time java Pi" // End: