2
$\begingroup$

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?

$\endgroup$
3
  • 4
    $\begingroup$ 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. $\endgroup$
    – mjqxxxx
    Commented Aug 8, 2015 at 4:59
  • $\begingroup$ Woah! Such a fast response! I will give this a try and see if it indeed works and get back to you $\endgroup$
    – Parad0x13
    Commented Aug 8, 2015 at 5:00
  • $\begingroup$ Yep, your assistance worked! I am greatly impressed and thankful $\endgroup$
    – Parad0x13
    Commented Aug 8, 2015 at 5:25

1 Answer 1

2
$\begingroup$

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}$.
$\endgroup$
2
  • $\begingroup$ I actually used your 2nd solution for my answer. You are the best thanks! $\endgroup$
    – Parad0x13
    Commented Aug 8, 2015 at 5:25
  • $\begingroup$ @Parad0x13 You're welcome :) $\endgroup$ Commented Aug 8, 2015 at 5:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .