summaryrefslogtreecommitdiff
path: root/media/webrtc/signaling/src/media-conduit/RunningStat.h
blob: 1d0cdbecaafc23c66b879586b025ae6550ae78ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */
/* Adapted from "Accurately computing running variance - John D. Cook"
   http://www.johndcook.com/standard_deviation.html */

#ifndef RUNNING_STAT_H_
#define RUNNING_STAT_H_
#include <math.h>

namespace mozilla {

class RunningStat
{
public:
  RunningStat() : mN(0) {}

  void Clear()
  {
    mN = 0;
  }

  void Push(double x)
  {
    mN++;

    // See Knuth TAOCP vol 2, 3rd edition, page 232
    if (mN == 1)
    {
      mOldM = mNewM = x;
      mOldS = 0.0;
    } else {
      mNewM = mOldM + (x - mOldM) / mN;
      mNewS = mOldS + (x - mOldM) * (x - mNewM);

      // set up for next iteration
      mOldM = mNewM;
      mOldS = mNewS;
    }
  }

  int NumDataValues() const
  {
    return mN;
  }

  double Mean() const
  {
    return (mN > 0) ? mNewM : 0.0;
  }

  double Variance() const
  {
    return (mN > 1) ? mNewS / (mN - 1) : 0.0;
  }

  double StandardDeviation() const
  {
    return sqrt(Variance());
  }

private:
  int mN;
  double mOldM, mNewM, mOldS, mNewS;
};
}
#endif //RUNNING_STAT_H_