Simple, Fast and Accurate Running Average in C#

Running averages, also called rolling average, rolling mean and moving average, can be calculated in several different ways:

  • Simple Moving Average
  • Cumulative Moving Average
  • Weighted Moving Average

For my scenario I needed a simple, fast and accurate average, so I settled on implementing the simple moving average calculator below.

   class SimpleRunningAverage
   {
      int _size;
      int[] _values = null;
      int _valuesIndex = 0;
      int _valueCount = 0;
      int _sum = 0;

      public SimpleRunningAverage(int size)
      {
         System.Diagnostics.Debug.Assert(size > 0);
         _size = Math.Max(size, 1);
         _values = new int[_size];
      }

      public int Add(int newValue)
      {
         // calculate new value to add to sum by subtracting the
         // value that is replaced from the new value;
         int temp = newValue - _values[_valuesIndex];
         _values[_valuesIndex] = newValue;
         _sum += temp;

         _valuesIndex++;
         _valuesIndex %= _size;
        
         if (_valueCount < _size)
            _valueCount++;

         return _sum / _valueCount;
      }
   }
 
 

Here is how to use it:

      SimpleRunningAverage avg = new SimpleRunningAverage(4);
      foreach (int i in new int[] { 1, 2, 3, 4, 4, 4, 4 })
      {
         Console.WriteLine(avg.Add(i));
      }

 

For an implementation with more bells and whistles check out Marc Cliftons great article.


No comments:

Post a Comment

My Latest Track