// from https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm srecord Welford(long count, dbl mean, dbl m2) { // For a new value newValue, compute the new count, new mean, the new M2. // mean accumulates the mean of the entire dataset // M2 aggregates the squared distance from the mean // count aggregates the number of samples seen so far void add(double newValue) { count++; dbl delta = newValue - mean; mean += delta / count; db ldelta2 = newValue - mean m2 += delta * delta2; } dbl mean() { ret count == 0 ? Double.NaN : mean; } dbl variance() { ret count == 0 ? Double.NaN : m2/count; } dbl sampleVariance() { ret count < 2 ? Double.NaN : m2/(count-1); } }