首页 > 代码库 > [Algorithms(Princeton)] Week1 - PercolationStats
[Algorithms(Princeton)] Week1 - PercolationStats
1 public class PercolationStats { 2 3 private int N; 4 private int T; 5 private double[] results; 6 7 public PercolationStats(int N, int T) { 8 if (N <= 0 || T <= 0) { 9 throw new java.lang.IllegalArgumentException(10 "N or T must be greater than 0");11 }12 13 this.N = N;14 this.T = T;15 results = new double[T];16 17 for (int t = 0; t < T; t++) {18 results[t] = run();19 }20 }21 22 private double run() {23 Percolation percolation = new Percolation(N);24 double count = 0;25 26 while (!percolation.percolates()) {27 count++;28 29 // pick a random site30 // (N+1 because second value to uniform is exclusive)31 int i = StdRandom.uniform(1, N + 1);32 int j = StdRandom.uniform(1, N + 1);33 34 // generate new random sites until a blocked one is found35 while (percolation.isOpen(i, j)) {36 37 i = StdRandom.uniform(1, N + 1);38 j = StdRandom.uniform(1, N + 1);39 40 }41 42 // open that site43 percolation.open(i, j);44 45 }46 return count / (N * N); // percolation threshold estimate47 }48 49 public double mean() {50 return StdStats.mean(results);51 }52 53 public double stddev() {54 return StdStats.stddev(results);55 }56 57 public double confidenceHi() {58 return mean() - 1.96 * stddev() / Math.sqrt(T);59 }60 61 public double confidenceLo() {62 return mean() + 1.96 * stddev() / Math.sqrt(T);63 }64 65 public static void main(String[] args) {66 67 int N;68 int T;69 70 if (args.length == 0) {71 N = 100;72 T = 10;73 } else {74 N = Integer.parseInt(args[0]);75 T = Integer.parseInt(args[1]);76 }77 78 // double startTime = System.nanoTime();79 PercolationStats stats = new PercolationStats(N, T);80 81 double confidenceLow = stats.confidenceHi();82 double confidenceHigh = stats.confidenceLo();83 84 System.out.println("mean = " + stats.mean());85 System.out.println("stddev = " + stats.stddev());86 System.out.println("95% confidence interval = " + confidenceLow + ", "87 + confidenceHigh);88 89 // performance measuring90 // double endTime = System.nanoTime();91 // System.out.println("time cost: " + (endTime - startTime));92 93 }94 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。