/****************************************************************************** * Compilation: javac Flip.java * Execution: java Flip n * Dependencies: StdDraw.java * * Each experiment consists of flipping n fair coins. Plots (in real time) * a histogram of the number of times exactly i of the n coins are heads. * * % java Flip 32 * * % java Flip 64 * * % java Flip 128 * ******************************************************************************/ public class Flip { // number of heads when flipping n coins, each with prob p of heads public static int binomial(int n, double p) { int heads = 0; for (int j = 0; j < n; j++) if (StdRandom.bernoulli(p)) heads++; return heads; } public static void main(String[] args) { int n = Integer.parseInt(args[0]); // number of coins to flip int[] freq = new int[n+1]; // freq[i] = # times you get i heads StdDraw.setCanvasSize(1000, 600); StdDraw.enableDoubleBuffering(); StdDraw.setXscale(0, n); StdDraw.setYscale(0, Math.sqrt(1.0 / n)); int count = 0; while (true) { // flip n coins and tabulate the results for (int j = 0; j < n; j++) { int heads = binomial(n, 0.5); freq[heads]++; count++; } StdDraw.clear(); // plot histogram StdDraw.setPenRadius(1.0 / n); for (int i = 0; i <= n; i++) { StdDraw.line(i, 0, i, 1.0 * freq[i] / count); } // plot hypothesis StdDraw.resetPenRadius(); double mean = 0.5 * n; double var = 0.25 * n; for (double i = 0.0; i < n; i += n/1000.0) StdDraw.point(i, Gaussian.pdf(i, mean, Math.sqrt(var))); StdDraw.show(); StdDraw.pause(50); } } }