-
Notifications
You must be signed in to change notification settings - Fork 0
/
PercolationStats.java
65 lines (56 loc) · 2.21 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
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 int experimentsCount;
private final double[] fractions;
// perform independent trials on an n-by-n grid
public PercolationStats(int n, int trials) {
if (n <= 0 || trials <= 0) {
throw new IllegalArgumentException("Given N <= 0 || T <= 0");
}
experimentsCount = trials;
fractions = new double[experimentsCount];
for (int expNum = 0; expNum < experimentsCount; expNum++) {
Percolation pr = new Percolation(n);
int openedSites = 0;
while (!pr.percolates()) {
int i = StdRandom.uniform(1, n + 1);
int j = StdRandom.uniform(1, n + 1);
if (!pr.isOpen(i, j)) {
pr.open(i, j);
openedSites++;
}
}
double fraction = (double) openedSites / (n * n);
fractions[expNum] = fraction;
}
}
// sample mean of percolation threshold
public double mean() {
return StdStats.mean(fractions);
}
// sample standard deviation of percolation threshold
public double stddev() {
return StdStats.stddev(fractions);
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
return mean() - ((CONFIDENCE_95 * stddev()) / Math.sqrt(experimentsCount));
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
return mean() + ((CONFIDENCE_95 * stddev()) / Math.sqrt(experimentsCount));
}
// test client (see below)
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int t = Integer.parseInt(args[1]);
PercolationStats ps = new PercolationStats(n, t);
String confidence = ps.confidenceLo() + ", " + ps.confidenceHi();
StdOut.println("mean = " + ps.mean());
StdOut.println("stddev = " + ps.stddev());
StdOut.println("95% confidence interval = " + confidence);
}
}