in reply to Code Review! Go Ahead, Rip It Up!

Writing your own numerical code is always a challenge, especially if you want robust results for a wide range of input data. It is easy to lose precision somewhere, or to miss an error condition, such as needing at least two data points.

Dividing by the number of samples is incorrect (1). Standard deviation pseudocode is:

s=sqrt((sum(samples)-mean(samples))/(num_samples-1))

There are many interesting ways to calculate standard deviation. One provides incremental results. That is, it minimizes calculations and storage such that you can find the standard deviation of a stream of numbers without having all the samples in memory at the same time. You can just read in another value and and recalculate the standard deviation. It takes advantage of this form:

s=sqrt((num_samples*sum(squares(samples))-square(sum(samples)))/(num +_samples*(num_samples-1)))
So you just keep a track of the number of samples, the sum of the squares of the samples, and the sum of the samples. This is how the old hand calculators were able to calculate standard deviation using very little memory.

(1) CRC Standard Mathematical Tables, 23rd ed, pg 573

It should work perfectly the first time! - toma