Note: I first published this tutorial on my old blog in March 2018. This version is rewritten and expanded: derivation, equivalent window length, bias correction, a fixed-point implementation for microcontrollers, and plots generated from a synthetic signal.

The problem: noisy sensor data

Very often we have a long sequence of data with a high variance caused by noise: an ADC reading a thermistor, the range returned by an ultrasonic sensor, the current drawn by a motor, the frame rate of a camera pipeline. Before using these values we want to smooth them, keeping the slow trend and rejecting the fast random fluctuations.

The textbook answer is the moving window average: keep the last N values and use their mean. It works, but on a small microcontroller it has a cost that is easy to underestimate. In this tutorial I show the approach I have used many times since I discovered it following the Deep Learning Specialization on Coursera by Andrew Ng: the Exponential Weighted Average (EWA, also known as Exponential Moving Average, EMA). It replaces the buffer with a single variable and the whole algorithm with one line of code.

The simple moving average and its cost

The simple moving average (SMA) of the last N values v at time t is:

Simple moving average: m_t equals one over N times the sum of v_(t-k) for k from 0 to N-1

The typical implementation uses a circular buffer of size N: each new value replaces the oldest one, and the mean is computed again. Summing N values at every sample costs N additions, so the “smart” version keeps a running sum, adds the new value and subtracts the one that leaves the window:

Running sum: S_t equals S_(t-1) plus v_t minus v_(t-N), and m_t equals S_t over N

This is O(1) per sample, but it is not free:

  • Memory: you still need the buffer, N values. A window of 100 float values is 400 bytes of RAM, which matters on a small MCU, and it is multiplied by the number of channels you filter.
  • Error prone: you must manage the write index, the wrap-around and the start-up phase, when the buffer is not yet full and you must divide by the number of values received so far instead of N.
  • Numerical drift: with floating-point values, the running sum accumulates rounding errors because each value is added and later subtracted at different magnitudes of the sum. With integer values there is no drift, but the accumulator must be sized to hold N times the maximum value.

From the incremental mean to the exponential weighted average

Dividing the running sum by N we can write the moving average as an update of the previous mean:

Incremental moving average: m_t equals m_(t-1) plus (v_t minus v_(t-N)) over N

The only reason we need the buffer is the term vt-N, the value that leaves the window. Now the trick: we do not know that old value without storing it, but we have a good estimate of a “typical” value inside the window, the mean itself. Replacing vt-N with mt-1:

Approximation: m_t is approximately m_(t-1) plus (v_t minus m_(t-1)) over N, which equals (1 minus 1 over N) times m_(t-1) plus 1 over N times v_t

Calling α = 1 - 1/N we obtain the Exponential Weighted Average:

Exponential weighted average: m_t equals alpha times m_(t-1) plus (1 minus alpha) times v_t, with m_0 equal to 0

mt is the mean at time t, vt is the new incoming value at time t, and α (between 0 and 1) is the weight given to the past. The only value that we must keep is m, which propagates through time: no buffer, no index, one multiply-add per sample.

Naming: I use α as the weight of the old mean, as in my original tutorial. Andrew Ng’s course calls the same parameter β. Many signal processing texts and Wikipedia use α for the weight of the new sample, which is 1 - α here. Always check the convention before copying a value from somewhere else.

Why it is called “exponential”

Let’s unroll the recursion, replacing each mt-1 with its own definition, back to m0 = 0:

Unrolled EWA: m_t equals (1 minus alpha) times the sum for k from 1 to t of alpha to the power (t minus k) times v_k

Every past value contributes to the mean, but its weight decreases exponentially with its age: the newest value has weight 1 - α, the previous one (1 - α)·α, then (1 - α)·α², and so on. The moving average, instead, gives the same weight 1/N to the last N values and zero to everything older.

Weight of each past sample versus its age: a flat 0.05 weight for the last 20 samples of the simple moving average, and two exponentially decaying curves for EWA with alpha 0.905 and alpha 0.95
Weight given to each past sample. The moving average (N = 20) is a rectangle; the EWA weights decay exponentially and never reach exactly zero.

The equivalent window length

