2014-05-18 11:52:39 -04:00
|
|
|
#ifndef INCLUDE_MOVINGAVERAGE_H
|
|
|
|
#define INCLUDE_MOVINGAVERAGE_H
|
|
|
|
|
2016-08-25 20:01:29 -04:00
|
|
|
#include <stdint.h>
|
2014-05-18 11:52:39 -04:00
|
|
|
#include <vector>
|
|
|
|
#include "dsp/dsptypes.h"
|
|
|
|
|
2015-06-20 03:28:57 -04:00
|
|
|
template<class Type> class MovingAverage {
|
2014-05-18 11:52:39 -04:00
|
|
|
public:
|
|
|
|
MovingAverage() :
|
|
|
|
m_history(),
|
|
|
|
m_sum(0),
|
2016-08-25 20:01:29 -04:00
|
|
|
m_index(0)
|
2014-05-18 11:52:39 -04:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2015-06-20 03:28:57 -04:00
|
|
|
MovingAverage(int historySize, Type initial) :
|
2014-05-18 11:52:39 -04:00
|
|
|
m_history(historySize, initial),
|
2015-06-20 03:28:57 -04:00
|
|
|
m_sum((float) historySize * initial),
|
2016-08-25 20:01:29 -04:00
|
|
|
m_index(0)
|
2014-05-18 11:52:39 -04:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2015-06-20 03:28:57 -04:00
|
|
|
void resize(int historySize, Type initial)
|
2014-05-18 11:52:39 -04:00
|
|
|
{
|
|
|
|
m_history.resize(historySize);
|
2016-08-25 20:01:29 -04:00
|
|
|
|
|
|
|
for(size_t i = 0; i < m_history.size(); i++) {
|
2014-05-18 11:52:39 -04:00
|
|
|
m_history[i] = initial;
|
2016-08-25 20:01:29 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
m_sum = (Type) m_history.size() * initial;
|
|
|
|
m_index = 0;
|
2014-05-18 11:52:39 -04:00
|
|
|
}
|
|
|
|
|
2015-06-20 03:28:57 -04:00
|
|
|
void feed(Type value)
|
2014-05-18 11:52:39 -04:00
|
|
|
{
|
2016-08-25 20:01:29 -04:00
|
|
|
Type& oldest = m_history[m_index];
|
|
|
|
m_sum += value - oldest;
|
|
|
|
oldest = value;
|
|
|
|
|
|
|
|
m_index++;
|
|
|
|
|
|
|
|
if(m_index >= m_history.size()) {
|
|
|
|
m_index = 0;
|
|
|
|
}
|
2014-05-18 11:52:39 -04:00
|
|
|
}
|
|
|
|
|
2015-06-20 03:28:57 -04:00
|
|
|
void fill(Type value)
|
2015-05-12 06:12:13 -04:00
|
|
|
{
|
2016-08-25 20:01:29 -04:00
|
|
|
for(size_t i = 0; i < m_history.size(); i++) {
|
2015-05-12 06:12:13 -04:00
|
|
|
m_history[i] = value;
|
2016-08-25 20:01:29 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
m_sum = (Type) m_history.size() * value;
|
2015-05-12 06:12:13 -04:00
|
|
|
}
|
|
|
|
|
2015-06-20 03:28:57 -04:00
|
|
|
Type average() const
|
2014-05-18 11:52:39 -04:00
|
|
|
{
|
2016-08-25 20:01:29 -04:00
|
|
|
return m_sum / (Type) m_history.size();
|
2014-05-18 11:52:39 -04:00
|
|
|
}
|
|
|
|
|
2015-09-13 05:56:14 -04:00
|
|
|
Type sum() const
|
|
|
|
{
|
|
|
|
return m_sum;
|
|
|
|
}
|
|
|
|
|
2014-05-18 11:52:39 -04:00
|
|
|
protected:
|
2015-06-20 03:28:57 -04:00
|
|
|
std::vector<Type> m_history;
|
|
|
|
Type m_sum;
|
2016-08-25 20:01:29 -04:00
|
|
|
uint32_t m_index;
|
2014-05-18 11:52:39 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
#endif // INCLUDE_MOVINGAVERAGE_H
|