Repository navigation
feat: add exponential moving average filter #164
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
gabrielfrasantos
merged 5 commits into
main
from
feature/add-exponential-moving-average-filter
Jul 26, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
77e315d
add exponential moving average filter
gabrielfrasantos 7dffeee
Apply suggestions from code review
gabrielfrasantos 4094348
Merge branch 'main' into feature/add-exponential-moving-average-filter
gabrielfrasantos 8e9a25a
fix build
gabrielfrasantos d8e411b
merge main
gabrielfrasantos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
|
gabrielfrasantos marked this conversation as resolved.
Resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| # Exponential Moving Average | ||
|
|
||
| ## Overview & Motivation | ||
|
|
||
| Sensor data in embedded systems is noisy. A full moving-average buffer costs O(N) RAM and O(N) | ||
| computation per sample. The exponential moving average (EMA), also called a one-pole recursive | ||
| low-pass filter or leaky integrator, achieves useful smoothing with a single state word and one | ||
| multiply-accumulate per sample. It is the minimal-cost filter that tracks a slowly varying DC | ||
| level while suppressing high-frequency noise. | ||
|
|
||
| ## Mathematical Theory | ||
|
|
||
| ### Core Definition | ||
|
|
||
| Given a smoothing factor $\alpha \in (0, 1]$ and a discrete input sequence $x[n]$, the EMA | ||
| output $y[n]$ obeys the first-order linear recurrence: | ||
|
|
||
| $$y[n] = \alpha \, x[n] + (1 - \alpha) \, y[n-1]$$ | ||
|
|
||
| with $y[-1] = y_0$ (the initial state, often zero). | ||
|
|
||
| ### Rearranged Update Form | ||
|
|
||
| Expanding the recurrence: | ||
|
|
||
| $$y[n] = y[n-1] + \alpha \bigl(x[n] - y[n-1]\bigr)$$ | ||
|
|
||
| This form has one subtraction and one multiply-accumulate; it avoids computing $(1-\alpha)$ | ||
| explicitly and keeps the error term $(x[n] - y[n-1])$ small, which is numerically preferable in | ||
| fixed-point arithmetic. | ||
|
|
||
| ### Pole Location and Stability | ||
|
|
||
| The transfer function in the $z$-domain is: | ||
|
|
||
| $$H(z) = \frac{\alpha}{1 - (1-\alpha)\,z^{-1}}$$ | ||
|
|
||
| The single pole is at $z = 1 - \alpha$. For $\alpha \in (0, 1]$ the pole lies in $[0, 1)$, which | ||
| is strictly inside the unit circle, so the filter is unconditionally stable. | ||
|
|
||
| ### DC Gain | ||
|
|
||
| Setting $z = 1$ (DC, $\omega = 0$): | ||
|
|
||
| $$H(1) = \frac{\alpha}{1 - (1-\alpha)} = 1$$ | ||
|
|
||
| Unity DC gain: a constant input converges exactly to that constant. | ||
|
|
||
| ### Cutoff Frequency | ||
|
|
||
| Matching the EMA pole to a first-order RC low-pass filter with time constant $\tau = 1/(2\pi f_c)$ | ||
| and sample period $T_s = 1/f_s$: | ||
|
|
||
| $$\alpha = \frac{T_s}{\tau + T_s} = \frac{T_s}{\frac{1}{2\pi f_c} + T_s}$$ | ||
|
|
||
| ### Impulse Response | ||
|
|
||
| The impulse response is $h[n] = \alpha (1-\alpha)^n \, u[n]$, which decays geometrically — | ||
| hence the name "exponential" moving average. | ||
|
|
||
| ## Complexity Analysis | ||
|
|
||
| | Case | Time | Space | Notes | | ||
| |---------|------|-------|----------------------------------------| | ||
| | Best | O(1) | O(1) | Single MAC per sample, one state word | | ||
| | Average | O(1) | O(1) | Identical regardless of input | | ||
| | Worst | O(1) | O(1) | No data-dependent branches on hot path | | ||
|
|
||
| ## Step-by-Step Walkthrough | ||
|
|
||
| Suppose $\alpha = 0.5$, $y[-1] = 0$, and the input is the unit impulse $x = [1, 0, 0, 0, \ldots]$. | ||
|
|
||
| | $n$ | $x[n]$ | $x[n] - y[n-1]$ | $\alpha \cdot \Delta$ | $y[n]$ | | ||
| |-----|--------|----------------------|-----------------------|----------| | ||
| | 0 | 1 | $1 - 0 = 1$ | $0.5$ | $0.5$ | | ||
| | 1 | 0 | $0 - 0.5 = -0.5$ | $-0.25$ | $0.25$ | | ||
| | 2 | 0 | $0 - 0.25 = -0.25$ | $-0.125$ | $0.125$ | | ||
| | 3 | 0 | $0 - 0.125 = -0.125$ | $-0.0625$ | $0.0625$ | | ||
|
|
||
| Each output is half the previous, confirming $h[n] = (0.5)^{n+1}$. | ||
|
|
||
| ## Pitfalls & Edge Cases | ||
|
|
||
| - $\alpha \to 0$: The filter barely reacts; the time constant grows toward infinity. At exactly | ||
| zero the state never updates (division by zero in the cutoff formula). | ||
| - $\alpha = 1$: Pure passthrough — no smoothing at all; the output equals the input exactly. | ||
| - Initial transient: If the initial state differs significantly from the true signal level, the | ||
| output will have a startup transient lasting approximately $1/\alpha$ samples. Seeding the | ||
| state with the first sample eliminates this. | ||
| - Floating-point accumulation: Long runs of constant input may show residual drift at the level | ||
| of floating-point epsilon relative to the signal magnitude; this is negligible for float32. | ||
|
|
||
| ## Variants & Generalizations | ||
|
|
||
| - **Double EMA (DEMA)**: Applies the EMA twice and corrects for lag: $2\,y_1[n] - y_2[n]$. | ||
| Reduces lag at the cost of one extra state word and multiply. | ||
| - **Kaufman Adaptive Moving Average (KAMA)**: Adjusts $\alpha$ dynamically based on market | ||
| efficiency ratio; the same one-pole structure with a time-varying coefficient. | ||
| - **Exponentially Weighted Moving Variance**: Tracks variance alongside the mean using a second | ||
| recurrence on the squared error. | ||
| - **Higher-order cascades**: Cascading $k$ EMA stages produces a Butterworth-like response with | ||
| $k$ poles and $-20k$ dB/decade roll-off. | ||
|
|
||
| ## Applications | ||
|
|
||
| - Sensor de-noising (IMU, ADC, temperature) where buffer RAM is scarce. | ||
| - DC-offset tracking and removal. | ||
| - Smoothed feedback signals in PID control loops. | ||
| - Battery voltage estimation. | ||
| - Signal envelope detection. | ||
|
|
||
| ## Connections to Other Algorithms | ||
|
|
||
| - **FIR moving average**: Linear-phase alternative; symmetric impulse response gives zero group | ||
| delay distortion but requires O(N) RAM and O(N) MACs. | ||
| - **Biquad cascade (IIR)**: Higher-order roll-off at the cost of two state words per section and | ||
| potential instability if coefficients are not quantised carefully. | ||
| - **Kalman filter (scalar)**: The steady-state scalar Kalman gain is equivalent to an EMA with | ||
| $\alpha = K$ determined by the noise ratio; EMA is the optimal estimator for a random-walk | ||
| signal in Gaussian noise. | ||
|
|
||
| ## References & Further Reading | ||
|
|
||
| - S. W. Smith, *The Scientist and Engineer's Guide to Digital Signal Processing*, Ch. 19 | ||
| (Recursive / single-pole filters). Available free at dspguide.com. | ||
| - A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Ch. 5 (IIR filter | ||
| design). | ||
| - R. G. Lyons, *Understanding Digital Signal Processing*, 3rd ed., Ch. 6 (recursive filters). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| #include "numerical/filters/passive/ExponentialMovingAverage.hpp" | ||
|
|
||
| namespace filters::passive | ||
| { | ||
| template class ExponentialMovingAverage<float>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| #pragma once | ||
|
|
||
| #if defined(__GNUC__) || defined(__clang__) | ||
| #pragma GCC optimize("O3", "fast-math") | ||
| #endif | ||
|
|
||
| #include "numerical/math/CompilerOptimizations.hpp" | ||
| #include <cassert> | ||
| #include <numbers> | ||
| #include <type_traits> | ||
|
|
||
| namespace filters::passive | ||
| { | ||
| template<typename T> | ||
| class ExponentialMovingAverage | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "ExponentialMovingAverage supports floating-point types"); | ||
|
|
||
| public: | ||
| explicit ExponentialMovingAverage(T alpha, T initial = T{}) noexcept; | ||
|
|
||
| OPTIMIZE_FOR_SPEED T Filter(T input) noexcept; | ||
| void Reset(T value = T{}) noexcept; | ||
| void SetAlpha(T alpha) noexcept; | ||
|
|
||
| static T AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept; | ||
|
|
||
| private: | ||
| T alpha; | ||
| T state; | ||
| }; | ||
|
|
||
| //// Implementation //// | ||
|
|
||
| template<typename T> | ||
| ExponentialMovingAverage<T>::ExponentialMovingAverage(T alpha, T initial) noexcept | ||
| : alpha{ alpha } | ||
| , state{ initial } | ||
| { | ||
| assert(alpha > T{} && alpha <= T{ 1 }); | ||
| } | ||
|
|
||
| template<typename T> | ||
| OPTIMIZE_FOR_SPEED T ExponentialMovingAverage<T>::Filter(T input) noexcept | ||
| { | ||
| state = state + alpha * (input - state); | ||
| return state; | ||
| } | ||
|
|
||
| template<typename T> | ||
| void ExponentialMovingAverage<T>::Reset(T value) noexcept | ||
| { | ||
| state = value; | ||
| } | ||
|
|
||
| template<typename T> | ||
| void ExponentialMovingAverage<T>::SetAlpha(T newAlpha) noexcept | ||
| { | ||
| assert(newAlpha > T{} && newAlpha <= T{ 1 }); | ||
| alpha = newAlpha; | ||
| } | ||
|
|
||
| template<typename T> | ||
| T ExponentialMovingAverage<T>::AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept | ||
| { | ||
| const T dt{ T{ 1 } / sampleRateHz }; | ||
| const T rc{ T{ 1 } / (T{ 2 } * std::numbers::pi_v<T> * cutoffHz) }; | ||
| return dt / (rc + dt); | ||
| } | ||
|
|
||
| #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD | ||
| extern template class ExponentialMovingAverage<float>; | ||
| #endif | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
80 changes: 80 additions & 0 deletions
80
numerical/filters/passive/test/TestExponentialMovingAverage.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| #include "numerical/filters/passive/ExponentialMovingAverage.hpp" | ||
| #include "numerical/math/Tolerance.hpp" | ||
| #include "gtest/gtest.h" | ||
|
|
||
| namespace | ||
| { | ||
| class TestExponentialMovingAverage | ||
| : public ::testing::Test | ||
| { | ||
| public: | ||
| filters::passive::ExponentialMovingAverage<float> ema{ 0.5f }; | ||
| }; | ||
| } | ||
|
|
||
| TEST_F(TestExponentialMovingAverage, impulse_decays_geometrically) | ||
| { | ||
| const float inputs[]{ 1.0f, 0.0f, 0.0f, 0.0f }; | ||
| const float expected[]{ 0.5f, 0.25f, 0.125f, 0.0625f }; | ||
|
|
||
| for (int i = 0; i < 4; ++i) | ||
| EXPECT_NEAR(ema.Filter(inputs[i]), expected[i], 1e-6f); | ||
| } | ||
|
|
||
| TEST_F(TestExponentialMovingAverage, constant_input_converges_to_dc) | ||
| { | ||
| filters::passive::ExponentialMovingAverage<float> filter{ 0.25f }; | ||
| const float c{ 0.8f }; | ||
|
|
||
| float output{}; | ||
| for (int i = 0; i < 50; ++i) | ||
| output = filter.Filter(c); | ||
|
|
||
| EXPECT_NEAR(output, c, math::Tolerance<float>()); | ||
| } | ||
|
|
||
| TEST_F(TestExponentialMovingAverage, alpha_one_is_passthrough) | ||
| { | ||
| filters::passive::ExponentialMovingAverage<float> filter{ 1.0f }; | ||
| const float inputs[]{ 0.3f, -0.7f, 1.0f, 0.0f }; | ||
|
|
||
| for (const float x : inputs) | ||
| EXPECT_NEAR(filter.Filter(x), x, 1e-6f); | ||
| } | ||
|
|
||
| TEST_F(TestExponentialMovingAverage, step_response_matches_time_constant) | ||
| { | ||
| filters::passive::ExponentialMovingAverage<float> filter{ 0.1f }; | ||
|
|
||
| float output{}; | ||
| for (int i = 0; i < 10; ++i) | ||
| output = filter.Filter(1.0f); | ||
|
|
||
| EXPECT_NEAR(output, 0.6513f, 1e-3f); | ||
| } | ||
|
|
||
| TEST_F(TestExponentialMovingAverage, reset_clears_state) | ||
| { | ||
| ema.Filter(1.0f); | ||
| ema.Filter(1.0f); | ||
| ema.Reset(0.0f); | ||
|
|
||
| const float nextInput{ 0.6f }; | ||
| EXPECT_NEAR(ema.Filter(nextInput), 0.5f * nextInput, 1e-6f); | ||
| } | ||
|
|
||
| TEST_F(TestExponentialMovingAverage, set_alpha_changes_smoothing) | ||
| { | ||
| ema.Filter(1.0f); | ||
| ema.SetAlpha(1.0f); | ||
|
|
||
| EXPECT_NEAR(ema.Filter(0.0f), 0.0f, 1e-6f); | ||
| } | ||
|
|
||
| TEST_F(TestExponentialMovingAverage, alpha_from_cutoff_produces_valid_alpha) | ||
| { | ||
| const float alpha{ filters::passive::ExponentialMovingAverage<float>::AlphaFromCutoff(100.0f, 1000.0f) }; | ||
| EXPECT_GT(alpha, 0.0f); | ||
| EXPECT_LE(alpha, 1.0f); | ||
| EXPECT_NEAR(alpha, 0.3859f, 1e-3f); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.