Search code examples
c++boostmoving-average

Calculate rolling / moving average in C++


I know this is achievable with boost as per:

Using boost::accumulators, how can I reset a rolling window size, does it keep extra history?

But I really would like to avoid using boost. I have googled and not found any suitable or readable examples.

Basically I want to track the moving average of an ongoing stream of a stream of floating point numbers using the most recent 1000 numbers as a data sample.

What is the easiest way to achieve this?


I experimented with using a circular array, exponential moving average and a more simple moving average and found that the results from the circular array suited my needs best.


Solution

  • You simply need a circular array (circular buffer) of 1000 elements, where you add the element to the previous element and store it.

    It becomes an increasing sum, where you can always get the sum between any two pairs of elements, and divide by the number of elements between them, to yield the average.