.NET logo

moving average calculator

home | software | utility classes | moving average calculator

using the class

An example usage, showing a simple case:

// create a new calculator with a window size of 5 MovingAverageCalculator calculator = new MovingAverageCalculator(5); // loop through the values 1 to 10 for (int i=1; i<=10; i++) { // write out the average Console.WriteLine(calculator.NextValue(i)); }

This sample code outputs values:

1 1.5 2 2.5 3 4 5 6 7 8

These values are plotted below, where the pink series is the average over all values, and the blue series is the average over the previous 5 values. Notice how both series are identical until the 6th value, at which point the first value 'falls out' of the moving average's window.

Moving average of a linearly increasing series.

You will also notice the smoothing effect the moving average function in this chart, where a jittery function (blue) is plotted alongside a 5-value and 10-value moving average.

Moving average of an irregular series.

CSV values from which this chart was produced were created using the following code:

MovingAverageCalculator calculator1 = new MovingAverageCalculator(5); MovingAverageCalculator calculator2 = new MovingAverageCalculator(20); Random random = new Random(); float lastValue = 0; for (int i=0; i<100; i++) { float value = lastValue + ((float)random.NextDouble() - 0.5f); lastValue = value; Console.WriteLine("{0},{1},{2}", value, calculator1.NextValue(value), calculator2.NextValue(value)); }


submitting feedback

Please feel free to provide feedback on this class . Bug reports are most appreciated when accompanied by a failing NUnit test case.

Authored by Drew Noakes, February 2005. Use freely, though keep this message in the source intact and report any bugs to me. I also appreciate seeing extensions, or simply hearing that you're using these classes. You may not copyright this work, though may use it in commercial/copyrighted works. Happy coding.