How can this formula approximate a moving window average? We can approximate the “width” of the window with:

Window size: W is approximately 1 over (1 minus alpha), equivalently alpha equals (W minus 1) over W

This is exactly the α = 1 - 1/N of the derivation above. W is the time constant of the filter: since αW ≈ 1/e for α close to 1, the samples older than W together weigh only about 37%, while the last W samples carry about 63% of the total weight.

There is a second way to match an EWA to a moving average of N samples, and it is worth knowing because it gives different numbers: choose α = (N - 1)/(N + 1). With this value the EWA has the same noise reduction as the moving average (the variance of white noise is divided by N in both cases) and the same mean age of the samples, (N - 1)/2. Reversing it, an EWA with weight α filters noise like a moving average of N = (1 + α)/(1 - α) samples.

α Time constant 1/(1 - α) Moving average with the same noise reduction
0.9 10 19
0.95 20 39
0.97 ≈ 33 ≈ 66
0.975 40 79
0.98 50 99
0.99 100 199

In practice: use W = 1/(1 - α) as an intuition of “how far back the filter remembers”, and α = (N - 1)/(N + 1) when you replace an existing moving average and want the same amount of smoothing.

Moving average versus EWA on a noisy signal

To compare the filters I generated a synthetic signal that looks like 12-bit ADC readings: a constant level of 1200 counts, a step to 2400 counts at sample 150, a slow sine wave from sample 250, and Gaussian noise with a standard deviation of 150 counts. Then I filtered it with a 20-sample moving average and with two EWAs: α = 0.95 (time constant 20) and α = 19/21 ≈ 0.905 (same noise reduction as the moving average).

Noisy synthetic ADC signal with a step and a sine wave, filtered by a 20 sample moving average and by two exponential weighted averages; a zoomed panel shows the response to the step
Synthetic noisy signal filtered by a 20-sample moving average and two EWAs. Bottom: zoom on the step at sample 150.

What the plot shows, with the numbers measured on this run:

  • Noise: on the flat parts of the signal the residual noise (standard deviation) drops from about 161 counts to 34 with the moving average, 37 with the EWA at α = 0.905, and 22 with the EWA at α = 0.95. The α = (N - 1)/(N + 1) rule works as expected.
  • Delay: after the step, the moving average reaches 90% of the new level in 18 samples, the EWA at α = 0.905 in 20, the EWA at α = 0.95 in 38. More smoothing always means more delay: the EWA does not escape this trade-off, it just gets there with one variable instead of a buffer.
  • Shape: the moving average responds to a step with a straight ramp that ends exactly N samples later; the EWA responds with an exponential curve that is fast at the beginning and slow at the end. On a sine wave, both lag behind and reduce the amplitude a little.

The start-up bias and its correction

There is a problem with the formula as written: m0 = 0. For the first values the mean is really “slow” and very close to zero, because the filter behaves as if it had seen a long history of zeros. With α = 0.95 it takes about 45 samples to reach 90% of the real value.

The unrolled formula tells us why, and how to fix it: the weights of the first t samples do not sum to 1, but to 1 - αt. Dividing by that sum gives a correctly normalized weighted average from the first sample:

Bias correction: the sum of the weights is 1 minus alpha to the t, so the corrected mean m-hat_t equals m_t divided by (1 minus alpha to the t)

At t = 1 the corrected mean is exactly the first sample, and as t grows αt goes to zero and the correction disappears. You keep updating the uncorrected mt and only correct the value you read.

A simpler alternative, popular on microcontrollers, is to seed the filter with the first sample: m1 = v1. It costs nothing, but the first sample keeps a weight of αt-1: if it is an outlier, it pollutes the mean for a while. Bias correction instead weighs the first samples as they deserve.

First 90 samples of the synthetic signal: the uncorrected EWA starts from zero and slowly rises, while the bias corrected EWA and the EWA seeded with the first sample follow the true level from the start
First 90 samples with α = 0.95. Without correction the EWA starts from zero and needs tens of samples to catch up.

C++ implementation

