From 6d8869a409e689100d738d5d62fa8f9caf2b5f62 Mon Sep 17 00:00:00 2001 From: CarlWachter Date: Mon, 15 Jul 2024 18:21:14 +0200 Subject: [PATCH] feat: rolling average --- .../sta/math/algorithms/rollingAverage.hpp | 37 +++++++++++++++++ src/algorithms/rollingAverage.cpp | 41 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 include/sta/math/algorithms/rollingAverage.hpp create mode 100644 src/algorithms/rollingAverage.cpp diff --git a/include/sta/math/algorithms/rollingAverage.hpp b/include/sta/math/algorithms/rollingAverage.hpp new file mode 100644 index 0000000..27cce05 --- /dev/null +++ b/include/sta/math/algorithms/rollingAverage.hpp @@ -0,0 +1,37 @@ +#ifndef INC_ROLLING_AVG_HPP_ +#define INC_ROLLING_AVG_HPP_ + +namespace sta +{ + namespace math + { + + /// Rolling average class, using a ring buffer + template class RollingAverage + { + public: + using Value = T; + + /// @brief Determines rolling average for a given size, discarding the oldest value + /// @param size Size of the rolling average + RollingAverage(int size); + ~RollingAverage(); + + /// @brief Adds a value to the rolling average + /// @param value Value to add + void add(Value value); + + /// @brief Returns the current rolling average + /// @return Current rolling average + Value get(); + + private: + Value *values_; + int size_; + int index_; + Value sum_; + }; + } // namespace math +} // namespace sta + +#endif /* INC_ROLLING_AVG_HPP_ */ diff --git a/src/algorithms/rollingAverage.cpp b/src/algorithms/rollingAverage.cpp new file mode 100644 index 0000000..1801031 --- /dev/null +++ b/src/algorithms/rollingAverage.cpp @@ -0,0 +1,41 @@ +#include + +namespace sta +{ + namespace math + { + template + RollingAverage::RollingAverage(int size) + : size_(size), values_(nullptr), index_(0), sum_(0) + { + values_ = new Value[size]; + for (int i = 0; i < size; i++) + { + values_[i] = 0; + } + } + + template + RollingAverage::~RollingAverage() + { + delete values_; + } + + template + void RollingAverage::add(Value value) + { + sum_ -= values_[index_]; + values_[index_] = value; + sum_ += value; + index_ = (index_ + 1) % size_; + } + + template + typename RollingAverage::Value RollingAverage::get() + { + return sum_ / size_; + } + + } // namespace math + +} // namespace sta