2

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?

Parad0x13
  • 213
  • 4
    If you know how many numbers are in the set already, then you can update the average as follows: $\mu \rightarrow (n \mu + x) / (n + 1)$. This works because $n\mu$ is the old sum, $n\mu + x$ is the new sum, and so $n\mu + x$ divided by $n+1$ is the new mean. – mjqxxxx Aug 08 '15 at 04:59
  • Woah! Such a fast response! I will give this a try and see if it indeed works and get back to you – Parad0x13 Aug 08 '15 at 05:00
  • Yep, your assistance worked! I am greatly impressed and thankful – Parad0x13 Aug 08 '15 at 05:25

1 Answers1

2

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}$.