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


In reply to Re: Code Review! Go Ahead, Rip It Up! by toma
in thread Code Review! Go Ahead, Rip It Up! by chaoticset

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.