Last active
November 27, 2019 01:43
-
-
Save TimSC/7cc146d3361cafd50c97 to your computer and use it in GitHub Desktop.
Calculate running average in C++
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
#ifndef _RUNNING_AVERAGE_H | |
#define _RUNNING_AVERAGE_H | |
#include <vector> | |
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
class RunningAverage | |
{ | |
private: | |
double val; | |
size_t count; | |
public: | |
RunningAverage() | |
{ | |
this->Reset(); | |
} | |
double Update(double valIn) | |
{ | |
double scaling = 1. / (double)(count + 1); | |
val = valIn * scaling + val * (1. - scaling); | |
count++; | |
return val; | |
} | |
double Get() | |
{ | |
return val; | |
} | |
size_t Count() | |
{ | |
return count; | |
} | |
void Reset() | |
{ | |
val = 0.; | |
count = 0; | |
} | |
}; | |
#endif //_RUNNING_AVERAGE_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment