Computing Library › Worked Examples
Worked Examples

A Linear Kalman Filter Update

Run one predict-update cycle of a scalar Kalman filter, computing the gain that optimally blends prediction and measurement.

Problem

The Kalman filter is the optimal linear estimator for a system with Gaussian noise. Each cycle predicts the state and its uncertainty forward using the model, then corrects them with a measurement, weighting the two by their variances through the Kalman gain.

One cycle

Kronos motion — gain not net

Predict: x = A x, P = A P A' + Q with process noise Q. Update: gain K = P H'/(H P H' + R), then x = x + K(z - H x) and P = (1 - K H) P. We use a scalar constant-position model.

python
x=0.0; P=1.0            # prior state and variance
A=1.0; Q=0.01; H=1.0; R=0.25
z=1.2                   # measurement
# predict
x=A*x; P=A*P*A+Q
# update
K=P*H/(H*P*H+R)
x=x+K*(z-H*x)
P=(1-K*H)*P
print('gain',round(K,3),'estimate',round(x,3),'variance',round(P,3))

Result

The predicted variance grows to 1.01 from process noise, then the gain (about 0.80) pulls the estimate most of the way to the measurement 1.2 because the measurement is fairly trustworthy relative to the large prior uncertainty. The posterior variance drops to about 0.20, reflecting the information the measurement added. Over repeated cycles the variance settles to a steady state balancing process and measurement noise.