qxLib
moving_average.inl
Go to the documentation of this file.
1 /**
2 
3  @file moving_average.inl
4  @author Khrapov
5  @date 20.08.2021
6  @copyright © Nick Khrapov, 2021. All right reserved.
7 
8 **/
9 
10 namespace qx
11 {
12 
13 template<class T>
14 inline std::vector<T> get_moving_average_simple_weights(size_t nEntries)
15 {
16  return std::vector<T>(nEntries, T(1.f) / static_cast<T>(nEntries));
17 }
18 
19 template<class T>
20 inline std::vector<T> get_moving_average_linear_weights(size_t nEntries)
21 {
22  std::vector<T> weights(nEntries, 0.f);
23 
24  const T fDenominator = static_cast<T>(nEntries * (nEntries + 1)) / T(2.f);
25 
26  for (size_t i = 0; i < nEntries; ++i)
27  weights[i] = static_cast<T>(i + 1) / fDenominator;
28 
29  return weights;
30 }
31 
32 template<class T>
33 inline std::vector<T> get_moving_average_exp_weights(size_t nEntries)
34 {
35  std::vector<T> weights(nEntries, 0.f);
36 
37  // the degree of weighting decrease, a constant smoothing
38  // factor between 0 and 1. A higher alpha discounts
39  // older observations faster
40  constexpr T fAlpha = T(0.8f);
41 
42  for (size_t i = 0; i < nEntries; ++i)
43  weights[i] = fAlpha * std::pow(1 - fAlpha, static_cast<T>(nEntries - i - 1));
44 
45  return weights;
46 }
47 
48 template<class T>
49 inline moving_average<T>::moving_average(size_t nEntries, T startValue, moving_average_weights_func<T> func)
50  : m_Value(startValue)
51  , m_Entries(nEntries, startValue)
52  , m_Weights(func(m_Entries.size()))
53 {
54 }
55 
56 template<class T>
57 inline T moving_average<T>::update(T value)
58 {
59  m_Entries.pop_front();
60  m_Entries.push_back(value);
61 
62  m_Value = T(0.f);
63  for (size_t i = 0; i < m_Entries.size(); ++i)
64  m_Value += m_Entries[i] * m_Weights[i];
65 
66  return m_Value;
67 }
68 
69 template<class T>
70 inline T moving_average<T>::get() const
71 {
72  return m_Value;
73 }
74 
75 template<class T>
77 {
78  return m_Entries.size();
79 }
80 
81 } // namespace qx
size_t get_num_entries() const
Get number of entries in average calc.
moving_average(size_t nEntries, T startValue, moving_average_weights_func< T > func=get_moving_average_simple_weights< T >)
moving_average object constructor
T update(T value)
Update moving average.
T get() const
Get current moving average.
std::vector< T > get_moving_average_exp_weights(size_t nEntries)
Generate weights for moving_average with exponential decrease, from highest weight for the most recen...
std::vector< T > get_moving_average_simple_weights(size_t nEntries)
Generate weights for moving_average as arithmetic mean.
std::vector< T > get_moving_average_linear_weights(size_t nEntries)
Generate weights for moving_average with linearly decrease, from highest weight for the most recent d...