From a2f5079b3dc4ca97961879c81df39660700120cb Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Fri, 6 May 2016 09:12:33 +0200 Subject: api: add class for computing running variance --- opentrack/variance.hpp | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 opentrack/variance.hpp (limited to 'opentrack') diff --git a/opentrack/variance.hpp b/opentrack/variance.hpp new file mode 100755 index 00000000..55060b02 --- /dev/null +++ b/opentrack/variance.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include + +// 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 + +// 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. + +class variance +{ + double m_old, m_new, s_old, s_new; + unsigned long cnt; + +public: + variance() : cnt(0) {} + + void clear() { *this = variance(); } + + 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; + } + } + + double avg() const { return cnt > 0 ? m_new : 0; } + double Var() const { return cnt > 1 ? s_new/(cnt - 1) : 0; } + double stddev() const { return std::sqrt(Var()); } +}; -- cgit v1.2.3