1
0
mirror of https://github.com/f4exb/sdrangel.git synced 2024-11-23 08:28:36 -05:00
sdrangel/sdrbase/dsp/movingaverage.h

60 lines
1.1 KiB
C
Raw Normal View History

#ifndef INCLUDE_MOVINGAVERAGE_H
#define INCLUDE_MOVINGAVERAGE_H
#include <stdint.h>
#include <vector>
2017-01-15 05:26:11 -05:00
#include <algorithm>
#include "dsp/dsptypes.h"
template<typename Type> class MovingAverage {
public:
MovingAverage(int historySize, Type initial)
{
resize(historySize, initial);
}
2015-06-20 03:28:57 -04:00
void resize(int historySize, Type initial)
{
m_history.resize(historySize);
2017-01-15 05:26:11 -05:00
std::fill(m_history.begin(), m_history.end(), initial);
m_sum = (Type) m_history.size() * initial;
m_index = 0;
}
2015-06-20 03:28:57 -04:00
void feed(Type value)
{
Type& oldest = m_history[m_index];
m_sum += value - oldest;
oldest = value;
2017-01-15 05:26:11 -05:00
if (m_index < m_history.size()) {
m_index++;
} else {
m_index = 0;
}
}
2015-06-20 03:28:57 -04:00
void fill(Type value)
2015-05-12 06:12:13 -04:00
{
2017-01-15 05:26:11 -05:00
std::fill(m_history.begin(), m_history.end(), value);
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
{
return m_sum / (Type) m_history.size();
}
Type sum() const
{
return m_sum;
}
protected:
2015-06-20 03:28:57 -04:00
std::vector<Type> m_history;
Type m_sum;
uint32_t m_index;
};
#endif // INCLUDE_MOVINGAVERAGE_H