On 2013-02-13 14:44, Joseph Rushton Wakeling wrote:
The docs for std.algorithm give an illustration of its use to calculate mean and
standard deviation in a single pass: [...]
However, this formula for standard deviation is one that is well known for being
subject to potentially fatal rounding error.

Typical thing with examples - they try to be terse and show off a mechanism like reduce, without going into too much details and hence are unusable IRL.

You can use reduce and put the division and subtraction into the reduce itself to prevent overflows. You also won't end up with jaw-dropping tuples, sorry. :)

    float[] a = [10_000.0f, 10_001.0f, 10_002.0f];
    auto n = a.length;
    auto avg = reduce!((a, b) => a + b / n)(0.0f, a);
    auto var = reduce!((a, b) => a + pow(b - avg, 2) / n)(0.0f, a);
    auto sd = sqrt(var);
    writeln(avg, "\t", sd);

Output: 10001   0.816497

Reply via email to