-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
76 lines (63 loc) · 2.4 KB
/
PercolationStats.java
File metadata and controls
76 lines (63 loc) · 2.4 KB
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
67
68
69
70
71
72
73
74
75
76
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private static final double CONFIDENCE_95 = 1.96;
private double meanVal = -1;
private double stddevVal = -1;
private final double[] results;
// perform trials independent experiments on an n-by-n grid
public PercolationStats(int n, int trials) {
if (n <= 0 || trials <= 0) {
throw new IllegalArgumentException();
}
results = new double[trials];
for (int i = 0; i < trials; i++) {
Percolation percolation = new Percolation(n);
while (!percolation.percolates()) {
int row = StdRandom.uniform(n) + 1;
int col = StdRandom.uniform(n) + 1;
if (!percolation.isOpen(row, col)) {
percolation.open(row, col);
}
}
results[i] = (double) percolation.numberOfOpenSites() / (n*n);
}
}
// sample mean of percolation threshold
public double mean() {
if (meanVal == -1)
this.meanVal = StdStats.mean(results);
return meanVal;
}
// sample standard deviation of percolation threshold
public double stddev() {
if (stddevVal == -1)
this.stddevVal = StdStats.stddev(results);
return stddevVal;
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
if (meanVal == -1)
mean();
if (stddevVal == -1)
stddev();
return meanVal - (CONFIDENCE_95 * stddevVal / Math.sqrt(results.length));
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
if (meanVal == -1)
mean();
if (stddevVal == -1)
stddev();
return meanVal + (CONFIDENCE_95 * stddevVal / Math.sqrt(results.length));
}
// test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
PercolationStats percolationStats = new PercolationStats(n, trials);
System.out.println("mean = " + percolationStats.mean());
System.out.println("stddev = " + percolationStats.stddev());
System.out.println("95% confidence interval = [" + percolationStats.confidenceLo() + ", " + percolationStats.confidenceHi() + "]");
}
}