Skip to content

Instantly share code, notes, and snippets.

@takamin
Last active August 29, 2015 14:05
Show Gist options
  • Save takamin/0d272233602f3e65ee09 to your computer and use it in GitHub Desktop.
Save takamin/0d272233602f3e65ee09 to your computer and use it in GitHub Desktop.
#include <deque>
template<class InputType, class InnerAvgType=double,
class AvgType=InputType>
class MovingAverage {
int average_count;
std::deque<InputType> buffer;
InnerAvgType average;
public:
MovingAverage() : average_count(1), average(0) { }
MovingAverage(int average_count)
: average_count(average_count), average(0)
{
assert(average_count > 0);
}
int getAverageCount() const {
return average_count;
}
void setAverageCount(int n) {
assert(n > 0);
average_count = n;
reset();
}
// reset average value and counter.
void reset() {
average = 0;
buffer.clear();
}
// average value stability
bool isStable() const {
return buffer.size() >= average_count;
}
// update and return average value
AvgType update(const InputType& input) {
InnerAvgType total = average * buffer.size();
if(buffer.size() >= average_count) {
total -= buffer.at(0);
buffer.pop_front();
}
buffer.push_back(input);
total += (InnerAvgType)input;
average = total / buffer.size();
return (AvgType)average;
}
operator AvgType () {
return (AvgType)average;
}
};
#include <iostream>
#include <assert.h>
#include "MovingAverage.h"
int main(int argc, char*argv[]) {
MovingAverage<int> intAverager(5);
int data[] = {
1,2,3,4,5,6,7,8,9,10,9,8,7,
6,5,4,3,2,1,0,0,0,0,0,0,0};
for(int i = 0; i < sizeof(data)/sizeof(data[0]); i++) {
int average = intAverager.update(data[i]);
std::cerr << "input " << data[i]
<< " average = " << average << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment