public class VisualAccumulator
VisualAccumulator() 创建一个累加器
void addDataValue(double val) 添加一个新的数据值
double mean() 所有数据值的平均值
String toString() 对象的字符串表示
所用到的java类有:
【 VisualAccumulator.java 】如下
1 public class VisualAccumulator { 2 3 private double total; 4 private int N; 5 6 public VisualAccumulator(int trials , double max){ 7 8 StdDraw.setXscale(0, trials); 9 StdDraw.setYscale(0, max);10 StdDraw.setPenRadius(.005);11 }12 13 public void addDataValue(double val){14 15 N ++;16 total += val;17 StdDraw.setPenColor(StdDraw.DARK_GRAY);18 StdDraw.point(N, val);19 StdDraw.setPenColor(StdDraw.RED);20 StdDraw.point(N, total/N);21 22 }23 public double mean(){24 return total/N;25 }26 public String toString(){27 return "mean (" + N + "values: )" + String.format("%7.5f", mean());28 }29 }
【TestVisualAccumulator.java 如下 】
1 public class TestVisualAccumulator { 2 3 4 public static void main(String[] args) { 5 6 int T = Integer.parseInt(args[0]); 7 VisualAccumulator a = new VisualAccumulator(T, 1.0); 8 for (int t = 0; t < T; t++) 9 a.addDataValue(StdRandom.uniform());10 StdOut.println(a);11 } 12 }
最后可视化的结果如下图: