TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › Difference and Differential Equations

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 10 ms10\ \text{ms} 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

∑k=0Nak y[n−k]=∑k=0Mbk x[n−k],a0=1\sum_{k=0}^{N} a_k\,y[n - k] = \sum_{k=0}^{M} b_k\,x[n - k], \qquad a_0 = 1

which, solved for the newest output, is a recipe: y[n]=∑kbkx[n−k]−∑k≥1aky[n−k]y[n] = \sum_k b_k x[n-k] - \sum_{k \ge 1} a_k y[n-k]. If all aka_k beyond a0a_0 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 rinr_i^n where rir_i are the roots of ∑akrN−k=0\sum a_k r^{N-k} = 0) and the response to the input from rest (the forced response, the convolution of the input with h[n]h[n]). The modes decay if and only if every ∣ri∣<1\lvert r_i \rvert < 1: 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 τ y˙(t)+y(t)=x(t)\tau\,\dot{y}(t) + y(t) = x(t). Sampling every TT seconds, there are several ways to write a difference equation:

Method Difference equation Pole Notes
forward Euler y[n]=(1−T/τ) y[n−1]+(T/τ) x[n−1]y[n] = (1 - T/\tau)\,y[n-1] + (T/\tau)\,x[n-1] 1−T/τ1 - T/\tau simple; unstable for T>2τT > 2\tau; poor for lightly damped systems
exact for a step-wise input (zero-order hold) y[n]=a y[n−1]+(1−a) x[n−1]y[n] = a\,y[n-1] + (1 - a)\,x[n-1] a=e−T/τa = e^{-T/\tau} samples of the true step response, exactly
bilinear (trapezoidal) see The Bilinear Transform 1−T/2τ1+T/2τ\frac{1 - T/2\tau}{1 + T/2\tau} standard for filter design

The general rule behind the zero-order-hold row: a continuous pole at s=ps = p maps to a discrete pole at z=epTz = e^{pT}. Any left-half-plane pole lands inside the unit circle, so the conversion preserves stability; forward Euler maps ss to z=1+sTz = 1 + sT, which does not.

Worked example: the logger's filter

Given: the analog filter has τ=10 ms\tau = 10\ \text{ms}; the logger samples at T=1 msT = 1\ \text{ms}; the firmware uses a=0.9a = 0.9, i.e. y[n]=0.9 y[n−1]+0.1 x[n]y[n] = 0.9\,y[n-1] + 0.1\,x[n]. A 10 V10\ \text{V} step (full-scale sensor jump) arrives at n=0n = 0.

Find: the exact discrete pole, the outputs after 10 ms10\ \text{ms} for the exact and the firmware filter, and the firmware coefficient at T=0.5 msT = 0.5\ \text{ms}.

Solve:

  • Exact pole a=e−T/τ=e−0.1=0.9048a = e^{-T/\tau} = e^{-0.1} = 0.9048; the firmware's 0.90.9 is the forward-Euler value 1−T/τ1 - T/\tau.
  • Exact (zero-order hold): y[10]=10 (1−a10)=10 (1−e−1)=6.321 Vy[10] = 10\,(1 - a^{10}) = 10\,(1 - e^{-1}) = 6.321\ \text{V}, the analog value at t=τt = \tau.
  • Firmware (Euler pole, same structure): 10 (1−0.910)=6.513 V10\,(1 - 0.9^{10}) = 6.513\ \text{V}, about 3 %3\,\% faster than the RC; its effective time constant is −T/ln⁡0.9=9.49 ms-T/\ln 0.9 = 9.49\ \text{ms}.
  • At T=0.5 msT = 0.5\ \text{ms}: a=e−0.05=0.9512a = e^{-0.05} = 0.9512 (Euler: 0.950.95).

Check: as T/τ→0T/\tau \to 0 the two poles agree (e−x≈1−xe^{-x} \approx 1 - x); the error grows with T/τT/\tau. The firmware writes 0.1 x[n]0.1\,x[n] rather than 0.1 x[n−1]0.1\,x[n-1], which only shifts its output one sample earlier.

python · try it yourself
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 50 ms50\ \text{ms}: the filter assumes the input was 0 V0\ \text{V} before n=0n = 0. 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, fn=50 Hzf_n = 50\ \text{Hz} and ζ=0.1\zeta = 0.1, sampled at 1 kHz1\ \text{kHz}. Its continuous poles s=−ζωn±jωn1−ζ2s = -\zeta\omega_n \pm j\omega_n\sqrt{1 - \zeta^2} are safely in the left half-plane. Forward Euler maps them to 1+sT1 + sT, outside the unit circle:

