Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
output[i] = alpha*input[i] + (1-alpha)*output[i-1]
0<=alpha<=1
#include <iostream>
#include <iterator>
#include <algorithm>
#include <queue>
#include <vector>
class MovingAverage {
std::queue<double> window; // окно
size_t period; // максимальный размер окна
double sum; // сумма элементов в окне
public:
MovingAverage(size_t period) : period(period) {}
double operator()(double num) {
sum += num;
window.push(num);
if (window.size() > period) {
sum -= window.front();
window.pop();
}
return sum / window.size();
}
};
int main() {
using namespace std;
double indata[] = {1, 2, 3, 2, 4, 5, 4, 5, 4, 5, 6, 2, 5, 6, 6, 7};
size_t size = sizeof(indata) / sizeof(double);
vector<double> out(size);
// применение функтора MovingAverage к исходному массиву
transform(indata, indata + size, out.begin(), MovingAverage(5));
// вывод результирующего массива
copy(out.begin(), out.end(), ostream_iterator<double>(cout, "\n"));
}Effects: Assigns through every iterator i in the range [result,result + (last1 — first1)) a new corresponding value equal to op(*(first1 + (i — result)) or binary_op(*(first1 + (i — result)), *(first2 + (i — result))).
25.2.3 Transform [lib.alg.transform]
Requires: op and binary_op shall not have any side effects.
Requires: op and binary_op shall not invalidate iterators or subranges, or modify elements in the ranges [first1,last1], [first2,first2 + (last1 — first1)], and [result,result + (last1 — first1)].
...
std::vector<double> &out;
public:
MovingAverage(std::vector<double> &out, size_t period) : out(out), period(period) {}
void operator()(double num) {
sum += num;
window.push(num);
if (window.size() > period) {
sum -= window.front();
window.pop();
}
out.push_back(sum / window.size());
} vector<double> out;
out.reserve(size);
for_each(indata, indata + size, MovingAverage(out, 5));
Алгоритм скользящего среднего (Simple Moving Average)