Skip to content

Commit 4db3f6f

Browse files
feat: add exponential moving average filter (#164)
* add exponential moving average filter * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix build --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 551547a commit 4db3f6f

11 files changed

Lines changed: 345 additions & 145 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
2121
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation |
2222
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |
2323
| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) |
24-
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Moving Average |
24+
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Exponential Moving Average, Moving Average |
2525
| [Kinematics](doc/kinematics/README.md) | Forward Kinematics |
2626
| [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model |
2727
| [Optimization](doc/optimization/README.md) | Gradient Descent |

‎ROADMAP.md‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ Difficulty legend:
2424

2525
## Master list (by priority)
2626

27+
<<<<<<< Updated upstream
28+
2729
| # | Component | Target module | Difficulty |
2830
|----|------------------------------------------------------|---------------------------|------------|
2931
| 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ |
@@ -71,6 +73,57 @@ Difficulty legend:
7173
| 45 | IIR filter design (Butterworth/Chebyshev + bilinear) | `filters/passive` | ★★★★★ |
7274
| 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ |
7375
| 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ |
76+
=======
77+
| # | Component | Target module | Difficulty |
78+
|----|------------------------------------------------------|---------------------------|------------|
79+
| 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ |
80+
| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ |
81+
| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ |
82+
| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ |
83+
| 6 | Median filter | `filters/passive` | ★★☆☆☆ |
84+
| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ |
85+
| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ |
86+
| 9 | Complementary filter | `filters/active` | ★★☆☆☆ |
87+
| 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ |
88+
| 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ |
89+
| 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ |
90+
| 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ |
91+
| 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ |
92+
| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ |
93+
| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ |
94+
| 17 | Lead-lag compensator | `controllers` | ★★★☆☆ |
95+
| 18 | Quaternion type | `math` | ★★★☆☆ |
96+
| 19 | Luenberger observer + pole placement (Ackermann) | `controllers` | ★★★☆☆ |
97+
| 20 | Integral / servo state feedback (LQI) | `controllers` | ★★★☆☆ |
98+
| 21 | LMS / NLMS adaptive filter | `estimators/online` | ★★★☆☆ |
99+
| 22 | Savitzky-Golay filter | `filters/passive` | ★★★☆☆ |
100+
| 23 | CORDIC | `math` | ★★★☆☆ |
101+
| 24 | Runge-Kutta ODE integrators (RK4 + Dormand-Prince) | `solvers` | ★★★☆☆ |
102+
| 25 | Real-input FFT (RFFT) | `analysis` | ★★★☆☆ |
103+
| 26 | Controllability / Observability matrices & Gramians | `control_analysis` | ★★★☆☆ |
104+
| 27 | QR decomposition (Householder / Givens) | `solvers` | ★★★★☆ |
105+
| 28 | LU decomposition with partial pivoting | `solvers` | ★★★★☆ |
106+
| 29 | Matrix exponential (scaling & squaring + Padé) | `math` | ★★★★☆ |
107+
| 30 | Continuous → discrete conversion (`c2d`) | `math` | ★★★★☆ |
108+
| 31 | Lyapunov / Sylvester equation solvers | `solvers` | ★★★★☆ |
109+
| 32 | Transfer-function ↔ state-space conversion | `control_analysis` | ★★★★☆ |
110+
| 33 | Madgwick / Mahony AHRS | `filters/active` | ★★★★☆ |
111+
| 34 | Sliding Mode Control (SMC) | `robust_control` (new) | ★★★★☆ |
112+
| 35 | Disturbance Observer (DOB) | `robust_control` (new) | ★★★★☆ |
113+
| 36 | Active Disturbance Rejection Control (ADRC + ESO) | `robust_control` (new) | ★★★★☆ |
114+
| 37 | Hilbert transform / analytic signal / envelope | `analysis` | ★★★★☆ |
115+
| 38 | Discrete Wavelet Transform (Haar / Daubechies) | `analysis` | ★★★★☆ |
116+
| 39 | Square-root / Information Kalman filter | `filters/active` | ★★★★☆ |
117+
| 40 | Feedback linearization | `nonlinear_control` (new) | ★★★★☆ |
118+
| 41 | Backstepping controller | `nonlinear_control` (new) | ★★★★☆ |
119+
| 42 | Symmetric eigenvalue solver (Jacobi) | `solvers` | ★★★★★ |
120+
| 43 | Singular Value Decomposition (Golub-Kahan) | `solvers` | ★★★★★ |
121+
| 44 | Total Least Squares | `estimators/offline` | ★★★★★ |
122+
| 45 | IIR filter design (Butterworth/Chebyshev + bilinear) | `filters/passive` | ★★★★★ |
123+
| 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ |
124+
| 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ |
125+
126+
>>>>>>> Stashed changes
74127
75128
---
76129

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# Exponential Moving Average
2+
3+
## Overview & Motivation
4+
5+
Sensor data in embedded systems is noisy. A full moving-average buffer costs O(N) RAM and O(N)
6+
computation per sample. The exponential moving average (EMA), also called a one-pole recursive
7+
low-pass filter or leaky integrator, achieves useful smoothing with a single state word and one
8+
multiply-accumulate per sample. It is the minimal-cost filter that tracks a slowly varying DC
9+
level while suppressing high-frequency noise.
10+
11+
## Mathematical Theory
12+
13+
### Core Definition
14+
15+
Given a smoothing factor $\alpha \in (0, 1]$ and a discrete input sequence $x[n]$, the EMA
16+
output $y[n]$ obeys the first-order linear recurrence:
17+
18+
$$y[n] = \alpha \, x[n] + (1 - \alpha) \, y[n-1]$$
19+
20+
with $y[-1] = y_0$ (the initial state, often zero).
21+
22+
### Rearranged Update Form
23+
24+
Expanding the recurrence:
25+
26+
$$y[n] = y[n-1] + \alpha \bigl(x[n] - y[n-1]\bigr)$$
27+
28+
This form has one subtraction and one multiply-accumulate; it avoids computing $(1-\alpha)$
29+
explicitly and keeps the error term $(x[n] - y[n-1])$ small, which is numerically preferable in
30+
fixed-point arithmetic.
31+
32+
### Pole Location and Stability
33+
34+
The transfer function in the $z$-domain is:
35+
36+
$$H(z) = \frac{\alpha}{1 - (1-\alpha)\,z^{-1}}$$
37+
38+
The single pole is at $z = 1 - \alpha$. For $\alpha \in (0, 1]$ the pole lies in $[0, 1)$, which
39+
is strictly inside the unit circle, so the filter is unconditionally stable.
40+
41+
### DC Gain
42+
43+
Setting $z = 1$ (DC, $\omega = 0$):
44+
45+
$$H(1) = \frac{\alpha}{1 - (1-\alpha)} = 1$$
46+
47+
Unity DC gain: a constant input converges exactly to that constant.
48+
49+
### Cutoff Frequency
50+
51+
Matching the EMA pole to a first-order RC low-pass filter with time constant $\tau = 1/(2\pi f_c)$
52+
and sample period $T_s = 1/f_s$:
53+
54+
$$\alpha = \frac{T_s}{\tau + T_s} = \frac{T_s}{\frac{1}{2\pi f_c} + T_s}$$
55+
56+
### Impulse Response
57+
58+
The impulse response is $h[n] = \alpha (1-\alpha)^n \, u[n]$, which decays geometrically —
59+
hence the name "exponential" moving average.
60+
61+
## Complexity Analysis
62+
63+
| Case | Time | Space | Notes |
64+
|---------|------|-------|----------------------------------------|
65+
| Best | O(1) | O(1) | Single MAC per sample, one state word |
66+
| Average | O(1) | O(1) | Identical regardless of input |
67+
| Worst | O(1) | O(1) | No data-dependent branches on hot path |
68+
69+
## Step-by-Step Walkthrough
70+
71+
Suppose $\alpha = 0.5$, $y[-1] = 0$, and the input is the unit impulse $x = [1, 0, 0, 0, \ldots]$.
72+
73+
| $n$ | $x[n]$ | $x[n] - y[n-1]$ | $\alpha \cdot \Delta$ | $y[n]$ |
74+
|-----|--------|----------------------|-----------------------|----------|
75+
| 0 | 1 | $1 - 0 = 1$ | $0.5$ | $0.5$ |
76+
| 1 | 0 | $0 - 0.5 = -0.5$ | $-0.25$ | $0.25$ |
77+
| 2 | 0 | $0 - 0.25 = -0.25$ | $-0.125$ | $0.125$ |
78+
| 3 | 0 | $0 - 0.125 = -0.125$ | $-0.0625$ | $0.0625$ |
79+
80+
Each output is half the previous, confirming $h[n] = (0.5)^{n+1}$.
81+
82+
## Pitfalls & Edge Cases
83+
84+
- $\alpha \to 0$: The filter barely reacts; the time constant grows toward infinity. At exactly
85+
zero the state never updates (division by zero in the cutoff formula).
86+
- $\alpha = 1$: Pure passthrough — no smoothing at all; the output equals the input exactly.
87+
- Initial transient: If the initial state differs significantly from the true signal level, the
88+
output will have a startup transient lasting approximately $1/\alpha$ samples. Seeding the
89+
state with the first sample eliminates this.
90+
- Floating-point accumulation: Long runs of constant input may show residual drift at the level
91+
of floating-point epsilon relative to the signal magnitude; this is negligible for float32.
92+
93+
## Variants & Generalizations
94+
95+
- **Double EMA (DEMA)**: Applies the EMA twice and corrects for lag: $2\,y_1[n] - y_2[n]$.
96+
Reduces lag at the cost of one extra state word and multiply.
97+
- **Kaufman Adaptive Moving Average (KAMA)**: Adjusts $\alpha$ dynamically based on market
98+
efficiency ratio; the same one-pole structure with a time-varying coefficient.
99+
- **Exponentially Weighted Moving Variance**: Tracks variance alongside the mean using a second
100+
recurrence on the squared error.
101+
- **Higher-order cascades**: Cascading $k$ EMA stages produces a Butterworth-like response with
102+
$k$ poles and $-20k$ dB/decade roll-off.
103+
104+
## Applications
105+
106+
- Sensor de-noising (IMU, ADC, temperature) where buffer RAM is scarce.
107+
- DC-offset tracking and removal.
108+
- Smoothed feedback signals in PID control loops.
109+
- Battery voltage estimation.
110+
- Signal envelope detection.
111+
112+
## Connections to Other Algorithms
113+
114+
- **FIR moving average**: Linear-phase alternative; symmetric impulse response gives zero group
115+
delay distortion but requires O(N) RAM and O(N) MACs.
116+
- **Biquad cascade (IIR)**: Higher-order roll-off at the cost of two state words per section and
117+
potential instability if coefficients are not quantised carefully.
118+
- **Kalman filter (scalar)**: The steady-state scalar Kalman gain is equivalent to an EMA with
119+
$\alpha = K$ determined by the noise ratio; EMA is the optimal estimator for a random-walk
120+
signal in Gaussian noise.
121+
122+
## References & Further Reading
123+
124+
- S. W. Smith, *The Scientist and Engineer's Guide to Digital Signal Processing*, Ch. 19
125+
(Recursive / single-pole filters). Available free at dspguide.com.
126+
- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Ch. 5 (IIR filter
127+
design).
128+
- R. G. Lyons, *Understanding Digital Signal Processing*, 3rd ed., Ch. 6 (recursive filters).

‎numerical/filters/passive/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@ target_link_libraries(numerical.filters.passive ${NUMERICAL_VISIBILITY}
1111
)
1212

1313
target_sources(numerical.filters.passive PRIVATE
14+
ExponentialMovingAverage.hpp
1415
Fir.hpp
1516
Iir.hpp
1617
MovingAverage.hpp
1718
)
1819

1920
numerical_add_coverage_sources(numerical.filters.passive
21+
ExponentialMovingAverage.cpp
2022
Fir.cpp
2123
Iir.cpp
2224
MovingAverage.cpp
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#include "numerical/filters/passive/ExponentialMovingAverage.hpp"
2+
3+
namespace filters::passive
4+
{
5+
template class ExponentialMovingAverage<float>;
6+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#pragma once
2+
3+
#if defined(__GNUC__) || defined(__clang__)
4+
#pragma GCC optimize("O3", "fast-math")
5+
#endif
6+
7+
#include "numerical/math/CompilerOptimizations.hpp"
8+
#include <cassert>
9+
#include <numbers>
10+
#include <type_traits>
11+
12+
namespace filters::passive
13+
{
14+
template<typename T>
15+
class ExponentialMovingAverage
16+
{
17+
static_assert(std::is_floating_point_v<T>, "ExponentialMovingAverage supports floating-point types");
18+
19+
public:
20+
explicit ExponentialMovingAverage(T alpha, T initial = T{}) noexcept;
21+
22+
OPTIMIZE_FOR_SPEED T Filter(T input) noexcept;
23+
void Reset(T value = T{}) noexcept;
24+
void SetAlpha(T alpha) noexcept;
25+
26+
static T AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept;
27+
28+
private:
29+
T alpha;
30+
T state;
31+
};
32+
33+
//// Implementation ////
34+
35+
template<typename T>
36+
ExponentialMovingAverage<T>::ExponentialMovingAverage(T alpha, T initial) noexcept
37+
: alpha{ alpha }
38+
, state{ initial }
39+
{
40+
assert(alpha > T{} && alpha <= T{ 1 });
41+
}
42+
43+
template<typename T>
44+
OPTIMIZE_FOR_SPEED T ExponentialMovingAverage<T>::Filter(T input) noexcept
45+
{
46+
state = state + alpha * (input - state);
47+
return state;
48+
}
49+
50+
template<typename T>
51+
void ExponentialMovingAverage<T>::Reset(T value) noexcept
52+
{
53+
state = value;
54+
}
55+
56+
template<typename T>
57+
void ExponentialMovingAverage<T>::SetAlpha(T newAlpha) noexcept
58+
{
59+
assert(newAlpha > T{} && newAlpha <= T{ 1 });
60+
alpha = newAlpha;
61+
}
62+
63+
template<typename T>
64+
T ExponentialMovingAverage<T>::AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept
65+
{
66+
const T dt{ T{ 1 } / sampleRateHz };
67+
const T rc{ T{ 1 } / (T{ 2 } * std::numbers::pi_v<T> * cutoffHz) };
68+
return dt / (rc + dt);
69+
}
70+
71+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
72+
extern template class ExponentialMovingAverage<float>;
73+
#endif
74+
}

‎numerical/filters/passive/test/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ target_link_libraries(numerical.filters.passive_test PUBLIC
1010
)
1111

1212
target_sources(numerical.filters.passive_test PRIVATE
13+
TestExponentialMovingAverage.cpp
1314
TestFir.cpp
1415
TestIir.cpp
1516
TestMovingAverage.cpp
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#include "numerical/filters/passive/ExponentialMovingAverage.hpp"
2+
#include "numerical/math/Tolerance.hpp"
3+
#include "gtest/gtest.h"
4+
5+
namespace
6+
{
7+
class TestExponentialMovingAverage
8+
: public ::testing::Test
9+
{
10+
public:
11+
filters::passive::ExponentialMovingAverage<float> ema{ 0.5f };
12+
};
13+
}
14+
15+
TEST_F(TestExponentialMovingAverage, impulse_decays_geometrically)
16+
{
17+
const float inputs[]{ 1.0f, 0.0f, 0.0f, 0.0f };
18+
const float expected[]{ 0.5f, 0.25f, 0.125f, 0.0625f };
19+
20+
for (int i = 0; i < 4; ++i)
21+
EXPECT_NEAR(ema.Filter(inputs[i]), expected[i], 1e-6f);
22+
}
23+
24+
TEST_F(TestExponentialMovingAverage, constant_input_converges_to_dc)
25+
{
26+
filters::passive::ExponentialMovingAverage<float> filter{ 0.25f };
27+
const float c{ 0.8f };
28+
29+
float output{};
30+
for (int i = 0; i < 50; ++i)
31+
output = filter.Filter(c);
32+
33+
EXPECT_NEAR(output, c, math::Tolerance<float>());
34+
}
35+
36+
TEST_F(TestExponentialMovingAverage, alpha_one_is_passthrough)
37+
{
38+
filters::passive::ExponentialMovingAverage<float> filter{ 1.0f };
39+
const float inputs[]{ 0.3f, -0.7f, 1.0f, 0.0f };
40+
41+
for (const float x : inputs)
42+
EXPECT_NEAR(filter.Filter(x), x, 1e-6f);
43+
}
44+
45+
TEST_F(TestExponentialMovingAverage, step_response_matches_time_constant)
46+
{
47+
filters::passive::ExponentialMovingAverage<float> filter{ 0.1f };
48+
49+
float output{};
50+
for (int i = 0; i < 10; ++i)
51+
output = filter.Filter(1.0f);
52+
53+
EXPECT_NEAR(output, 0.6513f, 1e-3f);
54+
}
55+
56+
TEST_F(TestExponentialMovingAverage, reset_clears_state)
57+
{
58+
ema.Filter(1.0f);
59+
ema.Filter(1.0f);
60+
ema.Reset(0.0f);
61+
62+
const float nextInput{ 0.6f };
63+
EXPECT_NEAR(ema.Filter(nextInput), 0.5f * nextInput, 1e-6f);
64+
}
65+
66+
TEST_F(TestExponentialMovingAverage, set_alpha_changes_smoothing)
67+
{
68+
ema.Filter(1.0f);
69+
ema.SetAlpha(1.0f);
70+
71+
EXPECT_NEAR(ema.Filter(0.0f), 0.0f, 1e-6f);
72+
}
73+
74+
TEST_F(TestExponentialMovingAverage, alpha_from_cutoff_produces_valid_alpha)
75+
{
76+
const float alpha{ filters::passive::ExponentialMovingAverage<float>::AlphaFromCutoff(100.0f, 1000.0f) };
77+
EXPECT_GT(alpha, 0.0f);
78+
EXPECT_LE(alpha, 1.0f);
79+
EXPECT_NEAR(alpha, 0.3859f, 1e-3f);
80+
}

0 commit comments

Comments
 (0)