首页  

增量方差java实现     所属分类 java 浏览量 105
增量方差 不需要全量样本 ,来一个数据之后,根据前值直接计算新值,适用于流式计算场景

需要维护三个值
count sum ivar(增量方差)

public class IVarBuilder {
	
    private int count=0;
    private double sum = 0;   
    private double ivar=0;
  
    // 增量计算 ,根据前值计算新值 
	public void add(double v){
		if(count<=0){
			count++;
			sum = sum + v;
			ivar = 0;
			return;
		}
		double avg = sum / count ;
		double avgnew = (sum+v) / (count+1);
		
		double difnew = v - avgnew;
		double difavg = avg - avgnew;
		double ivarnew = (ivar+difavg*difavg) * count + difnew*difnew;
		ivarnew = ivarnew / (count+1);
		
		count++;
		sum = sum + v;
		ivar = ivarnew;	
	}
	

测试代码
IvarTest.java

public class IvarTest {

	public static void main(String[] args) throws Exception {
		double[] arr = new double[] { 3, 3, 5, 7, 2, 9, 5, 3, 3 };
		run(arr);

		arr = new double[] { 50, 80, 100, 300, 700, 50 };
		run(arr);
		
		arr = new double[] { 50, 50,50};
		run(arr);
	}

	private static void run(double[] arr) {
		// 方差
		double var = MathUtil.var(arr);
		// 增量方差
		double ivar = MathUtil.ivar(arr).getIvar();
		System.out.println("var=" + var + ",ivar=" + ivar);
	}
}

完整代码
https://gitee.com/dyyx/hellocode/tree/master/src/dyyx/var

上一篇     下一篇
linux shell 获取进程相关信息

Linux Shell总结

社会潜规则21条

智能手环原理

互联网数据分析常用指标

职业修炼指南