...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
boost::accumulators::impl::immediate_rolling_variance_impl — Iterative calculation of the rolling variance.
// In header: <boost/accumulators/statistics/rolling_variance.hpp> template<typename Sample> struct immediate_rolling_variance_impl : public accumulator_base { // types typedef numeric::functional::fdiv< Sample, std::size_t >::result_type result_type; // construct/copy/destruct template<typename Args> immediate_rolling_variance_impl(Args const &); // public member functions template<typename Args> void operator()(Args const &); template<typename Args> result_type result(Args const &) const; template<typename Archive> void serialize(Archive &, const unsigned int); // private member functions template<typename T> void prevent_underflow(T &, typename boost::enable_if< boost::is_arithmetic< T >, T >::type * = 0); template<typename T> void prevent_underflow(T &, typename boost::disable_if< boost::is_arithmetic< T >, T >::type * = 0); };
Iterative calculation of sample variance is done as follows, see also http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance. For a rolling window of size , for the first samples, the variance is computed according to the formula
where the sum of squares can be recursively computed as:
and the estimate of the sample mean as:
For further samples, when the rolling window is fully filled with data, one has to take into account that the oldest sample is dropped from the window. The sample variance over the window now becomes:
where the sum of squares now equals:
and the estimated mean is:
Note that the sample variance is not defined for .