Created
December 20, 2011 15:55
-
-
Save musically-ut/1502045 to your computer and use it in GitHub Desktop.
Knuth's numerically stable standard deviation calculation
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
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