The original version of this class is in my CSmartMean gist. This is a modernized version: it is a template, so you can use float on a microcontroller with a single precision FPU (for example an ARM® Cortex®-M4F) and double on a PC, and it updates αt with one multiplication per sample instead of calling pow().

// exp_weighted_average.hpp
#ifndef EXP_WEIGHTED_AVERAGE_HPP
#define EXP_WEIGHTED_AVERAGE_HPP

#include <cstddef>
#include <limits>

/*!
 * \brief Exponential Weighted Average with bias correction.
 *
 * m'_t = alpha * m'_{t-1} + (1 - alpha) * v_t   (raw, biased toward 0)
 * m_t  = m'_t / (1 - alpha^t)                    (bias corrected)
 *
 * T can be float (MCUs with a single precision FPU) or double.
 */
template <typename T = float>
class ExpWeightedAverage
{
public:
    /// \param alpha weight of the previous mean, in [0, 1)
    explicit ExpWeightedAverage(T alpha) : mAlpha(alpha) {}

    /// Build the filter from the desired equivalent window size (>= 1)
    static ExpWeightedAverage fromWindow(T winSize)
    {
        return ExpWeightedAverage((winSize - T(1)) / winSize);
    }

    /// Add a new sample and return the updated (bias corrected) mean
    T addValue(T val)
    {
        mRaw = mAlpha * mRaw + (T(1) - mAlpha) * val;
        // alpha^t without calling pow() every sample. Once it is below the
        // machine epsilon, (1 - alpha^t) == 1: set it to 0 to avoid denormals.
        mAlphaPow *= mAlpha;
        if (mAlphaPow < std::numeric_limits<T>::epsilon()) mAlphaPow = T(0);
        mMean = mRaw / (T(1) - mAlphaPow);
        ++mCount;
        return mMean;
    }

    T mean() const { return mMean; }       ///< Bias corrected mean
    T rawMean() const { return mRaw; }     ///< Mean without bias correction
    std::size_t count() const { return mCount; }

    void reset()
    {
        mRaw = T(0);
        mMean = T(0);
        mAlphaPow = T(1);
        mCount = 0;
    }

private:
    T mAlpha;
    T mRaw = T(0);
    T mMean = T(0);
    T mAlphaPow = T(1);
    std::size_t mCount = 0;
};

#endif // EXP_WEIGHTED_AVERAGE_HPP

Using it, many lines of code are replaced by one call per sample:

#include "exp_weighted_average.hpp"

// About the last 20 values: alpha = 19/20 = 0.95
auto filter = ExpWeightedAverage<float>::fromWindow(20.0f);

while (acquiring) {
    float newValue = readSensor(); // get "newValue" in some way
    float mean = filter.addValue(newValue);
    // ... do something with the mean ...
}

mAlphaPow keeps shrinking: once it is smaller than the machine epsilon, 1 - αt is exactly 1 in floating point, so I set it to zero and the correction disappears. This also avoids denormal numbers, which are slow on many CPUs. Do not use α = 1: the filter would never move and the division would be by zero.

Fixed-point version for microcontrollers

On an MCU without an FPU (Cortex®-M0/M0+, 8-bit AVR®) floating point is emulated in software and is slow. If we choose α = 1 - 2-k, the multiplication by 1 - α becomes a right shift by k bits, and the time constant is W = 2k samples (k = 4 gives 16 samples, k = 5 gives 32, and so on).

To avoid losing resolution, the trick is to keep an accumulator A that stores the mean multiplied by 2k, so the fractional bits are never truncated away:

Fixed point EWA: alpha equals 1 minus 2 to the minus k, A_t equals 2 to the k times m_t, A_t equals A_(t-1) plus v_t minus A_(t-1) over 2 to the k

/* ewa_fixed.h */
#ifndef EWA_FIXED_H
#define EWA_FIXED_H

#include <stdint.h>

/*
 * Integer-only Exponential Weighted Average for unsigned 16-bit samples
 * (e.g. raw ADC counts).
 *   alpha = 1 - 2^-shift   ->   equivalent window W = 2^shift
 * The accumulator stores the mean scaled by 2^shift, so no resolution is
 * lost to truncation. Valid range: 1 <= shift <= 15 (no 32-bit overflow).
 * The filter is seeded with the first sample, so no bias correction needed.
 */
typedef struct
{
    uint32_t acc;   /* mean << shift */
    uint8_t shift;  /* window = 2^shift samples */
    uint8_t seeded; /* 0 until the first sample arrives */
} ewa_u16_t;

static inline void ewa_u16_init(ewa_u16_t *f, uint8_t shift)
{
    f->acc = 0;
    f->shift = shift;
    f->seeded = 0;
}

static inline uint16_t ewa_u16_update(ewa_u16_t *f, uint16_t val)
{
    const uint32_t half = 1UL << (f->shift - 1);

    if (!f->seeded) {
        f->acc = (uint32_t)val << f->shift;
        f->seeded = 1;
    } else {
        /* acc = acc + val - round(acc / 2^shift)  <=>  m = alpha*m + (1-alpha)*v */
        f->acc = f->acc + val - ((f->acc + half) >> f->shift);
    }
    return (uint16_t)((f->acc + half) >> f->shift); /* rounded mean */
}

#endif /* EWA_FIXED_H */
#include "ewa_fixed.h"

static ewa_u16_t adc_filter;

void setup(void)
{
    ewa_u16_init(&adc_filter, 4); /* alpha = 15/16, window of about 16 samples */
}

void on_adc_sample(uint16_t raw)
{
    uint16_t filtered = ewa_u16_update(&adc_filter, raw);
    /* ... use filtered ... */
}

A few notes on this version:

  • It uses the seeding approach for the start-up, because the bias correction needs a division at every sample, which is exactly what we want to avoid on a small MCU.
  • Rounding (+ half) instead of plain truncation avoids a systematic offset of up to one count in the steady state.
  • With 16-bit samples the 32-bit accumulator does not overflow for k up to 15. With a 12-bit ADC you could go higher, but a window of 32768 samples is rarely useful anyway.
  • For signed samples, use int32_t and be aware that right-shifting a negative value is implementation-defined in C: most compilers do an arithmetic shift, but check yours, or offset the samples to make them unsigned.

How I tested the code

I did not want to publish untested code, so I verified both implementations against a Python/NumPy reference:

  • the synthetic signal above (400 samples) is generated in Python and fed to a small test program compiled with g++ -std=c++11 -Wall -Wextra -Wpedantic -Wconversion (the C++ class, in both double and float, and the fixed-point header), and to a pure C program compiled with gcc -std=c99 with the same warnings (fixed-point header only). Both compile without warnings;
  • the double version matches the NumPy implementation of the bias corrected EWA within 5·10-13, the float version within 0.001 counts;
  • the fixed-point version matches a bit-exact Python model on every sample, and stays within 0.61 counts of the equivalent floating-point EWA;
  • the fixed-point version was also run with k = 1, 8 and 15 on full-scale 16-bit inputs (constant 65535, a 0 to 65535 step, uniform random values) to check that the accumulator never overflows and that a constant input converges exactly to its value;
  • the usage examples above compile as shown (with a stub readSensor()), and the double class was run on 200000 random samples to check the long-term behaviour of the αt term.

Conclusions

The Exponential Weighted Average is one of those small tools that once discovered you use everywhere: one variable, one line of code, and a single parameter that controls the trade-off between noise rejection and delay. Remember the three practical points:

  1. α close to 1 means more smoothing and more delay; 1/(1 - α) gives the time constant, (1 + α)/(1 - α) the moving average with the same noise reduction.
  2. Correct the start-up bias, or at least seed the filter with the first sample.
  3. On MCUs without an FPU, choose α = 1 - 2-k and use a scaled integer accumulator.

If you want to learn more, the second course of the Deep Learning Specialization (“Improving Deep Neural Networks”) covers this topic in three short lectures of week 2: “Exponentially Weighted Averages”, “Understanding Exponentially Weighted Averages” and “Bias Correction in Exponentially Weighted Averages”. The same EWA is at the heart of optimizers like Momentum, RMSprop and Adam (Adam also applies the bias correction).

Tags:

Categories:

Published: · Updated: