001package algs15.perc; 002import stdlib.*; 003 004public class PercolationStats { 005 double[] results; 006 007 // perform T independent computational experiments on an N-by-N grid 008 public PercolationStats(int N, int T) { 009 if (N<=0 || T<=0) throw new IllegalArgumentException(); 010 this.results = new double[T]; 011 012 for (int t=0; t<T; t++) { 013 int opened = 0; 014 Percolation perc = new Percolation(N); 015 long numTries = 0; 016 long maxTries = (long) Math.pow(N, 3); // N*N*N does int multiplication 017 while (!perc.percolates() && numTries<maxTries) { 018 int i = StdRandom.uniform(N); 019 int j = StdRandom.uniform(N); 020 if (!perc.isOpen(i, j)) { 021 opened ++; 022 perc.open(i, j); 023 } 024 numTries++; 025 } 026 results[t] = opened / (double) (N*N); 027 } 028 } 029 // sample mean of percolation threshold 030 public double mean() { 031 return StdStats.mean (results); 032 } 033 // sample standard deviation of percolation threshold 034 public double stddev() { 035 return StdStats.stddev (results); 036 } 037 // low end of 95% confidence interval 038 public double confidenceLow() { 039 return StdStats.mean(results) 040 - ((1.96 * StdStats.stddev(results)) 041 / Math.sqrt(results.length)); 042 } 043 // high end of 95% confidence interval 044 public double confidenceHigh() { 045 return StdStats.mean(results) 046 + ((1.96 * StdStats.stddev(results)) 047 / Math.sqrt(results.length)); 048 } 049 050 public static void main(String[] args) { 051 final int MIN = 16; 052 final int MAX = 200000; 053 final int T = 10; 054 double time = 0; 055 double prev = 0; 056 for (int NSquare=MIN; NSquare<=MAX; NSquare+=NSquare) { 057 int N = (int) Math.floor (Math.sqrt (NSquare)); 058 Stopwatch timer = new Stopwatch(); 059 PercolationStats stats = new PercolationStats(N,T); 060 time = timer.elapsedTime (); 061 StdOut.format ("T=%d N=%,5d N^2=%,10d mean=%5.3f confidence=[%5.3f,%5.3f] time=%6.2f ratio=%3.2f\n", 062 T, N, N*N, stats.mean(), stats.confidenceLow(), stats.confidenceHigh(), time, time/prev); 063 prev = time; 064 } 065 } 066}