diff --git a/src/utils/SensorDataUtils.cpp b/src/utils/SensorDataUtils.cpp index ebb44dea..65d87115 100644 --- a/src/utils/SensorDataUtils.cpp +++ b/src/utils/SensorDataUtils.cpp @@ -88,13 +88,19 @@ namespace{ int getAverageOfSensorDataIntField(const std::vector& datas, int (*selectorFct)(const SensorData&)){ //TODO: we gotta be careful for int overflow here - int total = 0; + double i = 1; + double currentAvg = 0; for (const auto& sensorData: datas){ - total += selectorFct(sensorData); + // Aaron's Algorithm for Average + // The average is a simplified version of A' =(A(n-1) + a)/n + // where A' is the new average at n, A is the current average at n - 1, and a is the value at n + currentAvg *= 1 - (1.0 / i); + currentAvg += selectorFct(sensorData) / i; + i++; } // TODO: this cast is technically iffy, but once we switch to fixed size vectors we should be safe - return total / static_cast(datas.size()); + return static_cast(currentAvg); } }