Created
October 19, 2020 18:34
-
-
Save pallas/e507f372cae484915a1becbba4ff20c2 to your computer and use it in GitHub Desktop.
Calculate mean, variance, deviation, & error using Welford's algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Author: Derrick Lyndon Pallas <[email protected]> | |
#include <cmath> | |
template <typename T = double> | |
class welford { | |
public: | |
welford() : _count(0), _mean(T(0.0)), _squared_distance(T(0.0)) { } | |
welford & operator<< (T value) { | |
T delta = value - _mean; | |
_mean += delta / ++_count; | |
_squared_distance += delta * (value - _mean); | |
return *this; | |
} | |
T samples() const { return _count; } | |
T mean() const { return _mean; } | |
T variance() const { return _squared_distance / T(_count - 1); } | |
T deviation() const { return std::sqrt(variance()); } | |
T error() const { return std::sqrt(variance()/samples()); } | |
T gosset(T u) { return (_mean - u) * std::sqrt(samples()/variance()); } | |
private: | |
unsigned _count; | |
T _mean, _squared_distance; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment