-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPercolationStats.java
77 lines (64 loc) · 2.25 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
67
68
69
70
71
72
73
74
75
76
77
import java.util.Random;
public class PercolationStats {
int gridSize;
int results[];
int noOfTests;
public PercolationStats(int N, int T) // perform T independent computational experiments on an N-by-N grid
{
gridSize = N;
noOfTests = T;
results = new int[T];
for(int i = 0; i < T; i++)
results[i] = execute();
}
private int execute()
{
Percolation obj = new Percolation(gridSize);
while(!obj.percolates())
{
obj.open(new Random().nextInt(gridSize) + 1, new Random().nextInt(gridSize) + 1);
}
// obj.display();
return obj.count;
}
public void display()
{
for(int i = 0; i < noOfTests; i++)
System.out.println(results[i]);
}
public double mean() // sample mean of percolation threshold
{
Integer sum = 0;
for(int result : results)
sum += result;
return sum/noOfTests;
}
public double stddev() // sample sPercolationStatsimport tandard deviation of percolation threshold
{
double mean = mean();
double stddev = 0;
for(int result : results)
stddev += Math.pow(result - mean, 2);
return Math.sqrt(stddev);
}
public double confidenceLo() // returns lower bound of the 95% confidence interval
{
double mean = mean();
double stddev = stddev();
return mean - (1.96 * stddev / Math.sqrt(noOfTests));
}
public double confidenceHi() // returns upper bound of the 95% confidence interval
{
double mean = mean();
double stddev = stddev();
return mean + (1.96 * stddev / Math.sqrt(noOfTests));
}
public static void main(String[] args) // test client, described below
{
PercolationStats pobj = new PercolationStats( Integer.parseInt(args[0]), Integer.parseInt(args[1]));
//PercolationStats pobj = new PercolationStats(5,3);
System.out.println("mean = " + pobj.mean()/Integer.parseInt(args[0]) / Integer.parseInt(args[0]));
System.out.println("stddev = " + pobj.stddev());
System.out.println("95% confidence interval = " + pobj.confidenceLo() + ", " + pobj.confidenceHi());
}
}