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; } } }