From 72554b836e2d914a25ea8d6fc5e9b83dbb4e72b7 Mon Sep 17 00:00:00 2001 From: Milosz Lagan Date: Fri, 22 Nov 2024 10:43:13 +0000 Subject: [PATCH] Use normal accumulation and division for MA calculation --- .../include/husarion_ugv_utils/moving_average.hpp | 10 ++++------ husarion_ugv_utils/test/test_moving_average.cpp | 9 +++++---- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/husarion_ugv_utils/include/husarion_ugv_utils/moving_average.hpp b/husarion_ugv_utils/include/husarion_ugv_utils/moving_average.hpp index 311f214d..fc1d6b4f 100644 --- a/husarion_ugv_utils/include/husarion_ugv_utils/moving_average.hpp +++ b/husarion_ugv_utils/include/husarion_ugv_utils/moving_average.hpp @@ -16,6 +16,7 @@ #define HUSARION_UGV_UTILS_MOVING_AVERAGE_HPP_ #include +#include namespace husarion_ugv_utils { @@ -49,13 +50,10 @@ class MovingAverage return initial_value_; } - T sum = T(0); + T sum = std::accumulate(buffer_.begin(), buffer_.end(), T(0)); + T average = sum / static_cast(buffer_.size()); - for (const auto & value : buffer_) { - sum += value / static_cast(buffer_.size()); - } - - return sum; + return average; } private: diff --git a/husarion_ugv_utils/test/test_moving_average.cpp b/husarion_ugv_utils/test/test_moving_average.cpp index 9c759980..2934f28e 100644 --- a/husarion_ugv_utils/test/test_moving_average.cpp +++ b/husarion_ugv_utils/test/test_moving_average.cpp @@ -59,15 +59,16 @@ TEST(TestMovingAverage, TestHighOverload) const std::size_t window_len = 1000; husarion_ugv_utils::MovingAverage ma(window_len); - double avg = 0.0; + double sum = 0.0; for (std::size_t i = 1; i <= window_len * 10; i++) { - avg += double(i) / double(window_len); + sum += double(i); ma.Roll(double(i)); // test every 1000 rolls expected average if (i % window_len == 0) { - ASSERT_NEAR(avg, ma.GetAverage(), std::numeric_limits::epsilon()); - avg = 0.0; + ASSERT_NEAR( + sum / double(window_len), ma.GetAverage(), std::numeric_limits::epsilon()); + sum = 0.0; } } }