SimpleStats.h
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #ifndef _SIMPLESTATS_H_
00019 #define _SIMPLESTATS_H_
00020
00021 #include <math.h>
00022 #include <iostream>
00023
00024
00025
00026
00027
00028 class RunningStat
00029 {
00030 public:
00031 RunningStat() : m_n(0), m_oldM(0), m_newM(0), m_oldS(0), m_newS(0) {}
00032
00033 void Clear()
00034 {
00035 m_n = 0;
00036 }
00037
00038 void Push(double x)
00039 {
00040 m_n++;
00041
00042
00043 if (m_n == 1)
00044 {
00045 m_oldM = x;
00046 m_oldS = 0.0;
00047 m_newM = x;
00048 m_newS = 0.0;
00049 }
00050 else
00051 {
00052 m_newM = m_oldM + (x - m_oldM)/m_n;
00053 m_newS = m_oldS + (x - m_oldM)*(x - m_newM);
00054
00055
00056 m_oldM = m_newM;
00057 m_oldS = m_newS;
00058 }
00059 }
00060
00061 int NumDataValues() const
00062 {
00063 return m_n;
00064 }
00065
00066 double Mean() const
00067 {
00068 return (m_n > 0) ? m_newM : 0.0;
00069 }
00070
00071 double Variance() const
00072 {
00073 return ((m_n > 1) ? m_newS/(m_n - 1) : 0.0);
00074 }
00075
00076 double StandardDeviation() const
00077 {
00078 return sqrt(Variance());
00079 }
00080
00081 private:
00082 uint64_t m_n;
00083 double m_oldM, m_newM, m_oldS, m_newS;
00084 };
00085
00086
00087
00088
00089 inline bool operator == (RunningStat &r, int i)
00090 {
00091 return r.NumDataValues() == i;
00092 }
00093
00094 inline std::ostream &operator << (std::ostream &stream, RunningStat &s)
00095 {
00096 stream << "N: " << s.NumDataValues()
00097 << " Mean: " << s.Mean()
00098 << " Standard Deviation: " << s.StandardDeviation();
00099
00100 return stream;
00101 }
00102
00103
00104 #endif