libStatGen Software 1
Loading...
Searching...
No Matches
SimpleStats.h
1/*
2 * Copyright (C) 2010 Regents of the University of Michigan
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#ifndef _SIMPLESTATS_H_
19#define _SIMPLESTATS_H_
20
21#include <math.h> // for sqrt
22#include <iostream>
23
24//
25// see http://www.johndcook.com/standard_deviation.html
26// or Donald Knuth's Art of Computer Programming, Vol 2, page 232, 3rd edition
27//
29{
30public:
31 RunningStat() : m_n(0), m_oldM(0), m_newM(0), m_oldS(0), m_newS(0) {}
32
33 void Clear()
34 {
35 m_n = 0;
36 }
37
38 void Push(double x)
39 {
40 m_n++;
41
42 // See Knuth TAOCP vol 2, 3rd edition, page 232
43 if (m_n == 1)
44 {
45 m_oldM = x;
46 m_oldS = 0.0;
47 m_newM = x;
48 m_newS = 0.0;
49 }
50 else
51 {
52 m_newM = m_oldM + (x - m_oldM)/m_n;
53 m_newS = m_oldS + (x - m_oldM)*(x - m_newM);
54
55 // set up for next iteration
56 m_oldM = m_newM;
57 m_oldS = m_newS;
58 }
59 }
60
61 int NumDataValues() const
62 {
63 return m_n;
64 }
65
66 double Mean() const
67 {
68 return (m_n > 0) ? m_newM : 0.0;
69 }
70
71 double Variance() const
72 {
73 return ((m_n > 1) ? m_newS/(m_n - 1) : 0.0);
74 }
75
76 double StandardDeviation() const
77 {
78 return sqrt(Variance());
79 }
80
81private:
82 uint64_t m_n;
83 double m_oldM, m_newM, m_oldS, m_newS;
84};
85
86//
87// helpers for Tabulate template
88//
89inline bool operator == (RunningStat &r, int i)
90{
91 return r.NumDataValues() == i;
92}
93
94inline std::ostream &operator << (std::ostream &stream, RunningStat &s)
95{
96 stream << "N: " << s.NumDataValues()
97 << " Mean: " << s.Mean()
98 << " Standard Deviation: " << s.StandardDeviation();
99
100 return stream;
101}
102
103
104#endif