I have one observation: you do not need to keep calculating the sum every time a reading is added or removed:

$mean = (1+2+3+4) / 4; $newreading = 5; $remove = 1; $newmean = $mean + ($newreading - $remove) / 4;

In this way you can have subs add_reading() and remove_reading() which also recalculate the mean without worrying about redandant summations.

Secondly, since you are dealing with infinite data, perhaps you can benefit from B.P.Welford's method of "running statistics". This is a simple method to keep a mean and lots of other descriptive statistics (e.g. standard deviation) without ever storing any readings at all! Ingenious yet simple. And you are lucky because last time I looked CPAN had 3 such modules Statistics::Welford, Statistics::Running and Statistics::Running::Tiny (disclaimer last 2 modules by myself). If you want that in C (via C++) have a look at John Cook's blog

You may find this approach useful especially if you will need higher-order statistics like standard deviation etc. because you will find that the moving average is not good enough for detecting outliers and you need to add more flexibility to your model.

1 minute EDIT: however, if your running mean varies during the day or the seasons, then keeping a "running" mean since the beginning of time is not right! In which case a model with more input parameters (like time of day) can assess whether a reading is an outlier (over this very recent time). If that's the case, at least you have the first observation, you don't need to re-do the sums for a moving average.


In reply to Re: Combining Exponential Moving Avg with Avg Filtering by bliako
in thread Combining Exponential Moving Avg with Avg Filtering by stevieb

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.