Last active
August 29, 2015 14:05
-
-
Save takamin/0d272233602f3e65ee09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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