Skip to content

Instantly share code, notes, and snippets.

@chmike
Created December 12, 2012 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chmike/4266325 to your computer and use it in GitHub Desktop.
Save chmike/4266325 to your computer and use it in GitHub Desktop.
Compute incrementally mean and std dev
#include <cmath>
//! One kibibyte unit size (see http://en.wikipedia.org/wiki/Kibibyte)
const size_t KiB = 1024;
//! One mebibyte unit size (see http://en.wikipedia.org/wiki/Mebibyte)
const size_t MiB = 1024*1024;
//! Convert timeval structure to a double
double toDbl( struct timeval& t )
{ return double(t.tv_sec) + double(t.tv_usec)/1000000.0; }
//! Compute incremental stats on a sequence of added values
class IncrementalStats
{
public:
IncrementalStats() : m_mean(0), m_var(0), m_n(0) {}
double mean() const { return m_mean; }
double stdDev() const { return ::sqrt(m_var); }
double n() const { return m_n; }
void clear() { m_mean = m_var = m_n = 0; }
void add(double x)
{
// See Knuth TAOCP vol 2, 3rd edition, page 232
m_n++;
double temp = (x - m_mean);
m_mean += temp/m_n;
m_var += temp*(x - m_mean);
}
private:
double m_mean, m_var, m_n;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment