One Step of a Constant-Velocity Kalman Filter
Implement kalman_step(x, P, z, dt, q, r) that runs one predict step and one update step and returns a list:
[[p, v], # [P00, P01], # , row 0 [P10, P11]] # , row 1
x is a length-2 array, P is a array, and z, , q, r are floats. Use NumPy; no filtering libraries.
Why this matters
This loop is the core of radar tracking and of sensor fusion. A perimeter air-defense system runs one of these per track, many times a second, and the covariance it maintains is what decides which new plot belongs to which track. Fusing a second sensor, such as a camera bearing or a second radar, is just another update step with its own H and r: the filter weighs each sensor by how much it trusts it. The same equations sit inside every GPS and IMU fusion loop and every self-driving object tracker.
Examples
The worked example
- Input
- kalman_step([0, 10], [[4, 0], [0, 1]], 12, 1, 0.5, 4)
- Output
- [[11.123288, 10.273973], [2.246575, 0.547945], [0.547945, 1.328767]]
Half-second radar sweep, correlated prior, target closing
- Input
- kalman_step([100, -3], [[2, 0.5], [0.5, 1]], 98.9, 0.5, 1, 1)
- Output
- [[98.793776, -2.887137], [0.73444, 0.282158], [0.282158, 0.950207]]
Huge measurement noise: a wild plot barely moves the estimate
- Input
- kalman_step([50, 5], [[1, 0], [0, 1]], 500, 1, 0.1, 1000000000)
- Output
- [[55.000001, 5], [2.025, 1.05], [1.05, 1.1]]
Hints
Hint 1
Use a matrix product rather than nested loops, and check which operand transposes.
Hint 2
Do not forget to process noise q in predict. That step is easy to skip.
Requirements
x: Prior mean [position, velocity], shape (2,)P: Prior covariance, shape (2, 2)z: Position measurement: Time step in seconds
q: Process noise (acceleration variance)r: Measurement noise varianceReturn [[p, v], [P00, P01], [P10, P11]]: posterior mean and covariance.
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
8 employers weight this skill
4 quant funds, 2 health and bio companies, 1 enterprise vendor, 1 big tech firm. Top match scores 63.
import numpy as np
def kalman_step(x, P, z, dt, q, r) -> list:
"""
One predict + update step of a constant-velocity Kalman filter.
Args:
x: Prior mean [position, velocity], shape (2,)
P: Prior covariance, shape (2, 2)
z: Position measurement
dt: Time step in seconds
q: Process noise (acceleration variance)
r: Measurement noise variance
Returns:
[[p, v], [P00, P01], [P10, P11]]: posterior mean and covariance.
"""
x = np.asarray(x, dtype=float)
P = np.asarray(P, dtype=float)
# Predict: x- = F x, P- = F P F^T + Q
# Update: y = z - H x-, S = H P- H^T + r, K = P- H^T / S
# YOUR CODE HERE
pass