Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 times;
- private final double stddev;
- private final double mean;
- public PercolationStats(int n, int times) {
- this.times = times;
- if (n <= 0 || times <= 0)
- throw new IllegalArgumentException("not valid indices");
- double [] thresholds = new double[times];
- // runs times times the monteCarlo simulation
- for (int i = 0; i < times; i++) {
- thresholds[i] = monteCarlo(n);
- }
- mean = StdStats.mean(thresholds);
- stddev = StdStats.stddev(thresholds);
- }
- public double mean() {
- return mean;
- }
- public double stddev() {
- return stddev;
- }
- public double confidenceLo() {
- return (mean - ((CONFIDENCE_95 * stddev) / Math.sqrt(times)));
- }
- public double confidenceHi() {
- return (mean + ((CONFIDENCE_95 * stddev) / Math.sqrt(times)));
- }
- private double monteCarlo(int n) {
- Percolation percolation = new Percolation(n);
- int p;
- int q;
- int opened = 0;
- // as long as the system does not percolate whe open a new random site
- while (!percolation.percolates()) {
- p = StdRandom.uniform(1, n + 1); // a random site index in a n size grid + 1 as last item is excluded
- q = StdRandom.uniform(1, n + 1); // an other random site
- if (!percolation.isOpen(p, q)) {
- percolation.open(p, q);
- opened++;
- }
- }
- return opened * 1.0 / (n * n);
- }
- 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.println("mean = " + stats.mean);
- System.out.println("stddev = " + stats.stddev);
- System.out.println("95% confidence interval = [" + stats.confidenceLo()
- + ", " + stats.confidenceHi() + " ]");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement