How to add and subtract values from an average?

Solution 1:

I know that's an old thread but I had the same problem. I want to add a value to an existing average without calculate it back to the total sum.

to add an value to an exisitng average we only must know for how much values the average is calculated: $$ average_{new} = average_{old} + \frac{ value_{new} - average_{old}}{size_{new}} $$

Solution 2:

$s=\frac{a_1+...+a_n}{n}$.

If you want the average of $a_1,...,a_n$ and $a_{n+1}$, then $s'=\frac{a_1+...+a_n+a_{n+1}}{n+1}=\frac{ns+a_{n+1}}{n+1} = \frac{(n+1)s+a_{n+1}}{n+1} - \frac{s}{n+1} = s + \frac{a_{n+1}-s}{n+1}$

If you want the average of $a_1,...,a_{n-1}$ then $s''=\frac{a_1+...+a_{n-1}}{n-1}=\frac{ns-a_n}{n-1}= \frac{(n-1)s-a_n}{n-1} + \frac{s}{n-1}=s+\frac{s-a_n}{n-1}$.

Solution 3:

To put it programmatically, and since the question was about how to both add and subtract:

Add a value:

average = average + ((value - average) / nValues)

Subtract a value:

average = (average * nValues - value) / (nValues - 1)