Created
March 29, 2019 02:22
-
-
Save wyukawa/fa6332f9239cc0a2ee2f98c48bb63cd7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import edu.princeton.cs.algs4.StdRandom; | |
import edu.princeton.cs.algs4.StdStats; | |
import edu.princeton.cs.algs4.Stopwatch; | |
public class PercolationStats { | |
private final double mean; | |
private final double stddev; | |
private final double confidenceLo; | |
private final double confidenceHi; | |
// perform trials independent experiments on an n-by-n grid | |
public PercolationStats(int n, int trials) { | |
if (n <= 0 || trials <= 0) { | |
throw new IllegalArgumentException("n or trials is illegal"); | |
} | |
System.out.println(String.format("n=%d, trials=%d", n, trials)); | |
double[] thresholds = new double[trials]; | |
for (int i = 0; i < trials; i++) { | |
Percolation percolation = new Percolation(n); | |
while (!percolation.percolates()) { | |
percolation.open(StdRandom.uniform(1, n + 1), StdRandom.uniform(1, n + 1)); | |
} | |
double threshold = (double) percolation.numberOfOpenSites() / (n * n); | |
thresholds[i] = threshold; | |
} | |
mean = StdStats.mean(thresholds); | |
stddev = trials == 1 ? Double.NaN : StdStats.stddev(thresholds); | |
confidenceLo = mean - 1.96 * stddev / Math.sqrt(trials); | |
confidenceHi = mean + 1.96 * stddev / Math.sqrt(trials); | |
} | |
// sample mean of percolation threshold | |
public double mean() { | |
return mean; | |
} | |
// sample standard deviation of percolation threshold | |
public double stddev() { | |
return stddev; | |
} | |
// low endpoint of 95% confidence interval | |
public double confidenceLo() { | |
return confidenceLo; | |
} | |
// high endpoint of 95% confidence interval | |
public double confidenceHi() { | |
return confidenceHi; | |
} | |
// test client (described below) | |
public static void main(String[] args) { | |
Stopwatch stopwatch = new Stopwatch(); | |
PercolationStats percolationStats = new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1])); | |
System.out.println(String.format("mean = %f", percolationStats.mean)); | |
System.out.println(String.format("stddev = %f", percolationStats.stddev)); | |
System.out.println(String.format("95%% confidence interval = [%f, %f]", percolationStats.confidenceLo, percolationStats.confidenceHi)); | |
System.out.println(String.format("elapsedTime=%f", stopwatch.elapsedTime())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment