Calculate rolling / moving average in C++

If your needs are simple, you might just try using an exponential moving average.

http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average

Put simply, you make an accumulator variable, and as your code looks at each sample, the code updates the accumulator with the new value. You pick a constant “alpha” that is between 0 and 1, and compute this:

accumulator = (alpha * new_value) + (1.0 - alpha) * accumulator

You just need to find a value of “alpha” where the effect of a given sample only lasts for about 1000 samples.

Hmm, I’m not actually sure this is suitable for you, now that I’ve put it here. The problem is that 1000 is a pretty long window for an exponential moving average; I’m not sure there is an alpha that would spread the average over the last 1000 numbers, without underflow in the floating point calculation. But if you wanted a smaller average, like 30 numbers or so, this is a very easy and fast way to do it.

Leave a Comment