Created
December 12, 2012 09:19
-
-
Save chmike/4266325 to your computer and use it in GitHub Desktop.
Compute incrementally mean and std dev
This file contains hidden or 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 <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