blob: 9f7a0e996b89f465eb08f3f743966d249a92415b (
plain)
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
|
/* vim: set expandtab tabstop=4 shiftwidth=4 : */
public class PercolationStats
{
private double[] results;
private double mean;
private double stddev;
private int N;
// perform T independent computational experiments on an N-by-N grid
public PercolationStats(int N, int T)
{
if (N < 1 || T < 1)
throw new java.lang.IllegalArgumentException("received value < 1");
this.N = N;
results = new double[T];
int n = N*N;
for (int t = 0; t < T; t++)
{
double c = 0;
Percolation p = new Percolation(N);
do
{
int i = StdRandom.uniform(1, N+1);
int j = StdRandom.uniform(1, N+1);
if (!p.isOpen(i, j)) {
p.open(i, j);
c += 1;
}
}
while(!p.percolates());
results[t] = c / n;
}
mean = StdStats.mean(results);
stddev = StdStats.stddev(results);
}
// sample mean of percolation threshold
public double mean()
{
return mean;
}
// sample standard deviation of percolation threshold
public double stddev()
{
return stddev;
}
// returns lower bound of the 95% confidence interval
public double confidenceLo()
{
return mean - 1.96*stddev/Math.sqrt(N);
}
// returns upper bound of the 95% confidence interval
public double confidenceHi()
{
return mean + 1.96*stddev/Math.sqrt(N);
}
// test client
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
PercolationStats stats = new PercolationStats(N, T);
System.out.printf("mean = %.16f\n", stats.mean());
System.out.printf("stddev = %.16f\n", stats.stddev());
System.out.printf("95%% confidence interval = %.16f, %.16f\n\n",
stats.confidenceLo(), stats.confidenceHi());
}
}
|