# Calculate the average as numbers arrive

So, suppose you have to calculate the average of a set of numbers, but you don't know the whole set yet. Someone is providing you one number after the other and you cannot use more than the current number and the next number in order to calculate the total average.

For example, given the set

X = {1, 2, 4, 3, 2, 8}


The average of X, knowing the whole set, is:

(1 + 2 + 4 + 3 + 2 + 8) / 6 = 3.3333


But, if you can only use two numbers at a time, then you have:

(1      + 2) / 2 = 1.5
(1.5    + 4) / 2 = 2.75
(2.75   + 3) / 2 = 2.875
(2.875  + 2) / 2 = 2.4375
(2.4375 + 8) / 2 = 5.21


And the average of X would be 5.21. This result is far from the real one 3.33.

So my question is: it is possible calculate the average (or at least a close value) of a given set using the last method? Thanks.

• If you know both the current number and the next, and also how many numbers have appeared up until the current one, it can be done. Something like $n$ times current average + next value, divided by $n+1$ for the next average. [Then update $n.$] – coffeemath Nov 7 '14 at 23:22
• You need to also count the elements. If your average so far is $10$, and the next number is $100$, it makes a big difference whether it's the tenth or the thousandth number. – Daniel Fischer Nov 7 '14 at 23:22
• Thanks coffeemath and Daniel Fischer ! – Enrique Marcos Nov 7 '14 at 23:28

Just keep count of the number of numbers that you have averaged, and use the following formulas: $$\bar X_{new} = \frac{\bar X_{old}*n_{old}+X_{current}*1}{n_{old}+1}$$ $$n_{new} = n_{old} +1$$
For the next iteration, the ${\bar X}_{new}$ becomes $\bar X_{old}$. Ditto for $n_{new}$ into $n_{old}$.