Skip to content

Instantly share code, notes, and snippets.

@musically-ut
Created December 20, 2011 15:55
Show Gist options
  • Save musically-ut/1502045 to your computer and use it in GitHub Desktop.
Save musically-ut/1502045 to your computer and use it in GitHub Desktop.
Knuth's numerically stable standard deviation calculation
class StdDevCalcKnuth {
private:
long long m_count;
double m_meanPrev, m_meanCurr, m_sPrev, m_sCurr, m_varianceCurr;
public:
StdDevCalcKnuth() {
m_count = 0;
}
void append(double d) {
m_count++;
if (m_count == 1) {
// Set the very first values.
m_meanCurr = d;
m_sCurr = 0;
m_varianceCurr = m_sCurr;
}
else {
// Save the previous values.
m_meanPrev = m_meanCurr;
m_sPrev = m_sCurr;
// Update the current values.
m_meanCurr = m_meanPrev + (d - m_meanPrev) / m_count;
m_sCurr = m_sPrev + (d - m_meanPrev) * (d - m_meanCurr);
m_varianceCurr = m_sCurr / (m_count - 1);
}
}
double get_std_dev() {
return sqrt(m_varianceCurr);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment