Simvik

Exponential moving average

Implement a one-pole low-pass filter with a shift instead of a multiply. A medium embedded C problem (Fixed-point and signal processing), run and graded in…

medium · Fixed-point and signal processing · filters · iir

An exponential moving average needs no sample history: y += (x - y) / 2^shift. To avoid losing the fraction, keep the state scaled up by 2^shift.

*state holds the filter output multiplied by 2^shift. For each sample do *state += sample - (*state >> shift) and return *state >> shift. All samples in the tests are non-negative.

Starter code

int16_t ema_update(int32_t *state, int16_t sample, uint8_t shift) {
  // state is the output scaled by 2^shift.
  return sample;
}

Example tests

Step response

int32_t state = 0;
for (int i = 0; i < 4; i++) printf("%d ", ema_update(&state, 100, 2));
printf("\n");

Expected output:

25 43 58 68

No filtering with a shift of zero

int32_t state = 0;
printf("%d ", ema_update(&state, 77, 0));
printf("%d\n", ema_update(&state, 50, 0));

Expected output:

77 50

Learn it first

More Fixed-point and signal processing problems