PercolationStats

PercolationStats


 1public class PercolationStats {
 2
 3    private double[] res;
 4
 5    // perform independent trials on an n-by-n grid
 6    public PercolationStats(int n, int trials) {
 7        if (n <= 0 || trials <= 0)
 8            throw new IllegalArgumentException();
 9        res = new double[trials];
10        for (int i = 0; i < trials; i++) {
11            Percolation percolation = new Percolation(n);
12            while(!percolation.percolates()){
13                int row = StdRandom.uniformInt(1, n + 1);
14                int col = StdRandom.uniformInt(1, n + 1);
15                percolation.open(row, col);
16            }
17            res[i] = percolation.numberOfOpenSites() / (n * n * 1.0e0);
18        }
19    }
20
21    // sample mean of percolation threshold
22    public double mean() {
23        return StdStats.mean(res);
24    }
25
26    // sample standard deviation of percolation threshold
27    public double stddev() {
28        return StdStats.stddev(res);
29    }
30
31    // low endpoint of 95% confidence interval
32    public double confidenceLo() {
33        return StdStats.min(res);
34    }
35
36    // high endpoint of 95% confidence interval
37    public double confidenceHi() {
38        return StdStats.max(res);
39    }
40
41    // test client (see below)
42    public static void main(String[] args) {
43//        int  n = Integer.parseInt(args[0]);
44//        int trials = Integer.parseInt(args[1]);
45         int n = StdIn.readInt();
46         int trials = StdIn.readInt();
47
48        PercolationStats ps = new PercolationStats(n, trials);
49        StdOut.printf("mean = %.12f\t\n", ps.mean());
50        StdOut.printf("stddev = %.12f\t\n", ps.stddev());
51        StdOut.printf("95%% confidence interval = [%.12f, %.12f]\n", ps.confidenceLo(), ps.confidenceHi());
52    }
53}