mirror of
https://git.intern.spaceteamaachen.de/ALPAKA/sta-peak.git
synced 2025-06-12 19:05:58 +00:00
feat: rolling average
This commit is contained in:
parent
d5914f2d1c
commit
6d8869a409
37
include/sta/math/algorithms/rollingAverage.hpp
Normal file
37
include/sta/math/algorithms/rollingAverage.hpp
Normal file
@ -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 <typename T> 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_ */
|
41
src/algorithms/rollingAverage.cpp
Normal file
41
src/algorithms/rollingAverage.cpp
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
#include <sta/math/algorithms/rollingAverage.hpp>
|
||||||
|
|
||||||
|
namespace sta
|
||||||
|
{
|
||||||
|
namespace math
|
||||||
|
{
|
||||||
|
template <typename T>
|
||||||
|
RollingAverage<T>::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 <typename T>
|
||||||
|
RollingAverage<T>::~RollingAverage()
|
||||||
|
{
|
||||||
|
delete values_;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
void RollingAverage<T>::add(Value value)
|
||||||
|
{
|
||||||
|
sum_ -= values_[index_];
|
||||||
|
values_[index_] = value;
|
||||||
|
sum_ += value;
|
||||||
|
index_ = (index_ + 1) % size_;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
typename RollingAverage<T>::Value RollingAverage<T>::get()
|
||||||
|
{
|
||||||
|
return sum_ / size_;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace math
|
||||||
|
|
||||||
|
} // namespace sta
|
Loading…
x
Reference in New Issue
Block a user