// CSE 142 Lecture 12 // Random, boolean // Calculates Pi using Random numbers. // Picture a circle of radius 1 inside of a square. The circle has area Pi * radius^2. // Since our circle has radius 1, it has area Pi. The square has area 4. // If we pick a bunch of random points in the square, we can calculate Pi // by using the ratio of points that fall inside the circle to the number of points we picked. import java.util.*; // for Random import java.awt.*; // for Graphics, Color public class Pi { // How far away from actual Pi our calculation is allowed to be. public static final double ERROR = 0.00000001; // The size to draw the representation of our calculations at public static final int SIZE = 400; public static void main(String[] args) { DrawingPanel p = new DrawingPanel(SIZE, SIZE); Graphics g = p.getGraphics(); Random r = new Random(1342425406762L); // ~66K points //Random r = new Random(1342424639929L); // ~1.3M points //Random r = new Random(1342425440783L); // ~8M points //Random r = new Random(1342425511441L); // ~350M points (this will take a long time) double pi = 0; int n = 0; int inside = 0; // Keep going until the difference between Pi and our calculation is less than // than or equal to the acceptable error. while (Math.abs(Math.PI - pi) > ERROR) { // We're only going to use the upper right quarter of the circle and square // described earlier. Symmetry makes this work out. // Pick a random point in a 1 by 1 square. double x = r.nextDouble(); double y = r.nextDouble(); // See if this point would be within a radius 1 circle. if (Math.sqrt(x * x + y * y) <= 1) { inside++; g.setColor(Color.BLUE); } else { g.setColor(Color.RED); } g.drawRect((int)(x * SIZE), (int)(y * SIZE), 1, 1); n++; // Pi is the ratio of points inside the circle to points inside the square. pi = 4.0 * inside / n; // Limit the amount of printing because it slows down the computation. if (n % 1000 == 0) { System.out.println("Step " + n + ", Pi = " + pi); } } System.out.println("Step " + n + ", Pi = " + pi); System.out.println(); System.out.println("We calculated Pi = " + pi); System.out.println("Pi actually = " + Math.PI); System.out.println("Error = " + Math.abs(Math.PI - pi)); } }