ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
RunningAverage.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2010-2026 The ESPResSo project
3 * Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
4 * Max-Planck-Institute for Polymer Research, Theory Group
5 *
6 * This file is part of ESPResSo.
7 *
8 * ESPResSo is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * ESPResSo is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#ifndef STATISTICS_RUNING_AVERAGE_HPP
23#define STATISTICS_RUNING_AVERAGE_HPP
24
25#include <algorithm>
26#include <cmath>
27#include <limits>
28
29namespace Utils {
30namespace Statistics {
31
32/**
33 * \brief Keep running average and variance.
34 * The average should be numerically stable.
35 */
36template <typename Scalar> class RunningAverage {
37public:
39 : m_n(0), m_old_avg(0), m_new_avg(0), m_old_var(0), m_new_var(0.0),
40 m_min(std::numeric_limits<Scalar>::max()),
41 m_max(-std::numeric_limits<Scalar>::max()) {}
42 void add_sample(Scalar s) {
43 m_n++;
44
45 if (m_n == 1) {
46 m_old_avg = m_new_avg = s;
47 } else {
48 m_new_avg = m_old_avg + (s - m_old_avg) / m_n;
49 m_new_var = m_old_var + (s - m_old_avg) * (s - m_new_avg);
50
51 m_old_avg = m_new_avg;
52 m_old_var = m_new_var;
53 }
54
55 m_min = std::min(m_min, s);
56 m_max = std::max(m_max, s);
57 }
58
59 void clear() {
60 m_n = 0;
61 m_old_avg = m_new_avg = 0;
62 m_old_var = m_new_var = 0;
63 m_min = std::numeric_limits<Scalar>::max();
64 m_max = -std::numeric_limits<Scalar>::max();
65 }
66
67 int n() const { return m_n; }
68
69 /** Average of the samples */
70 Scalar avg() const {
71 if (m_n > 0)
72 return m_new_avg;
73
74 return 0.0;
75 }
76 /** Variance of the samples */
77 Scalar var() const {
78 if (m_n > 1)
79 return m_new_var / m_n;
80
81 return 0.0;
82 }
83
84 /** Standard deviation of the samples */
85 Scalar sig() const { return std::sqrt(var()); }
86
87 /** Minimum */
88 Scalar min() const { return m_min; }
89
90 /** Minimum */
91 Scalar max() const { return m_max; }
92
93private:
94 int m_n;
95 Scalar m_old_avg, m_new_avg;
96 Scalar m_old_var, m_new_var;
97 Scalar m_min, m_max;
98};
99} // namespace Statistics
100} // namespace Utils
101
102#endif
Keep running average and variance.
Scalar avg() const
Average of the samples.
Scalar sig() const
Standard deviation of the samples.
Scalar var() const
Variance of the samples.
STL namespace.