Below is the syntax highlighted version of Flip.java
from §2.2 Libraries.
/************************************************************************* * 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 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.show(0); StdDraw.setXscale(0, N); StdDraw.setYscale(0, Math.sqrt(1.0 / N)); while (true) { // flip N coins and tabulate the results for (int j = 0; j < N; j++) { int heads = binomial(N, 0.5); freq[heads]++; } StdDraw.clear(); // plot histogram StdDraw.setPenRadius(1.0 / N); double total = StdStats.sum(freq); for (int i = 0; i <= N; i++) { StdDraw.line(i, 0, i, freq[i] / total); } // plot hypothesis StdDraw.setPenRadius(); 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.phi(i, mean, Math.sqrt(var))); StdDraw.show(50); } } }