Skip to content

Instantly share code, notes, and snippets.

@TimSC
Last active November 27, 2019 01:43
Show Gist options
  • Save TimSC/7cc146d3361cafd50c97 to your computer and use it in GitHub Desktop.
Save TimSC/7cc146d3361cafd50c97 to your computer and use it in GitHub Desktop.
Calculate running average in C++
#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