From 0aee3d47ba80a19f612931cdabe5141c815eaf7e Mon Sep 17 00:00:00 2001 From: AaronP15 <80867228+AaronP15@users.noreply.github.com> Date: Wed, 21 Feb 2024 20:50:52 -0500 Subject: [PATCH] Rework of `averageData` (#41) * new average algorithm * fixed casting type * attempting to get rid of casting * fixed casting and added comments --- src/utils/SensorDataUtils.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) 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); } }