//----------------------------------------------------------------------- // Miranda Moore // COS488/MAT474 // Problem Set 7, Q2 //----------------------------------------------------------------------- // The command "java Ehrenfest k t" // simulates t trials of the Ehrenfest model with 1000 balls and 10^k // steps, and plots a histogram of the distribution of the number of // balls in chamber A at the end of each trial. // The resulting histogram has its x-axis ranging from 0 to 1000, // and the heights of the bars show the relative likelihood of each // outcome. //----------------------------------------------------------------------- public class Ehrenfest { public static final int N = 1000; // number of balls // adapted from StdStats.java // plots a histogram of the data public static void histogram(double[] a, int trials) { StdDraw.setCanvasSize(700, 100); StdDraw.setXscale(0, N+1); StdDraw.setYscale(0, .06); for (int i = 0; i <= N ; i++) { StdDraw.filledRectangle(i+.5, a[i]/(2*trials), 0.5, a[i]/(2*trials)); } } // simulate one trial with n steps public static int trial(int n) { int a = N; // # balls in urn A int b = 0; // # balls in urn B int i; // a random integer // simulate the n steps. // at each step, we choose a random integer, // and move the corresponding ball for (int l = 0; l < n; l++) { i = StdRandom.uniform(N); if (i < a) {a--; b++;} else {b--; a++;} } // return the number of balls in urn A at the end of n steps return a; } public static void main(String[] args) { int pow = Integer.parseInt(args[0]); int n = (int) Math.pow(10, pow); // number of steps // array keeping track of the frequency of each result double[] freq = new double[N+1]; int trials = Integer.parseInt(args[1]); // number of trials for (int k = 0; k < trials; k++) { freq[trial(n)]++; } histogram(freq, trials); } }