Can averages be calculated one value at a time?

1.7k Views Asked by At

I'm writing some code which calculates some averages. Obviously, the traditional way to calculate any average is to add up all the values, and then divide by the number of values.

However, in the mechanism I'm working on, I find it much easier to add and calculate the averages one at a time, as in add a new value to the averaged total, and then divide by two each time (since each time there are two numbers being added). But I'm not sure how accurate it would be.

Can I calculate averages this way? Or is it not reliable?


NOTE: I began writing this question originally, and while coming up with an example, found my answer. So I added an answer with my question at the same time.

2

There are 2 best solutions below

3
On BEST ANSWER

(I'm answering my question Q/A style)

Imagine this set of numbers:

1, 2, 3, 4, 5

The traditional method is:

((1 + 2 + 3 + 4 + 5) / 5) = 3

What you are proposing is:

((1 + 2) / 2) = 1.5
((1.5 + 3) / 2) = 2.25
((2.25 + 4) / 2) = 3.125
((3.125 + 5) / 2) = 4.0625

So no, this proposed method of calculating an average does not work.

3 <> 4.0625

Not to mention, even if it did work, it would be much slower anyway.


What you could do instead is to continue adding the values together, and elsewhere keep track of the number of values. Each time you add a value, also increment the number of values added. Then, at any given point, you are able to calculate the average...

(1 + 2) = 3       C = 2     (3 / 2) = 1.5
(3 + 3) = 6       C = 3     (6 / 3) = 2
(6 + 4) = 10      C = 4     (10 / 4) = 2.5
(10 + 5) = 15     C = 5     (15 / 5) = 3

In any case, the moral of the story is that you still need to add all the values together, and then divide by the number of values. You can keep a sum of all values, but you also need to keep a count of the values which have been added to that sum.

0
On

Here is a reference of a quite accurate algorithm for getting the average of a series of floating point numbers:

https://en.wikipedia.org/wiki/Kahan_summation_algorithm

If you also want to compute the variance, look here:

https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance

A good reference is this:

https://people.eecs.berkeley.edu/~wkahan/Math128/MeanVar.pdf