Difference and Differential Equations
The firmware of a temperature logger contains one line: y = 0.9 * y + 0.1 * x. The analog front end it replaced was an RC filter with a time constant. Are the two the same filter? How should the line be changed if the sampling rate doubles? What does the filter output in its first second, before y has "caught up"? These questions connect two descriptions of the same system: a differential equation in continuous time and a difference equation in discrete time. This lesson shows how to run difference equations (lfilter, initial conditions), how to turn an ODE into one, and how the wrong conversion can make a stable system unstable. The solution methods for ODEs are in Differential Equations and Circuit ODEs; the z-domain view follows in the z-transform.
Linear constant-coefficient difference equations
Every LTI system you can build in software (and every one in this course) obeys
which, solved for the newest output, is a recipe: . If all beyond are zero the system is FIR (no feedback, finite impulse response); otherwise it is recursive, usually IIR. In SciPy the two coefficient lists are the arguments of scipy.signal.lfilter(b, a, x).
Total response = zero-input + zero-state. The output splits into the response to the stored initial values with no input (the natural response, made of the system's modes where are the roots of ) and the response to the input from rest (the forced response, the convolution of the input with ). The modes decay if and only if every : that is the stability condition, the discrete twin of "all roots in the left half-plane".
From a differential equation to a difference equation
An RC low-pass obeys . Sampling every seconds, there are several ways to write a difference equation:
| Method | Difference equation | Pole | Notes |
|---|---|---|---|
| forward Euler | simple; unstable for ; poor for lightly damped systems | ||
| exact for a step-wise input (zero-order hold) | samples of the true step response, exactly | ||
| bilinear (trapezoidal) | see The Bilinear Transform | standard for filter design |
The general rule behind the zero-order-hold row: a continuous pole at maps to a discrete pole at . Any left-half-plane pole lands inside the unit circle, so the conversion preserves stability; forward Euler maps to , which does not.
Worked example: the logger's filter
Given: the analog filter has ; the logger samples at ; the firmware uses , i.e. . A step (full-scale sensor jump) arrives at .
Find: the exact discrete pole, the outputs after for the exact and the firmware filter, and the firmware coefficient at .
Solve:
- Exact pole ; the firmware's is the forward-Euler value .
- Exact (zero-order hold): , the analog value at .
- Firmware (Euler pole, same structure): , about faster than the RC; its effective time constant is .
- At : (Euler: ).
Check: as the two poles agree (); the error grows with . The firmware writes rather than , which only shifts its output one sample earlier.
import numpy as np
from scipy.signal import lfilter, lfilter_zi
tau, T = 10e-3, 1e-3
a_zoh, a_eul = np.exp(-T / tau), 1 - T / tau
x = np.full(31, 10.0) # 10 V step at n = 0
y_zoh = lfilter([0, 1 - a_zoh], [1, -a_zoh], x) # y[n] = a y[n-1] + (1 - a) x[n-1]
y_eul = lfilter([0, 1 - a_eul], [1, -a_eul], x)
y_rc = 10 * (1 - np.exp(-np.arange(31) * T / tau)) # samples of the analog step response
print(f"poles: exact {a_zoh:.4f}, Euler {a_eul:.4f}; Euler time constant {-T / np.log(a_eul) * 1e3:.2f} ms")
print(f"n = 10: RC {y_rc[10]:.3f} V, ZOH {y_zoh[10]:.3f} V, Euler {y_eul[10]:.3f} V")
print(f"max |ZOH - RC| over 30 samples = {np.max(np.abs(y_zoh - y_rc)):.1e} V")
# The same recursion as a loop, with a stored initial value (zero-input response)
y, out = 2.0, [] # y[-1] = 2 V left over, no input
for n in range(4):
y = a_zoh * y + (1 - a_zoh) * 0.0
out.append(round(float(y), 4))
print("zero-input response from y[-1] = 2 V:", out)
# Starting a filter on a sensor that already sits at 10 V: steady-state initial conditions
b, a = [0, 1 - a_zoh], [1, -a_zoh]
y_cold = lfilter(b, a, x) # assumes the past input was 0 V
y_warm, _ = lfilter(b, a, x, zi=lfilter_zi(b, a) * x[0])
print(f"first outputs, cold start: {np.round(y_cold[:3], 3)}; warm start: {np.round(y_warm[:3], 3)}")poles: exact 0.9048, Euler 0.9000; Euler time constant 9.49 ms
n = 10: RC 6.321 V, ZOH 6.321 V, Euler 6.513 V
max |ZOH - RC| over 30 samples = 5.3e-15 V
zero-input response from y[-1] = 2 V: [1.8097, 1.6375, 1.4816, 1.3406]
first outputs, cold start: [0. 0.952 1.813]; warm start: [10. 10. 10.]
The cold start is the "catching up" the logger shows in its first : the filter assumes the input was before . lfilter_zi computes the internal state of a filter that has seen a constant input forever, so a filter started on a steady sensor gives the right value at once.
When the conversion makes a stable system unstable
A lightly damped mechanical resonance, and , sampled at . Its continuous poles are safely in the left half-plane. Forward Euler maps them to , outside the unit circle:
import numpy as np
from scipy.signal import cont2discrete
fn, zeta, T = 50.0, 0.1, 1e-3
wn = 2 * np.pi * fn
num, den = [wn**2], [1, 2 * zeta * wn, wn**2]
s_poles = np.roots(den)
bz, az, _ = cont2discrete((num, den), T, method="zoh")
z_zoh = np.roots(az)
z_euler = 1 + s_poles * T
print("s poles:", np.round(s_poles, 2))
print(f"ZOH |z| = {np.abs(z_zoh[0]):.4f} (e^(-zeta wn T) = {np.exp(-zeta * wn * T):.4f}), angle {np.angle(z_zoh[0]):.4f} rad")
print(f"Euler |z| = {np.abs(z_euler[0]):.4f} -> {'unstable' if np.abs(z_euler[0]) > 1 else 'stable'}")
print("difference equation (ZOH): a =", np.round(az, 5), " b =", np.round(np.ravel(bz), 6))s poles: [-31.42+312.58j -31.42-312.58j]
ZOH |z| = 0.9691 (e^(-zeta wn T) = 0.9691), angle 0.3126 rad
Euler |z| = 1.0178 -> unstable
difference equation (ZOH): a = [ 1. -1.84423 0.9391 ] b = [0. 0.047936 0.046939]
The forward-Euler model of a perfectly stable resonance grows by per sample. Use an exact (zoh, impulse) or bilinear conversion, or a sampling rate many times higher than the resonance.
Guided lab: the RC filter and its digital twin
Hand calculation. , : . A step gives at ; the exact digital filter at gives the same at , the Euler filter .
Simulation. At the lab reads (), the value the y_zoh column reproduces sample for sample.
What you would measure. Feed the same to square wave () to an RC on a breadboard and to a microcontroller ADC sampling at that runs y = a*y + (1-a)*x. Log both the ADC reading of the capacitor voltage (a second channel) and the filter output. With the two curves agree within the capacitor tolerance (often to for electrolytics, so measure first); with the digital curve runs ahead, about high at (its time constant is ).
Hazards and safe setup. USB-powered board, generator limited to to and checked on a scope before connecting, in series with each ADC input; observe the polarity of an electrolytic capacitor.
Pitfalls
- Copying to a board with a different sampling rate: the time constant changes with .
- Converting an ODE with forward Euler and getting a filter that oscillates or diverges.
- Forgetting initial conditions: a cold-started filter on a sensor at reads for a while.
- Assuming the coefficients of
ainlfilterare those on the right-hand side: SciPy wants , so feedback terms change sign.
Practice
- Write the difference equation of a filter with
b = [0.2, 0.2],a = [1, -0.6]. Is it stable? What is its DC gain? - An RC has and is sampled at . What is the exact discrete pole?
- For which sampling periods is forward Euler of unstable?
Answer
- ; pole , stable; DC gain .
- , .
- Pole outside : .
Test yourself
A continuous pole at maps under the exact (zero-order-hold) conversion to
For lfilter(b, a, x) with a = [1, -0.9], the recursion is
- an FIR filter
A recursive filter is stable when the roots of its characteristic polynomial satisfy
- real
What does lfilter_zi provide?
- the impulse response
- initial state for a filter that has seen a constant input forever
- zero padding
- the filter's poles