added simple moving average

This commit is contained in:
Ahmet Inan 2019-02-14 13:30:16 +01:00
commit 487232ec20
2 changed files with 65 additions and 0 deletions

View file

@ -71,6 +71,10 @@ Implemented are the following [trigger functions](https://en.wikipedia.org/wiki/
* [Rising edge trigger](https://en.wikipedia.org/wiki/Signal_edge)
* [Falling edge trigger](https://en.wikipedia.org/wiki/Signal_edge)
### [sma.hh](sma.hh)
The [simple moving average](https://en.wikipedia.org/wiki/Moving_average#Simple_moving_average) gives us the mean of the last N data points.
### [const.hh](const.hh)
Some constants we need

61
sma.hh Normal file
View file

@ -0,0 +1,61 @@
/*
Simple moving average
Copyright 2019 Ahmet Inan <inan@aicodix.de>
*/
#pragma once
namespace DSP {
template <typename TYPE, int NUM>
class SMA1
{
TYPE hist_inp[NUM];
TYPE hist_avg;
int hist_pos;
public:
SMA1() : hist_avg(0), hist_pos(0)
{
}
TYPE abs_dev()
{
TYPE sum(abs(hist_inp[0] - hist_avg));
for (int i = 1; i < NUM; ++i)
sum += abs(hist_inp[i] - hist_avg);
return sum / NUM;
}
TYPE operator () (TYPE input)
{
hist_inp[hist_pos] = input;
if (++hist_pos >= NUM)
hist_pos = 0;
TYPE hist_sum(hist_inp[0]);
for (int i = 1; i < NUM; ++i)
hist_sum += hist_inp[i];
return hist_avg = hist_sum / NUM;
}
};
template <typename TYPE, int NUM>
class SMA2
{
TYPE hist_inp[NUM];
TYPE hist_sum;
int hist_pos;
public:
SMA2() : hist_sum(0), hist_pos(0)
{
}
TYPE operator () (TYPE input)
{
hist_sum += input - hist_inp[hist_pos];
hist_inp[hist_pos] = input;
if (++hist_pos >= NUM)
hist_pos = 0;
return hist_sum / NUM;
}
};
}