/** * Computes the average and standard devaiation of a number * of samples iteratively using constant space. * * Standard you shouldn't trust this code disclaimer: * You shouldn't trust this code. I make no guarantees that it * actually does anything. * * (in particular, this code will have rounding issues) * * Proof or correctness and description at * http://www.cs.umd.edu/~austinjp/constSD.pdf * * email with corrections / improvements. * * @author Austin Parker * @email austinjp@cs.umd.edu */ package jist.swans.misc; public class AverageSD { protected int num = 0; protected double var = 0; //store the variance -- save a couple of square roots. protected double avg = 0; public int getNumberOfSamples() { return num; } public double getVariance() { return var; } public double getStandardDeviation() { return Math.sqrt(var); } public double getAverage() { return avg; } /** * includes the parameter as a sample. Recomputes * variance, average, and number of samples to * correspond to having this as a new sample. */ public void addSample(double sample) { int newNum = num+1; double newAvg = (num*avg+sample) / (newNum); double intermediate1 = (sample-avg) / newNum; double intermediate2 = sample-newAvg; double newVar = (num*var + num*intermediate1*intermediate1 + intermediate2*intermediate2) / newNum; num = newNum; avg = newAvg; var = newVar; } public String toString() { return "average: "+avg+", standard deviation: "+getStandardDeviation()+", number of samples: "+num; } }