RunningStat.h (1148B)
1 /* Any copyright is dedicated to the Public Domain. 2 http://creativecommons.org/publicdomain/zero/1.0/ */ 3 /* Adapted from "Accurately computing running variance - John D. Cook" 4 http://www.johndcook.com/standard_deviation.html */ 5 6 #ifndef RUNNING_STAT_H_ 7 #define RUNNING_STAT_H_ 8 #include <math.h> 9 10 namespace mozilla { 11 12 class RunningStat { 13 public: 14 RunningStat() : mN(0), mOldM(0.0), mNewM(0.0), mOldS(0.0), mNewS(0.0) {} 15 16 void Clear() { mN = 0; } 17 18 void Push(double x) { 19 mN++; 20 21 // See Knuth TAOCP vol 2, 3rd edition, page 232 22 if (mN == 1) { 23 mOldM = mNewM = x; 24 mOldS = 0.0; 25 } else { 26 mNewM = mOldM + (x - mOldM) / mN; 27 mNewS = mOldS + (x - mOldM) * (x - mNewM); 28 29 // set up for next iteration 30 mOldM = mNewM; 31 mOldS = mNewS; 32 } 33 } 34 35 int NumDataValues() const { return mN; } 36 37 double Mean() const { return (mN > 0) ? mNewM : 0.0; } 38 39 double Variance() const { return (mN > 1) ? mNewS / (mN - 1) : 0.0; } 40 41 double StandardDeviation() const { return sqrt(Variance()); } 42 43 private: 44 int mN; 45 double mOldM, mNewM, mOldS, mNewS; 46 }; 47 } // namespace mozilla 48 #endif // RUNNING_STAT_H_