Plaquette
 
Loading...
Searching...
No Matches
pq_moving_average.h
1
2/*
3 * pq_moving_average.h
4 *
5 * (c) 2011-2025 Sofian Audry -- info(@)sofianaudry(.)com
6 * Inspired by code by Karsten Kutza
7 * http://www.ip-atlas.com/pub/nap/nn-src/bpn.txt
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22#ifndef PQ_MOVING_AVERAGE_H_
23#define PQ_MOVING_AVERAGE_H_
24
25#include "PqCore.h"
26
27namespace pq {
28
29// When using a pre-initialized moving average value, we use this value as the stabilization time (in seconds).
30// In other words: we presume that the pre-initialized value as if it had been stabilized over that amount of time.
31constexpr float PRE_INITIALIZED_STABILIZATION_TIME = 60.0f;
32
34inline float computeMovingAverageUpdate(float runningValue, float newValue, float alpha) {
35 return runningValue + alpha * (newValue - runningValue);
36}
37
39inline float computeMovingAverageDelta(float runningValue, float delta) {
40 return runningValue + delta;
41}
42
44inline float computeAmendMovingAverageUpdate(float runningValue, float previousValue, float newValue, float alpha) {
45 return runningValue + alpha * (newValue - previousValue);
46}
47
52inline float applyMovingAverageUpdate(float& runningValue, float newValue, float alpha) {
53 return runningValue = computeMovingAverageUpdate(runningValue, newValue, alpha);
54}
55
57inline float applyMovingAverageDelta(float& runningValue, float delta) {
58 return runningValue = computeMovingAverageDelta(runningValue, delta);
59}
60
62inline float amendMovingAverageUpdate(float& runningValue, float previousValue, float newValue, float alpha) {
63 return runningValue = computeAmendMovingAverageUpdate(runningValue, previousValue, newValue, alpha);
64}
65
67inline float movingAverageExponentialAlpha(float nSamples) {
68 // Formula used is standard formula: 2 /(nSamplesTarget+1); set maximum alpha to 1.
69 return (nSamples > 1.0f ?
70 2.0f / (nSamples + 1) :
71 1.0f);
72}
73
75inline float movingAverageSimpleAlpha(float nSamples) {
76 return 1.0f / ((float)nSamples + 1);
77}
78
80float movingAverageAlpha(float sampleRate, float timeWindow=INFINITE_TIME_WINDOW, unsigned int nSamples=UINT_MAX, bool preInitialized=false);
81
82}
83
84#endif