-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPercolationStats.java
66 lines (52 loc) · 2.03 KB
/
PercolationStats.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private static final double CONFIDENCE_95 = 1.96;
private final double[] thresholds;
// perform independent trials on an n-by-n grid
public PercolationStats(int n, int trials) {
if (n <= 0 || trials <= 0)
throw new IllegalArgumentException();
thresholds = new double[trials];
for (int i = 0; i < trials; i++) {
Percolation p = new Percolation(n);
while (!p.percolates()) {
p.open(StdRandom.uniform(1, n + 1), StdRandom.uniform(1, n + 1));
}
double openSites = (double) (p.numberOfOpenSites());
thresholds[i] = openSites / Math.pow(n, 2);
}
}
// sample mean of percolation threshold
public double mean() {
return StdStats.mean(thresholds);
}
// sample standard deviation of percolation threshold
public double stddev() {
if (thresholds.length == 1)
return Double.NaN;
return StdStats.stddev(thresholds);
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
return mean() - CONFIDENCE_95 * stddev() / Math.sqrt(thresholds.length);
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
return mean() + CONFIDENCE_95 * stddev() / Math.sqrt(thresholds.length);
}
// test client (see below)
public static void main(String[] args) {
PercolationStats pStats = new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
StdOut.print("mean = ");
StdOut.println(pStats.mean());
StdOut.print("stddev = ");
StdOut.println(pStats.stddev());
StdOut.print("95% confidence interval= [");
StdOut.print(pStats.confidenceLo());
StdOut.print(",");
StdOut.print(pStats.confidenceHi());
StdOut.println("]");
}
}