1

I'm trying to calculate the average of a value that is changing, and I would like to do so without storing all the previous values in an array and iterating over them.

I found this formula

avg = avg + (value - avg) / n

where n is the number of changes to value.

TL;DR

My question is if this formula is identical to the normal way of calculating an average (which it seems to be when I compare them), or if it might give different results under certain circumstances?

I'm not sure what the correct name of this formula is - I've seen "running average, "rolling average", "moving average", etc. The results of it seem to be exactly the same as storing each historical value, summing them up and dividing by n - i.e. a "normal average".

What's confusing is that people sometimes call this formula a "moving average", which in my mind sounds more like you're using a subset of the historical values to calculate an average. Others say it's an exponential moving average (see comment by Julia on OP).

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • To calculate a moving average you need to store at least the number of values that are within the window over which you want to calculate the average. For the average about all values so far can be calculated without storing all the values. – MrSmith42 Dec 29 '17 at 19:55

1 Answers1

2

Is this formula is identical to the normal way of calculating an average?

With infinite precision, this formula does indeed compute the sum of the first n samples if avg is set equal to 0 at the start.

It is clearly true when n=1 because the average of 1 sample works out as:

avg' = avg + (value - avg) / n
     = 0   + (value - 0) / 1
     = value

For larger values, assume it is true for n-1 (i.e. avg=(x[1]+..+x[n-1])/(n-1) ).

Then:

avg' = avg + (x[n] - avg) / n
      = (n-1)*avg/n + x[n]/n
      = (x[1]+...+x[n-1])/n + x[n]/n
      = (x[1]+...+x[n])/n

So the new value of avg is also equal to the average of the first n samples.

Is this a moving average?

Normally by "moving average" people are referring to a simple moving average.

This formula is actually known as a cumulative moving average.

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75