累加器的方差。以下代码为Accumulator类添加了var()和stddev()方法,它们计算了addDataValue()的方法的参数的方远大和标准差,验证这段代码。
/** * Description : * Author : mn@furzoom.com * Date : Sep 26, 2016 10:35:26 AM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs; /** * ClassName : Accumulator <br> * Function : TODO ADD FUNCTION. <br> * date : Sep 26, 2016 10:35:26 AM <br> * * @version */ public class Accumulator { private double m; private double s; private int n; public void addDataValue(double val) { n++; s = s + 1.0 * (n - 1) / n * (val - m) * (val - m); m = m + (val - m) / n; } public double mean() { return m; } public double var() { return s / (n - 1); } public double stddev() { return Math.sqrt(this.var()); } public String toString() { return String.format("%.5f %.5f", mean(), stddev()); } }
测试数据:
/** * Description : * Author : mn@furzoom.com * Date : Sep 27, 2016 3:46:18 PM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.algs.ch102; import com.furzoom.lab.algs.Accumulator; /** * ClassName : E10218 <br> * Function : TODO ADD FUNCTION. <br> * date : Sep 27, 2016 3:46:18 PM <br> * * @version */ public class E10218 { public static void main(String[] args) { Accumulator acc = new Accumulator(); acc.addDataValue(7); acc.addDataValue(8); acc.addDataValue(9); acc.addDataValue(10); System.out.println(acc); } }