Line data Source code
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 : {
14 : public:
15 0 : RunningStat() : mN(0) {}
16 :
17 : void Clear()
18 : {
19 : mN = 0;
20 : }
21 :
22 0 : void Push(double x)
23 : {
24 0 : mN++;
25 :
26 : // See Knuth TAOCP vol 2, 3rd edition, page 232
27 0 : if (mN == 1)
28 : {
29 0 : mOldM = mNewM = x;
30 0 : mOldS = 0.0;
31 : } else {
32 0 : mNewM = mOldM + (x - mOldM) / mN;
33 0 : mNewS = mOldS + (x - mOldM) * (x - mNewM);
34 :
35 : // set up for next iteration
36 0 : mOldM = mNewM;
37 0 : mOldS = mNewS;
38 : }
39 0 : }
40 :
41 0 : int NumDataValues() const
42 : {
43 0 : return mN;
44 : }
45 :
46 0 : double Mean() const
47 : {
48 0 : return (mN > 0) ? mNewM : 0.0;
49 : }
50 :
51 0 : double Variance() const
52 : {
53 0 : return (mN > 1) ? mNewS / (mN - 1) : 0.0;
54 : }
55 :
56 0 : double StandardDeviation() const
57 : {
58 0 : return sqrt(Variance());
59 : }
60 :
61 : private:
62 : int mN;
63 : double mOldM, mNewM, mOldS, mNewS;
64 : };
65 : }
66 : #endif //RUNNING_STAT_H_
|