Last active
August 29, 2015 14:05
-
-
Save takamin/4218fa22d47771a00f1b 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
template<class InputType, class InnerAvgType=double, class AvgType=InputType> | |
class LongAverage { | |
int average_count; | |
int buffer_count; | |
InnerAvgType average; | |
public: | |
LongAverage() : average_count(100000), buffer_count(0), average(0) { } | |
LongAverage(int average_count) : average_count(average_count), buffer_count(0), 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() { | |
buffer_count = 0; | |
average = 0; | |
} | |
// update and return average value | |
AvgType update(const InputType& input) { | |
buffer_count += (buffer_count < average_count) ? 1 : 0; | |
average += (InnerAvgType)(((InnerAvgType)input - average) / buffer_count); | |
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 "LongAverage.h" | |
int main(int argc, char*argv[]) { | |
LongAverage<double> intAverager; | |
double data[] = {0, 1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1,0,}; | |
for(int ii = 0; ii < 10000; ii++) { | |
for(int i = 0; i < sizeof(data)/sizeof(data[0]); i++) { | |
intAverager.update(data[i]); | |
} | |
} | |
std::cerr << "average = " << (double)intAverager << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment