1
0
mirror of https://github.com/f4exb/sdrangel.git synced 2024-11-29 19:28:47 -05:00
sdrangel/include-gpl/dsp/movingaverage.h

61 lines
1.0 KiB
C
Raw Normal View History

#ifndef INCLUDE_MOVINGAVERAGE_H
#define INCLUDE_MOVINGAVERAGE_H
#include <vector>
#include "dsp/dsptypes.h"
2015-06-20 03:28:57 -04:00
template<class Type> class MovingAverage {
public:
MovingAverage() :
m_history(),
m_sum(0),
m_ptr(0)
{
}
2015-06-20 03:28:57 -04:00
MovingAverage(int historySize, Type initial) :
m_history(historySize, initial),
2015-06-20 03:28:57 -04:00
m_sum((float) historySize * initial),
m_ptr(0)
{
}
2015-06-20 03:28:57 -04:00
void resize(int historySize, Type initial)
{
m_history.resize(historySize);
for(size_t i = 0; i < m_history.size(); i++)
m_history[i] = initial;
2015-06-20 03:28:57 -04:00
m_sum = (float) m_history.size() * initial;
m_ptr = 0;
}
2015-06-20 03:28:57 -04:00
void feed(Type value)
{
m_sum -= m_history[m_ptr];
m_history[m_ptr] = value;
m_sum += value;
m_ptr++;
if(m_ptr >= m_history.size())
m_ptr = 0;
}
2015-06-20 03:28:57 -04:00
void fill(Type value)
2015-05-12 06:12:13 -04:00
{
for(size_t i = 0; i < m_history.size(); i++)
m_history[i] = value;
2015-06-20 03:28:57 -04:00
m_sum = (float) m_history.size() * value;
2015-05-12 06:12:13 -04:00
}
2015-06-20 03:28:57 -04:00
Type average() const
{
2015-06-20 03:28:57 -04:00
return m_sum / (float) m_history.size();
}
protected:
2015-06-20 03:28:57 -04:00
std::vector<Type> m_history;
Type m_sum;
uint m_ptr;
};
#endif // INCLUDE_MOVINGAVERAGE_H