Skip to content

Commit

Permalink
Review changes
Browse files Browse the repository at this point in the history
  • Loading branch information
miloszlagan committed Nov 22, 2024
1 parent 8faab9c commit b891a89
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
19 changes: 11 additions & 8 deletions husarion_ugv_utils/include/husarion_ugv_utils/moving_average.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,37 +27,40 @@ class MovingAverage
MovingAverage(const std::size_t window_size = 5, const T initial_value = T(0))
: window_size_(window_size), initial_value_(initial_value)
{
if (window_size_ == 0) {
throw std::invalid_argument("Window size must be greater than 0");
}
}

void Roll(const T value)
{
values_.push_back(value);
buffer_.push_back(value);

if (values_.size() > window_size_) {
values_.pop_front();
if (buffer_.size() > window_size_) {
buffer_.pop_front();
}
}

void Reset() { values_.erase(values_.begin(), values_.end()); }
void Reset() { buffer_.erase(buffer_.begin(), buffer_.end()); }

T GetAverage() const
{
if (values_.size() == 0) {
if (buffer_.size() == 0) {
return initial_value_;
}

T sum = T(0);

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

return sum;
}

private:
const std::size_t window_size_;
std::deque<T> values_;
std::deque<T> buffer_;
const T initial_value_;
};

Expand Down
8 changes: 4 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,15 @@ TEST(TestMovingAverage, TestHighOverload)
const std::size_t window_len = 1000;
husarion_ugv_utils::MovingAverage<double> ma(window_len);

double sum = 0.0;
double avg = 0.0;
for (std::size_t i = 1; i <= window_len * 10; i++) {
sum += double(i) / double(window_len);
avg += double(i) / double(window_len);
ma.Roll(double(i));

// test every 1000 rolls expected average
if (i % window_len == 0) {
EXPECT_LT(sum - ma.GetAverage(), std::numeric_limits<double>::epsilon());
sum = 0.0;
ASSERT_NEAR(avg, ma.GetAverage(), std::numeric_limits<double>::epsilon());
avg = 0.0;
}
}
}
Expand Down

0 comments on commit b891a89

Please sign in to comment.