Lesson 13 of 15

IIR Filters

IIR Filters

An Infinite Impulse Response (IIR) filter uses feedback — the output depends on both the input and previous outputs. The simplest first-order IIR:

y[n]=bx[n]+ay[n1]y[n] = b \cdot x[n] + a \cdot y[n-1]

with y[1]=0y[-1] = 0 (causal initialization).

Stability

The filter is stable when a<1|a| < 1. If a1a \geq 1, the output diverges.

Exponential Smoother

A common application is the exponential moving average (EMA):

y[n]=αx[n]+(1α)y[n1]y[n] = \alpha \cdot x[n] + (1-\alpha) \cdot y[n-1]

This is iir_filter(x, a=1-alpha, b=alpha). The parameter α(0,1)\alpha \in (0,1) controls smoothing:

  • α\alpha close to 1: fast response, little smoothing
  • α\alpha close to 0: slow response, heavy smoothing

Example

Signal [1,0,0,0][1, 0, 0, 0] through filter with a=0.5a=0.5, b=1b=1:

y[0]=11+0.50=1.0y[0] = 1 \cdot 1 + 0.5 \cdot 0 = 1.0 y[1]=10+0.51=0.5y[1] = 1 \cdot 0 + 0.5 \cdot 1 = 0.5 y[2]=10+0.50.5=0.25y[2] = 1 \cdot 0 + 0.5 \cdot 0.5 = 0.25 y[3]=10+0.50.25=0.125y[3] = 1 \cdot 0 + 0.5 \cdot 0.25 = 0.125

The impulse response decays exponentially — hence "infinite" (theoretically never reaches zero).

Your Task

Implement:

  • iir_filter(x, a, b) — causal first-order IIR: y[n]=bx[n]+ay[n1]y[n] = b \cdot x[n] + a \cdot y[n-1]
  • exponential_smoother(x, alpha) — calls iir_filter(x, 1-alpha, alpha)
def iir_filter(x, a, b):
    y = []
    y_prev = 0.0
    for xi in x:
        yi = b * xi + a * y_prev
        y.append(yi)
        y_prev = yi
    return y

def exponential_smoother(x, alpha):
    return iir_filter(x, 1 - alpha, alpha)
Python runtime loading...
Loading...
Click "Run" to execute your code.