Filter a noisy signal with a 1D Kalman filter

Why it matters Smoothing GPU temperature, queue depth or sensor streams in robotics uses this exact loop.

A Kalman filter tracks a hidden value from noisy measurements by blending prediction and observation.

Write kalman_1d(z, q, r, x0, p0) for a random-walk model. For each measurement z_t: predict x = x, p = p + q; gain K = p / (p + r); update x = x + K (z_t - x), p = (1 - K) p. Return the array of filtered x after each update.

Signaturedef kalman_1d(z, q, r, x0, p0)

Example

kalman_1d([1.0], 0.0, 1.0, 0.0, 1.0) gives K = 0.5 and [0.5].

Understand the idea

A 1D Kalman filter tracks a hidden value from noisy readings. Each step has two moves. Predict: the value may have drifted, so the uncertainty p grows by the process noise q. Update: blend the prediction with the new reading using a gain K, which is large when you are unsure about the prediction and small when you trust it. Worked example: z = [2, 2], q = 1, r = 1, x0 = 0, p0 = 1. Step 1: p = 1 + 1 = 2, K = 2 / 3, x = 0 + (2/3)(2 - 0) = 1.333, p = (1/3) * 2 = 0.667. Step 2: p = 0.667 + 1 = 1.667, K = 1.667 / 2.667 = 0.625, x = 1.333 + 0.625 * 0.667 = 1.75, p = 0.375 * 1.667 = 0.625. Output [1.333, 1.75]. Rule: p = p + q; K = p / (p + r); x = x + K (z_t - x); p = (1 - K) p; record x after each update. Skipping the predict step makes the gain shrink to zero. Used in: sensor fusion, GPS tracking, and smoothing noisy metrics.

Shapes and data flow

state: x (scalar estimate), p (scalar variance)
predict p += q -> gain K -> update x, p
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplekalman_1d([1.0], 0.0, 1.0, 0.0, 1.0)
  • Sample 2: steadykalman_1d([2, 2, 2, 2], 0.01, 1.0, 0.0, 10.0)