简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM