简体   繁体   中英

Calculate or Update Average without iteration over time

Consider a small monitoring device which displays temperature average every 10 seconds.

timestamp               value
20190304000000           62.7
20190304000010           62.5
20190304000020           62.8 
.... 
....

how to calculate and update average without increasing memory footprint. that is, whole data storage (persistent or memory) in not possible

In addition to other answers, you might want to use IIR filter to get Exponential moving average : filter that applies weighting factors which decrease exponentially , so last values have more impact than older ones

newAverage = OldAverage * (1-alpha) + NewValue * alpha

where alpha is small value like 0.1 that has relation to decreasing time/constant

Keep a total sum, and a count of the number of temperatures recorded. Then divide the sum by the count every time you report the answer, to avoid compounding floating point errors.

from itertools import count

temperature_sum = 0
for temperature_count in count(1):
    temperature_sum += read_from_sensor()
    print("Average: {}".format(temperature_sum / temperature_count))

we will need two variables

int count;
float average;

void main() {
   do while(true) {
      float temperature = ReadFromSensor(); //not included
      average = ((average*count) + temperature)/ ++count;
      cout << "average: " << average << endl;
   }
}

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