Average of a list of numbers, read one at a time

193 Views Asked by At

I have a dilemma

Lets take the set $\{1, 2, 3, 4, 5, 6, 7, 8, 9\}$

If we wanted to calculate the average of this set we would add up all the numbers in the set $(45)$ and then divide by the total number of items in the set $(9)$ and arrive at the correct average of $5$

What happens if we are not given the full set? What if we are only given one number at a time and have to calculate the correct average?

For instance if we are given $1$ we know the average is $1$, then if we are given $2$ then we add $1+2$ and get $3$, then divide $3$ by $2$ and arrive at the correct average of $1.5$.

Then what if we are given the next number $3$ we would add $1.5$ and $3$ giving $4.5$ and divide that by $2$ arriving at $2.25$ which is incorrect since $1+2+3=6$ and $6/3=2$.

Is there a way of calculating the correct total average like this?

1

There are 1 best solutions below

2
On BEST ANSWER

You can:

  • Keep track of the total number of values you have seen so far, call it $n$, and the average of the numbers so far, $A$. Then when you see a new number $x$, map \begin{align*} n &\mapsto n+1 \\ A &\mapsto \frac{nA + x}{n+1} \end{align*}

Or:

  • Keep track of the total number of values you have seen so far, call it $n$, and the sum of the numbers so far, $S$. Then when you see a new number $x$, map \begin{align*} n &\mapsto n+1 \\ S &\mapsto S+x \end{align*} at the end, compute the average $\frac{S}{n}$.