Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  PercolationStats
Language: JAVA
Code:
public class PercolationStats {
     public PercolationStats(int N, int T) {   
          if (N <= 0 || T <= 0) throw java.lang.IllegalArgumentException;
          this.N = N;
          this.T = T;
          double x[] = new double[T];
          
          mean = 0.0;
          stddev = 0.0;
          
          long seed = 1316600602069;
          int greedSize = N * N;
          for (int i = 0; i < T; i++) {
               Percolation oPerc = new Percolation(N);
               StdRandom.setSeed(seed);
               int opened = 0;
               while (!oPerc.percolate() && opened < greedSize) {
                    int row = 0, col = 0;
                    do {
                         row = StdRandom.uniform(N+1);
                         col = StdRandom.uniform(N+1);
                    } while (!oPerc.isOpen(row, col));
                    oPerc.open(row, col);
                    opened++;
               }
               x[i] = opened / (greedSize);
               mean += x[i]
               seed += 111;
          }
          mean /= T;
          for (int i = 0; i < T; i++) 
               stddev += (x[i] - mean) * (x[i] - mean);
          stddev /= (T - 1);
          stddev = Math.sqrt(stddev);
     }
     
     public double mean() {
          return mean;
     }
     
     public double stddev() {
          return stddev;
     }
     
     public static void main(String[] args) {
          N = Integer.parseInt(args[0]);
          T = Integer.parseInt(args[1]);
          
          PercolationStats ps = new PercolationStats(N, T);
          StdOut.printf("mean =                    ");
          StdOut.printf("%18.16f", ps.mean());
          StdOut.println();
          StdOut.pringf("stddev =                  ");
          StdOut.printf("%18.16f", ps.stddev());
          StdOut.println();
          double left = ps.mean() - (1.96 * ps.stddev()) / Math.sqrt(T),
                 right = ps.mean() - (1.96 * ps.stddev()) / Math.sqrt(T);
          StdOut.printf("95% confidence interval = ");
          StdOut.printf("%18.16f", left);
          StdOut.printf(", ");
          StdOut.printf("%18.16f", right);
          StdOut.println();
     }

     private int N;
     private int T;
     
     double mean;
     double stdddev;
}
Comments: