Skip to content

Commit

Permalink
Use normal accumulation and division for MA calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
miloszlagan committed Nov 22, 2024
1 parent b891a89 commit 72554b8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
10 changes: 4 additions & 6 deletions husarion_ugv_utils/include/husarion_ugv_utils/moving_average.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#define HUSARION_UGV_UTILS_MOVING_AVERAGE_HPP_

#include <deque>
#include <numeric>

namespace husarion_ugv_utils
{
Expand Down Expand Up @@ -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<T>(buffer_.size());

for (const auto & value : buffer_) {
sum += value / static_cast<T>(buffer_.size());
}

return sum;
return average;
}

private:
Expand Down
9 changes: 5 additions & 4 deletions husarion_ugv_utils/test/test_moving_average.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,16 @@ TEST(TestMovingAverage, TestHighOverload)
const std::size_t window_len = 1000;
husarion_ugv_utils::MovingAverage<double> 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<double>::epsilon());
avg = 0.0;
ASSERT_NEAR(
sum / double(window_len), ma.GetAverage(), std::numeric_limits<double>::epsilon());
sum = 0.0;
}
}
}
Expand Down

0 comments on commit 72554b8

Please sign in to comment.