summaryrefslogtreecommitdiffhomepage
path: root/compat/variance.hpp
blob: 8abefd33e12412674358c6c7d3c057f5a7728063 (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
#pragma once

#include <cmath>

// no copyright information other than the attribution below.

// code shared as an example/tutorial of running variance
// written by John D. Cook on the website <http://www.johndcook.com/blog/standard_deviation>

// following references in the site's article:

// Chan, Tony F.; Golub, Gene H.; LeVeque, Randall J. (1983).
// Algorithms for Computing the Sample Variance: Analysis and Recommendations.
// The American Statistician 37, 242-247.

// Ling, Robert F. (1974).
// Comparison of Several Algorithms for Computing Sample Means and Variances.
// Journal of the American Statistical Association, Vol. 69, No. 348, 859-866.

struct variance final
{
    using size_type = unsigned;

    variance& operator=(variance const&) = default;
    void clear() { *this = {}; }

    constexpr size_type count() const { return cnt; }

    constexpr double avg() const { return cnt > 0 ? m_new : 0; }
    constexpr double Var() const { return cnt > 1 ? s_new/(cnt - 1) : 0; }
    double stddev() const { return std::sqrt(Var()); }

    void input(double x)
    {
        cnt++;

        if (cnt == 1)
        {
            m_old = m_new = x;
            s_old = 0;
        }
        else
        {
            m_new = m_old + (x - m_old)/cnt;
            s_new = s_old + (x - m_old)*(x - m_new);

            m_old = m_new;
            s_old = s_new;
        }
    }

private:
    double m_old, m_new, s_old, s_new;
    size_type cnt = 0;
};