python · try it yourself
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 1.8 %1.8\,\% 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. R=1 kΩR = 1\ \text{k}\Omega, C=10 μFC = 10\ \mu\text{F}: τ=10 ms\tau = 10\ \text{ms}. A 10 V10\ \text{V} step gives 6.32 V6.32\ \text{V} at t=τt = \tau; the exact digital filter at T=1 msT = 1\ \text{ms} gives the same at n=10n = 10, the Euler filter 6.51 V6.51\ \text{V}.

Simulation. At t=1τt = 1\tau the lab reads vC=6.32 Vv_C = 6.32\ \text{V} (63.2 %63.2\,\%), the value the y_zoh column reproduces sample for sample.

+-R = 1.00 kOhmswitch closed at t = 0V = 10.0 V, C = 10.0 uFtau = RC = 10.0 mst10.0 mst/tau1.00vC6.32 Vi3.68 mAvR3.68 V0.02.55.07.510.001 tau2 tau3 tau4 tau5 tau6 tautv (V)0 A5.0 mA10 mAi63.2 %5 tau: 99.3 %vC(t), capacitor voltagei(t)

What you would measure. Feed the same 00 to 3 V3\ \text{V} square wave (5 Hz5\ \text{Hz}) to an RC on a breadboard and to a microcontroller ADC sampling at 1 kSa/s1\ \text{kSa/s} 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 a=0.9048a = 0.9048 the two curves agree within the capacitor tolerance (often ±10\pm 10 to 20 %20\,\% for electrolytics, so measure CC first); with a=0.9a = 0.9 the digital curve runs ahead, about 3 %3\,\% high at t=τt = \tau (its time constant is 9.49 ms9.49\ \text{ms}).

Hazards and safe setup. USB-powered board, generator limited to 00 to 3 V3\ \text{V} and checked on a scope before connecting, 1 kΩ1\ \text{k}\Omega in series with each ADC input; observe the polarity of an electrolytic capacitor.

Pitfalls

  • Copying y=0.9y+0.1xy = 0.9y + 0.1x to a board with a different sampling rate: the time constant changes with TT.
  • 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 25 ∘C25\,^\circ\text{C} reads 0 ∘C0\,^\circ\text{C} for a while.
  • Assuming the coefficients of a in lfilter are those on the right-hand side: SciPy wants a0y[n]+a1y[n−1]+…a_0 y[n] + a_1 y[n-1] + \ldots, so feedback terms change sign.

Practice

  1. 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?
  2. An RC has τ=2 ms\tau = 2\ \text{ms} and is sampled at 5 kSa/s5\ \text{kSa/s}. What is the exact discrete pole?
  3. For which sampling periods is forward Euler of τy˙+y=x\tau\dot{y} + y = x unstable?
Answer
  1. y[n]=0.6 y[n−1]+0.2 x[n]+0.2 x[n−1]y[n] = 0.6\,y[n-1] + 0.2\,x[n] + 0.2\,x[n-1]; pole 0.60.6, stable; DC gain (0.2+0.2)/(1−0.6)=1(0.2 + 0.2)/(1 - 0.6) = 1.
  2. T=0.2 msT = 0.2\ \text{ms}, a=e−0.1=0.905a = e^{-0.1} = 0.905.
  3. Pole 1−T/τ1 - T/\tau outside [−1,1][-1, 1]: T>2τT > 2\tau.

Test yourself

A continuous pole at s=ps = p maps under the exact (zero-order-hold) conversion to

  1. z=1+pTz = 1 + pT
  2. z=epTz = e^{pT}
  3. z=pTz = pT
  4. z=1/(1−pT)z = 1/(1 - pT)

For lfilter(b, a, x) with a = [1, -0.9], the recursion is

  1. y[n]=−0.9y[n−1]+…y[n] = -0.9y[n-1] + \ldots
  2. y[n]=0.9y[n−1]+…y[n] = 0.9y[n-1] + \ldots
  3. y[n]=y[n−1]−0.9+…y[n] = y[n-1] - 0.9 + \ldots
  4. an FIR filter

A recursive filter is stable when the roots of its characteristic polynomial satisfy

  1. ∣r∣<1\lvert r \rvert < 1
  2. Re⁡(r)<0\operatorname{Re}(r) < 0
  3. ∣r∣>1\lvert r \rvert > 1
  4. rr real

What does lfilter_zi provide?

  1. the impulse response
  2. initial state for a filter that has seen a constant input forever
  3. zero padding
  4. the filter's poles