Dan
Dan

Reputation: 1174

Calculate the average of an ever growing list

How can I calculate the average of an ever growing list?

To elaborate: I have rough accelerometer data, returned as a double from 10 to 15 times a second. How to find the average at a given moment in time?

The solution that comes to my mind is storing the sum returned and its count, then dividing it every time, but this leads to buffer overflows and inaccurate results, since computers have issues with decimal numbers.

Please propose an algorithm or mathematical formula.

Upvotes: 0

Views: 959

Answers (2)

Juan Lopes
Juan Lopes

Reputation: 10565

John D. Cook has a very good post on computing mean and standard deviation with stronger numerical properties.

Basically (reducing all the complexity) it can be as simple as this python code (imagine data as an infinite iterable):

n = 0
mean = 0

for value in data:
    n += 1
    mean += (value - mean) / n

Upvotes: 2

mksteve
mksteve

Reputation: 13073

Incremental average from here math.stackexchange

Using incrental average allows the new average to be calculated from the previous average + new value. This will be faster, and not generate massive numbers.

The second form on the page addresses precision concerns

Upvotes: 1

Related Questions