I want to walk you through state estimation using two questions I keep coming back to when working on drones. How high are we above the ground, and which way is the aircraft tilted? Imagine the drone banks over a flat landing pad and its rangefinder suddenly reads a little farther. Did we climb, or is the beam just pointing at an angle? Height and tilt are part of the drone’s state. Working out their likely values from imperfect readings is what I mean by state estimation.

Which way is the drone pointing, and how high is it?

Picture the drone hovering three metres above a level landing pad. Find the orange stripe in the drawing. That’s the nose. Left and right are from the drone’s point of view, as if you were sitting inside facing forward.

A level four-rotor drone three metres above a fixed landing pad, with its nose, right side and vertical height marked.
Explore roll, pitch, yaw and altitude. Move one slider, then return to level hover to try another.
  • Roll is a bank about the line from nose to tail. Try +20°. The right side drops and the left side rises.
  • Pitch is a tilt about the line from side to side. Try +15°. The nose rises and the tail drops.
  • Yaw changes where the nose points. Starting level, try +45°. Seen from above, the drone turns clockwise while its rotors stay level.

Together those three angles describe the drone’s attitude, its orientation relative to a reference frame. Altitude is a distance measured vertically from a reference level. Here our zero is the landing pad. Leave the three angles alone and raise altitude from 3 m to 4 m. The whole drone moves up one metre and its attitude stays the same.

Now return to level hover and change just roll. The height of the drone’s centre stays at 3 m. A rangefinder aimed straight out of its belly now looks diagonally across the pad. That’s how two sensors on the same aircraft can tell different parts of the same story.

I’ll start on the bench with one rangefinder and three simple filters. A running mean, a moving average and a low-pass filter each give us a slightly different answer from the same readings. Once the drone starts climbing, we’ll see why: the older samples still describe where it used to be. That’s where the Kalman filter starts to make sense to me. It lets us predict where the drone should be by the next sample, keep track of how uncertain that prediction is, and decide how far to move it when the reading arrives.

From there we’ll look at sensor fusion. A gyro measures how quickly the drone turns, and a quiet accelerometer gives us a clue about tilt. How do we use those clues together to estimate attitude? We’ll start with a complementary filter for the horizon, use the spread of repeated height readings to build a scalar Kalman filter, then follow one curved range measurement through the extended Kalman filter (EKF) and the unscented Kalman filter (UKF). If those names are new to you, compare the two height needles in the simulated cockpit below. By the end, you’ll be able to follow a single reading through the maths and explain why an estimate moved as much as it did.

Two cockpit displays compare raw and filtered bank, pitch and height instruments.
Explore the drone cockpit. Play or scrub the 24-second simulated flight. Select an altimeter to plot height, or a horizon to plot roll. Choose pitch from the plot menu. Both columns use the same sensor record. This replay shows how an estimator changes what a pilot sees; a flight controller would use those estimates to command the motors.

What does each filter remember?

I’d start with sample four. The rangefinder reads 4.60 m. The three estimates land at different heights even though each filter has seen exactly the same four readings. Pick Moving average and change the window from three readings to one. Where does the estimate go? Then switch to the 2-to-5 m step. That’s where the price of a quieter display becomes visible.

The same twelve range readings with running mean, three-sample window and first-order low-pass curves.
Compare the three filters. The window starts with the available samples. The low-pass starts at the first reading. Open the Matplotlib figure.

If you prefer to try it in Python, the runnable plotting example uses these same readings and settings.

What if I keep every range reading?

For the bench example I’ll keep the airframe level above a flat target. The first three simulated readings are 4.2, 2.6 and 3.8 metres. Their mean is 3.53 m. A fourth reading of 4.6 m brings the sum to 15.2 and the mean to 3.80 m. Do I need a buffer of every reading to keep that number up to date?

Two stored numbers are enough here: the count and the previous mean. The fourth reading gets a quarter of the weight, so I can start at the old mean and move a quarter of the way toward 4.6. For reading n the rule is mean ← mean + (reading − mean) / n. On the display I round to two decimals. Inside the filter I keep the extra digits for the next update.

The fourth reading gets one quarter of the weight. On a stationary target, all four samples describe the same height. After 100 readings, the next one contributes only 1/101 of its difference from the old mean.

For independent errors with the same variance R, averaging n samples reduces that variance to R/n. A common 20 cm calibration offset survives. And when the drone leaves the stand, the first hundred readings now describe somewhere it used to be. How much history do we want to keep?

What changes if I keep only three readings?

Use the same four readings. The first full window, [4.2, 2.6, 3.8], still gives 3.53 m. When 4.6 arrives, 4.2 leaves: the new window is [2.6, 3.8, 4.6] and its mean is 3.67 m. The all-history mean was 3.80 m. The difference is entirely in which readings still count. On the sensor board, a three-slot circular buffer supplies the outgoing value: sum ← sum + incoming − outgoing. Once the window is full, divide by three.

Watch the window move. Follow a three-reading average on the rangefinder. Then watch a step from 2 m to 5 m. The average moves through 3 m and 4 m before it catches up. Captions are on throughout.

How quickly should a low-pass follow a climb?

Suppose the target jumps from 2 m to 5 m. The three-sample window returns 3, 4, then 5 m. A first-order low-pass can do the smoothing with one stored output. Each time a reading arrives, move a fraction α of the remaining gap: estimate ← estimate + α × (reading − estimate). With α = 0.25 the estimate goes 2 → 2.75 → 3.3125 → 3.7344 m. It keeps approaching five.

Follow a quarter of the gap. Pause after each sample. The fraction stays at ¼ while the number of metres added gets smaller.
Select either branch. One keeps 1.50 m from the previous estimate, the other contributes 1.25 m from the new reading. The sum, 2.75 m, goes into memory.
Follow the low-pass block diagram. Select either branch. One keeps 1.50 m from the previous estimate, the other contributes 1.25 m from the new reading. The sum, 2.75 m, goes into memory.

Why call it low-pass? A slow height change persists long enough for the estimate to follow. A rapid back-and-forth fluctuation tends to cancel before the estimate moves far. A moving average also smooths this way. Its weights disappear at the edge of the window; the first-order filter gives older samples weights proportional to α, α(1−α), α(1−α)², …. It takes less memory, and it still introduces delay.

The sample clock matters. For a first-order response with time constant τ seconds and readings Δt seconds apart, choose α = 1 − exp(−Δt/τ) for a held input. After one time constant the estimate covers about 63% of a step. For τ = 0.5 s this gives α ≈ 0.181 at 10 Hz and 0.020 at 100 Hz. Reusing the same α at both rates changes how the filter feels in flight.

On a step from two to five metres, the window average reaches five in three new readings. The exponential average approaches five gradually.
A bench test: move a flat target between two known distances beneath the rangefinder. An idealized step makes the delay visible. For the first sample the exponential filter starts at the input; the window uses the readings available so far.
The same four range readings: 4.2, 2.6, 3.8 and 4.6 m
FilterWhat the fourth update usesOutput
Running meanAll four readings with equal weight3.80 m
Three-reading windowOnly 2.6, 3.8 and 4.63.67 m
First-order low-passPrevious output 3.8, plus ¼ of the 0.8 m gap4.00 m

I started the low-pass at the first reading. That starting choice is worth writing down in a log because it can account for a difference between two implementations during the first few samples.

If my display jitters while the drone sits on the pad, this filter gives me a quieter number with one value in memory. During a real climb the same setting makes the display lag. Turning the gain down trades more delay for more smoothing. Where did the change that I smoothed away go?

Keep the part the low-pass leaves behind

Take the 2-to-5 m target step again. At the first new reading the low-pass output is 2.75 m. Subtract it from the actual reading: 5 − 2.75 = 2.25 m. At the next sample the remainder is 1.6875 m. Adding the low-pass output and its remainder gives exactly the original reading at each sample. As the target holds steady at 5 m, the remainder tends to zero.

Where the sudden change goes. Both traces are in metres. A large residual can come from a real change in height or from a noisy sample.
Low-pass output and high-pass remainder for the 2-to-5 metre step
This figure uses --signal step --alpha 0.25. At sample four I get 2.75 m on the low-pass branch and 2.25 m on the high-pass branch. Their sum is the 5 m reading. Open full-size plot.

The remainder is a simple high-pass output. On this bench step I can see it fade as the rangefinder settles. A vibration or a single noisy sample could also leave a spike here. The vertical axis is still in metres. To estimate climb rate I’d need the timing as well as the change in height.

What changes when I plug in a second sensor?

So far each timestamp has given me one number. Suppose I also log pressure and convert it to barometric height. On this flat-pad example I’ve aligned both heights to the same zero and sampled them at the same times. The fourth sample now looks like [4.6, 4.2] metres. One row is a two-entry vector. Stack four rows and I have a 4 × 2 array, or rank-two tensor: time down the rows, sensors across the columns.

The rangefinder column is [4.2, 2.6, 3.8, 4.6]. For the barometric column I’ll use [4.0, 4.2, 4.0, 4.2]. I can run the same three filters down each column. Here’s what I get at the fourth timestamp.

Two sensors in, two smoothed heights out (metres)
FilterRangeBarometric
Mean of all four3.804.10
Mean of the last three3.674.13
First-order low-pass, α = 0.254.004.08
Range and barometric height on the same scale, with three filters applied separately to each sensor.
Each output follows its own sensor history. The columns share a sample clock and a vertical scale. Open the two-sensor Matplotlib figure.

I can smooth six IMU channels in exactly this way. Three gyro channels come out in degrees per second and three accelerometer channels come out in metres per second squared. None of those six numbers is a roll, pitch or yaw angle yet. To put an angle on the horizon display I first need to work out what each instrument can tell me about orientation.

Back at the horizon: blend gyro rate with a gravity reference

Now watch the bank indicator. A gyro measures angular rate. If bank was 9° and the gyro reads 10°/s for 0.1 s, the predicted bank is 10°. That tracks a quick roll well. A small constant gyro bias also integrates on every step, so the displayed horizon can slowly lean while the drone sits still.

Follow the gyro through the time step and the accelerometer through the gravity-tilt calculation. Both arrows entering the correction now carry degrees.
Trace the two branches of the complementary filter. Follow the gyro through the time step and the accelerometer through the gravity-tilt calculation. Both arrows entering the correction now carry degrees.

When translational acceleration is small, the accelerometer gives a second estimate of tilt from the direction of gravity. Suppose it says 12°. In this one-axis illustration a complementary filter takes the gyro prediction plus 2% of the discrepancy: 10° + 0.02 × (12° − 10°) = 10.04°. Fast changes come mainly from the gyro; over longer intervals the gravity reference draws the estimate back. A sustained lateral acceleration can look like tilt to the accelerometer, and gravity alone cannot tell us yaw. Accelerometer inclination sensing and its assumptions.

Two ways to estimate the same bank. Follow the 32-second example with CKE narration and English captions. The gyro supplies a rate in degrees per second; only after multiplying by elapsed time can we combine its predicted angle with a tilt reading in degrees. Open the version with selectable captions.
Simulated bank with noisy accelerometer tilt, biased gyro integration and complementary estimate
I added a fixed 0.45°/s gyro bias to this simulated roll. The gyro-only trace gradually separates from the known bank. The complementary estimate uses a small tilt correction each sample. The script fixes the noise seed so the points stay put between runs. Open full-size plot.

If I wave the sensor board and then hold it still, I’d expect the quick turn to appear first and the slow correction to become visible as the board settles. In an early bench note I saved the sensor traces. The raw readings made more sense to me than the estimate did. Following each branch and checking its units gives me a place to start when that happens.

Can I do the complementary update on roll and pitch together?

For a small turn near level, I can follow two local angles in the order [roll, pitch]. Suppose the previous estimate was [9, −3]° and the gyro reads [10, 5]°/s. After 0.1 s the gyro prediction is [10, −2.5]°. The accelerometer gives a tilt estimate of [12, −1.5]° in the same frame. Now I have two angle vectors I can compare.

The difference is [2, 1]°. Accepting 2% of it moves the prediction by [0.04, 0.02]°, giving [10.04, −2.48]°. It’s the same scalar calculation applied to each coordinate. The integration step is what turns a rate in degrees per second into an angle I can combine with the tilt observation.

Try the two-axis complementary update. At 0% both markers stay on the gyro prediction. At 100% both reach the accelerometer tilt. In between, look at how far each angle moves in degrees.

What happens when the drone rolls and pitches together?

Imagine pitching the nose up after banking the drone onto its side. The gyro axes turned with the airframe. Adding the three body rates separately to roll, pitch and yaw would treat them as if they still lined up with three independent angle changes. For a full turn I’d keep one unit quaternion for the orientation, compose it with the small rotation measured by all three gyro axes during the interval, and use gravity to correct the estimated tilt. I can convert that one orientation to roll, pitch and yaw for the display. Here’s how composing quaternion rotations works.

Turn a level board flat on the desk. The gyro sees the turn, while gravity still points straight down. A quaternion represents that turn just fine. Keeping an absolute yaw estimate from drifting requires another heading reference, such as a calibrated magnetometer in a clean magnetic environment.

After the scalar Kalman example, we’ll read a six-channel IMU log and see how those sensor values enter a state vector and a correction.

When would I change the correction?

In a quiet hover, a 2° gap between gyro prediction and accelerometer tilt might be slow gyro drift. During a sideways acceleration the very same 2° gap can come from the accelerometer sensing the motion. Our fixed 2% correction moves the display by 0.04° in both cases. For modest motion and a steady sample rate, that simplicity can be enough. If the quality of a reading changes, I’d like the correction to reflect what I know about the error. A Kalman filter gives me a way to express that knowledge. It still needs a model or a check that accounts for the acceleration.

How close is a reading to the actual height?

Let’s put the drone back on the bench and use one rangefinder. I can measure the target distance with a tape. Say it is 4.00 m and the rangefinder says 4.20 m. For this reading I know the error: +0.20 m. In flight I don’t have the tape. What I can carry from the bench is a description of the errors I saw over many readings.

Picture a histogram of reading minus tape distance. Its centre tells me about bias. Its width tells me about random scatter. If the errors cluster roughly symmetrically around zero after calibration, a Gaussian bell curve is a useful first model. A standard deviation of 0.10 m makes that 0.20 m error two standard deviations from the centre. With a 1 m standard deviation, the same error is only a fifth of one. A sensor can also give a beautifully tight cluster that sits 0.30 m too high. I’d check the offset separately.

Narrow and broad Gaussian curves show how much spread the same centre can hide.
Start with the centre and width of the bell. Inspect the Gaussian diagram and its terms.

What if I want one height for the display? Now I need to decide how much I trust each sensor. Suppose two simultaneous readings of the same height are 4.0 and 4.5 m, their errors are unbiased and independent, and their variances are 0.04 and 0.16 m². Weighting by inverse variance gives the first reading four times the weight of the second. The fused height is 0.8 × 4.0 + 0.2 × 4.5 = 4.1 m. Here I’m combining sensors at one instant. The table above averages each sensor over time.

That calculation combined two sensors looking at the same height at the same instant. It assumes a common height reference, aligned timestamps and independent errors. In a Kalman update one of those two pieces of evidence will instead come from our prediction. What exactly should we predict, and how wide should its bell be?

What are we estimating, exactly?

A measurement is what an instrument reports. A state is what I need to carry forward to predict the next instant. In hover I might estimate just height. In flight, a drone passing through 4 m on the way up and one passing through 4 m on the way down give the same level range reading. Add vertical velocity and their next heights are different. Throughout the height examples, up is positive, the floor is level and the rangefinder points straight down. Tilting it would change what it measures.

State estimation means inferring those quantities from measurements and a model over time. We choose the state to suit the question. If a range sensor develops a persistent offset, adding a bias to the state helps only if the data can distinguish a wrong height from a wrong sensor zero. A second height reference would help separate those two errors.

What does the Kalman filter carry from one reading to the next?

Let’s give the prediction its own centre and width. The centre, x, is our best estimate of height. The variance, P, describes the spread of the error in that estimate. For this deliberately uncertain start, set x = 0 m and P = 4 m². Taking the square root gives a standard deviation of 2 m. Those two numbers are enough to describe a one-dimensional Gaussian. This simple bell extends below floor level because the model has no lower bound.

There are two separate sources of uncertainty. R is the measurement-noise variance: how much repeat readings scatter around the actual distance. We’ll use 1 m². Q is the variance we add for possible change between samples. Here it is 0.08 m² per interval. Even in hover, height can drift slightly between range updates. If the distance really is constant and that assumption is dependable, Q = 0 is a sensible experiment too.

In flight I can see the gap between the reading and my prediction. I can’t directly see which one was closer to the true height. If their errors are independent, the expected variance of that gap is the predicted variance plus the sensor variance. A wide prediction and a precise sensor call for a bigger move toward the reading. Let’s put the 4.2 m reading through that calculation.

One reading, all the arithmetic

  1. Predict. We expect the distance to stay where it was, so the predicted mean is still 0. Its variance grows to 4 + 0.08 = 4.08 m².
  2. Compare. The sensor reads 4.2. Subtract the predicted reading to get the innovation: 4.2 − 0 = 4.2 m. Its expected variance is 4.08 + 1 = 5.08 m², assuming independent prediction and measurement errors.
  3. Choose the gain. Divide 4.08 by 5.08. The result, 0.803, is the fraction of this discrepancy to accept. The square metres cancel.
  4. Correct. Move from 0 by 0.803 × 4.2 to about 3.37 m. The new variance is (1 − 0.803…) × 4.08 ≈ 0.803 m². Carry that updated mean and variance into the next step.
One reading, two estimates. This 12-second animation includes narration. Both runs start at 0 m and receive the same 4.2 m reading. Watch the circle accept about 80% of the gap (3.37 m). The diamond assumes nine times the sensor variance and accepts only 31% (1.31 m). Each marker shows what the filter believes about the same instant. Open the animated SVG or try your own sensor variance. Watch the 32-second captioned walkthrough.
Two scalar height estimates with different measurement variances
I replayed the twelve readings twice with the same prediction settings. The larger R pulls the estimate less toward the first reading. The gap between traces changes again as more samples arrive. Open full-size plot.

Why that particular fraction?

Imagine choosing the gain yourself. Your new estimate is a blend: (1 − K) times the prediction plus K times the reading. For unbiased, independent errors, the variance of that blend is (1 − K)² P⁻ + K² R. Here the superscript minus means “before the measurement.” Differentiate with respect to K and set the derivative to zero. You get −2(1 − K)P⁻ + 2KR = 0, hence K = P⁻ / (P⁻ + R). The gain is the blend with the smallest expected squared error under those assumptions.

Now the 2.6 m reading arrives. The prediction is already around 3.37 m and the new uncertainty is only about 0.883 m² after adding Q. The innovation points back toward the sensor, and the gain drops to about 0.469. The corrected estimate is about 3.01 m. I kept the sensor noise setting fixed for both readings. The gain changed because the first reading had already reduced the uncertainty in height.

If you write C, you can replay these three readings with our stateEstimation library and compare each result with the arithmetic above.

Read the symbols inside the diagram

When the drone is higher than predicted, is it also climbing faster than predicted? Open Covariance to see the annotated equation. Select Gaussian belief to see how the same uncertainty shapes a bell curve. Each inspector includes a worked example; open a term to follow the arithmetic.

Try the same twelve readings

A position estimate moves through prediction and measurement correction, then feeds the next step.
Explore the Kalman position filter. Step to the first reading and move the measurement variance slider from 1 to 9. The reading stays at 4.2 m. The estimate moves only about 1.31 m from zero because the gain drops to 4.08 / 13.08.

Watch the two plots in the explorer. The time plot shows how the estimate changes from sample to sample. The bell curves show one instant from another angle: the prediction puts weight near its mean, and the likelihood describes which positions could plausibly produce this reading. For the Gaussian model their product, normalized to unit area, is the updated belief. Increasing R broadens the likelihood; the same reading tells us less about the position.

Twelve synthetic range readings scatter around the estimate, whose uncertainty band narrows from the initial two-metre standard deviation.
Reference run at Q = 0.08 and R = 1. The shaded region shows uncertainty in the estimated position. Individual sensor readings can fall outside it because they carry additional measurement noise.

Reproduce it in plain Python

I use the small program below when I want to follow the arithmetic one sample at a time. Its columns are the reading, innovation, gain, corrected height and corrected variance. Raising R while replaying the same samples is an easy way to see the gain change.

kalman_position.py · no external packages
readings = [4.2, 2.6, 3.8, 4.6, 2.9, 3.7, 4.1, 2.7, 3.2, 4.4, 3.3, 3.8]

def estimate(readings, q=0.08, r=1.0):
    x, p = 0.0, 4.0             # metres, then square metres
    for z in readings:
        prior_p = p + q         # position prediction stays at x
        residual = z - x
        gain = prior_p / (prior_p + r)
        x += gain * residual
        p = (1.0 - gain) * prior_p
        yield z, residual, gain, x, p

for z, residual, gain, x, p in estimate(readings):
    print(f"{z:4.1f}  {residual:+6.3f}  {gain:.3f}  {x:.3f}  {p:.3f}")
First three updates · rounded for display
 4.2  +4.200  0.803  3.373  0.803
 2.6  -0.773  0.469  3.011  0.469
 3.8  +0.789  0.354  3.290  0.354

Plot the readings on your own machine

This is the version I’d open beside a flight log. Download the Python script as drone_filters.py. It writes SVGs you can zoom into and a CSV with one row per sample. The default run uses the twelve bench readings, a three-sample window and α = 0.25.

Bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install matplotlib
python drone_filters.py
python drone_filters.py --signal step --window 5 --alpha 0.50 --out step-plots

Open drone-filter-plots/smoothing.svg and find sample four in samples.csv. The second command writes a separate folder, so you can put the two runs side by side. The signal, window and gain switches apply to the introductory plots; the vector, beacon and attitude figures each have their own worked example.

The script also writes two-sensor.svg and two-sensor.csv for the four paired bench readings, and prints the two-axis complementary result. In Python, smooth(z, window=3, alpha=.25) accepts a flat series or a time-by-sensor array.

From one range reading to six IMU channels

We’ve followed a scalar height reading through a Kalman update. Now imagine putting an IMU on a tilting bench. I hold it level for two seconds, roll it right by 12° over one second, then hold it there. I can write down the fixture angle at every instant. That gives me something to compare my estimates with. The readings below are synthetic, sampled every 0.1 s, with noise on all six channels and a deliberately added 0.6°/s roll-gyro bias.

I’m using body axes x forward, y right and z down. Positive roll lowers the right side. An accelerometer reports specific force: a level sensor resting on the bench reads approximately −9.81 m/s² on z in this convention. This fixture rotates about the sensor and has no translational acceleration. The gyro row describes the interval ending at the timestamp. The accelerometer row describes the orientation at that instant.

Five timestamps from a simulated six-axis IMU. Triples are x, y, z in that order.
Time (s)Gyro (°/s)Accel (m/s²)Derived roll
0.01.01, -0.27, -0.660.00, -0.41, -9.692.42°
2.212.26, -0.46, -0.70-0.22, -0.41, -10.002.37°
2.612.66, 0.20, -0.27-0.03, -0.80, -9.944.58°
3.012.43, 0.10, -0.69-0.25, -2.11, -10.0011.89°
4.00.63, 0.64, -0.13-0.20, -1.60, -9.269.80°

Read the 2.6 s row across. The x gyro reports about 12.66°/s. Over a tenth of a second that adds about 1.27° of roll before bias correction. The accelerometer answers a different question. Here I can estimate roll with atan2(−fᵧ, −f𝓏), converted to degrees. Using the unrounded readings gives 4.58°; the fixture is actually at 7.20°. At 4 s the fixture still has a 12° bank even though the gyro rate is close to zero. Holding an angle and turning through an angle leave different signatures in the log.

Where do those numbers go in a Kalman filter?

Start with one rotation axis. My state is x = [roll, gyro bias]. Roll is in degrees and bias is in degrees per second. The x gyro is a measured input to the prediction. The gravity-derived roll is the observation for the correction. The other gyro axes are logged because a real IMU supplies them; this single-axis model only needs the x rate. It also uses just the y and z accelerometer channels for tilt.

The one-axis state-space model for this replay
StepCalculationWhat it means on the bench
Predictroll⁻ = roll + Δt × (gyroₓ − bias)
bias⁻ = bias
Subtract the estimated zero-rate offset before integrating. Allow the bias to wander through process noise.
Observez = tilt from acceleration
predicted z = roll⁻
Both sides of this comparison are now angles. The difference is the innovation.
Correctx = x⁻ + K × (z − roll⁻)The gain has two entries. The same angle discrepancy can change both roll and the gyro-bias estimate.

In matrix form the prediction is x⁻ = F x + B u, with F = [[1, −Δt], [0, 1]], B = [Δt, 0]ᵀ and u = gyroₓ. The observation row is H = [1, 0]. The scalar height example had one state and one variance. Here there are two state entries, a 2 × 2 state covariance P, a 2 × 2 process-noise covariance Q, and one tilt-noise variance R in degrees squared.

Why do angle and bias share a covariance?

For a scalar Gaussian I could draw a bell over possible height errors. With two unknowns, imagine a dot for every plausible pair of roll error and bias error, where error means estimate minus truth. Slicing that bell-shaped surface horizontally gives an ellipse. The diagonal entries of P give its spread along the roll and bias coordinates. The off-diagonal entry says whether the two errors tend to have the same sign or opposite signs.

Try one second on paper. Begin with independent errors: a roll standard deviation of 0.5° and a bias standard deviation of 1°/s. Set extra process noise to zero just for this picture. If I overestimate the gyro bias by 1°/s, I subtract too much from the gyro. My predicted roll ends up 1° too low after that second. The covariance changes from [[0.25, 0], [0, 1]] to [[1.25, −1], [−1, 1]] under F P Fᵀ. The cross term has units of degrees squared per second. Its negative sign explains why a tilt reading above my prediction can pull roll up and the estimated bias down.

Two equal-density contour plots. The original upright contours lean downward after a one-second roll prediction.
Horizontal is roll error. Vertical is gyro-bias error. Each outline joins equally likely error pairs under the Gaussian model. Open full-size plot.

Which filter follows the turn, and which looks quiet in the hold?

I replayed all six seconds through each estimator. The three averaging filters use accelerometer tilt. The complementary filter and Kalman filter also see the gyro. Both start at the first measured tilt. The complementary filter accepts 8% of each tilt discrepancy. The Kalman filter starts with a zero bias estimate and learns it from the sequence. Its noise settings match the simulated bench: gyro noise of 0.4°/s per sample and accelerometer-axis noise of 0.25 m/s², which near level corresponds to about 1.46° of tilt noise. The script includes the process and measurement covariances.

Two aligned roll plots compare the same noisy accelerometer tilt and known fixture angle with three smoothers and two gyro-assisted estimates.
Top: estimates using the accelerometer alone. Bottom: estimates that can also use the gyro. Both panels share the same time and angle scales. Open full-size plot.
Tracking a 12° bank. All rows use the same 61 timestamps.
EstimateAt 3 s (true 12°)Whole-run RMSEFinal hold spread
Raw accelerometer tilt11.89°1.64°1.87°
Running mean1.99°5.69°0.77°
Five-sample mean9.23°1.28°0.79°
Low-pass, α = 0.258.32°1.54°0.70°
Complementary, β = 0.0812.73°1.05°0.25°
Roll + bias Kalman11.60°0.77°0.28°

The last two columns answer different questions. Whole-run root-mean-square error (RMSE) measures distance from the known fixture angle. Final hold spread is the standard deviation around each estimate’s own mean from 4 to 6 seconds. The complementary trace was the quietest in that hold (0.25°). The Kalman estimate tracked the whole turn most closely (0.77° RMSE). The running mean shows why quiet alone is a poor target: when the fixture reached 12°, it still reported 1.99°. Changing the noise, gains or manoeuvre can change this ordering.

You can replay every row with the downloadable plotting script. It writes imu-bench.csv with the six raw channels, fixture angle and all six outputs. Use imu-bench.svg for the comparison and roll-bias-covariance.svg for the one-second covariance example.

Where does the quaternion enter on a real three-axis IMU?

The bench rotates about one fixed axis. For a pure +12° roll, a scalar-first, body-to-world quaternion is [cos 6°, sin 6°, 0, 0], approximately [0.9945, 0.1045, 0, 0]. The four entries describe one orientation. For combined roll, pitch and yaw, the estimator integrates all three bias-corrected body rates into a small rotation and composes it with the current quaternion. Use radians for that rotation step and maintain unit length. See our worked quaternion rotations.

One common attitude EKF keeps a nominal quaternion and three gyro biases. Its local error state has six entries: three small rotation errors in radians and three bias errors in radians per second. Its 6 × 6 covariance describes uncertainty in those six quantities. During a quiet interval, rotate the expected upward specific-force vector into the body frame and compare its direction with the accelerometer. The correction adjusts the orientation and bias. A level turn about gravity leaves that direction unchanged, so absolute yaw requires another heading reference. Sustained sideways acceleration also changes the measured direction; an estimator needs to account for that before using it as a tilt reference. The three-axis extension here explains the representation; the plotted replay executes the two-state roll filter. Quaternion kinematics for the error-state Kalman filter · Accelerometer inclination and its assumptions.

The roll example connected an angle error to a bias error. The next example uses the same idea vertically: a climb-rate error accumulates into a height error. That connection lets a rangefinder update two state entries too.

To see the gyroscope, accelerometer and rangefinder in one estimator, follow the observation equations or open the flight bench.

How can a height sensor update climb rate?

For height alone, one number P described the spread. Now imagine drawing the prediction errors for height and climb rate as pairs. If the trials that underestimate height also tend to underestimate climb rate, those errors vary together. Their covariance is positive. The two diagonal entries of a 2 × 2 covariance matrix give the separate variances. The off-diagonal entries record that shared variation, in m²/s for this pair. It’s the reason a new height reading can also change the estimated climb rate.

Picture a level drone climbing above a flat landing pad. Use height relative to the starting hover point for position. Now a state has two entries: position in metres and velocity in metres per second. Between readings, predict position with p_next = p + Δt × v and carry velocity forward. In matrix form the transition is F = [[1, Δt], [0, 1]]. The sensor sees only position, so its observation matrix is H = [1, 0].

Here’s a one-second example you can do by hand. Start at 0 m with velocity 1 m/s. Give position and velocity independent uncertainties of one standard unit each, so P starts with ones on the diagonal and zeros elsewhere. For this single step use Q = 0 to isolate the effect of motion. The predicted position is 1 m. The predicted covariance F P Fᵀ becomes [[2, 1], [1, 1]]. The off-diagonal 1 appears because a velocity error now also contributes to position error.

The sensor reports 2.5 m, with R = 1 m². The innovation is 1.5 m. Its variance is 2 + 1 = 3 m². The gain is now a column: take the first column of the predicted covariance and divide by 3. The two gains are 2/3 and 1/3 per second. Position moves by (2/3) × 1.5 = 1 m, to 2 m. Velocity moves by (1/3) × 1.5 = 0.5 m/s, to 1.5 m/s. The sensor never reported a speed. The motion model created a relationship between the two errors, and the filter used it.

To see which entry in memory connects those two estimates, run the same one-second update in C. It prints the cross-covariance just before the correction.

Read the vector update one row at a time

The range reading is still a scalar: one number in metres. The state is a vector: two numbers with different units. On paper write it as a 2 × 1 column; in NumPy a flat array of shape (2,) can hold the same entries. A matrix records how each entry relates to each other entry. Here the 2 × 2 covariance has height variance in m², speed variance in (m/s)², and shared error in m²/s. The word tensor covers all these shapes. The units and what the entries describe are the part to keep track of.

Read H = [1, 0] as “the rangefinder sees height.” Read the gain column as two instructions for the same residual: height += (2/3) × 1.5 m and speed += (1/3 s⁻¹) × 1.5 m. If the predicted height and speed errors had zero covariance, that second gain would be zero. That cross term is where the range reading gets its influence on climb rate.

One reading can change two estimates. The units tell the story: one residual in metres produces both a height correction in metres and a speed correction in metres per second.
Predicted and corrected height and climb rate on separate axes
Here’s the same correction in two sets of units. The height estimate rises by 1 m. The speed estimate rises by 0.5 m/s. Each has its own vertical axis. Open full-size plot.

What the matrix operations do

  • P⁻ = F P Fᵀ + Q carries yesterday’s uncertainty through today’s motion and adds the uncertainty of that motion.
  • r = z − Hx⁻ compares the reading with what the sensor would see at the predicted state. S = H P⁻ Hᵀ + R puts a scale on that discrepancy.
  • K S = P⁻ Hᵀ gives the gain. With one measurement, S is a scalar. With several, a numerical implementation can solve a linear system. Then x⁺ = x⁻ + Kr.
  • With A = I − KH, the Joseph update P⁺ = A P⁻ Aᵀ + K R Kᵀ carries the uncertainty from prediction and measurement through the correction. This form is useful when rounding error matters.
Tilted position and velocity covariance ellipses before and after one position reading. Both coordinates of the estimated centre move.
Dots are the estimated states. Ellipses trace one unit of Mahalanobis distance around each mean. Their tilt shows correlated errors; their widths and heights use different physical units. Open full size.

Open up one covariance multiplication

In the vertical climb example the next position error is δp + Δt δv. Square that expression and take its expected value. The position variance becomes Ppp + 2 Δt Ppv + Δt² Pvv, before adding process noise. Starting with independent unit variances and Δt = 1 gives 1 + 0 + 1 = 2 m². The new position–velocity covariance is Ppv + Δt Pvv, or 1 m²/s. Those two numbers are the first row of F P Fᵀ. Matrix multiplication keeps track of the same products you would have written by hand.

Open the covariance matrix. After a one-second prediction, the off-diagonal entries connect the height error to the speed error. A height sensor selects the first column.

Now follow the dimensions. For two state variables and a single range reading, F, P and Q are 2 × 2; H is 1 × 2. Multiplying H P⁻ Hᵀ picks out the predicted variance in the one direction the sensor observes. Add R and you have a single number, S. Multiplying P⁻ Hᵀ instead keeps two entries: how position moves with the reading and how velocity moves with it. Divide each by S and you have the two correction gains. That is why one sensor reading can change two state entries by different amounts.

What happens during one second without range?

I’m curious what the height trace does when the rangefinder misses a few returns. In this simulated replay the drone hovers at 2 m, accelerates into a 1 m/s climb, then settles into a new hover. From 4 to 5 seconds the range data stops. The last five readings in the buffer stay the same while the simulated aircraft keeps climbing.

During the range dropout the window holds its last average while the Kalman estimate continues along the climb.
Synthetic flight with a fixed random seed, sampled at 10 Hz. The dark dashed line is available to us for scoring; neither estimator sees it. Open full size.

The window holds its last average until range returns. The Kalman filter predicts height and climb rate every 0.1 s using a second noisy input: vertical acceleration. Between samples it adds v Δt + ½a Δt² to height and a Δt to climb rate. When a fresh range reading arrives, the innovation corrects both. The whole-flight root-mean-square height error on this replay is 0.341 m for the five-reading window and 0.089 m for the Kalman estimate.

I gave the Kalman filter a second input here, so the two curves answer slightly different questions. Its acceleration samples are noisy, but they have already been rotated into the vertical frame and gravity has been removed. In a real flight log I’d check both steps before using that channel. To explore the drift, I’d first extend the outage, then repeat the replay with a small constant acceleration bias.

Reproduce the noisy flight and both errors in PythonPython
import numpy as np

rng = np.random.default_rng(61)
dt = 0.1
t = np.arange(101) * dt
# Hover, accelerate up for 1 s, climb, then brake for 1 s.
a = ((t >= 2) & (t < 3)).astype(float) - ((t >= 6) & (t < 7))
height, speed = np.zeros(len(t)), 0.0
height[0] = 2.0
for k in range(1, len(t)):
    height[k] = height[k-1] + dt*speed + 0.5*dt**2*a[k-1]
    speed += dt*a[k-1]

# Synthetic vertical acceleration after attitude and gravity compensation.
accel = a + rng.normal(0, 0.25, len(t))
z = height + rng.normal(0, 0.35, len(t))
z[(t >= 4) & (t < 5)] = np.nan
F = np.array([[1., dt], [0., 1.]])
g = np.array([0.5*dt**2, dt])
Q = np.outer(g, g) * 0.25**2
R = 0.35**2
x = np.array([z[0], 0.])
P = np.diag([R, 1.])
filtered, averaged, window = [x[0]], [z[0]], [z[0]]
for k in range(1, len(t)):
    x = F @ x + g*accel[k-1]
    P = F @ P @ F.T + Q
    if np.isfinite(z[k]):
        window = (window + [z[k]])[-5:]
        gain = P[:, 0] / (P[0, 0] + R)
        x += gain * (z[k] - x[0])
        P -= np.outer(gain, P[0].copy())
    filtered.append(x[0])
    averaged.append(np.mean(window))

for label, estimate in [('Window', averaged), ('Kalman', filtered)]:
    print(label, 'height RMSE (m):', round(np.sqrt(np.mean((estimate-height)**2)), 3))

How would I build the system model in the first place?

I’d start with a question I can check on the bench: if the fixture is 3 m above the pad and climbing at 2 m/s, what should a rangefinder see half a second from now? Height alone leaves two possibilities open. A fixture passing 3 m on the way down has a different future. That’s a reason to put velocity into the state. I also need to write down the reference: for this vertical example the floor is zero, and up is positive.

Five model-building steps and an annotated state derivative equation.
Walk through the state-space model. Use Next to follow the model from its state to a reading. Select a symbol for its meaning. At “Predict a reading,” switch the instrument and watch the units change.

Write one rate equation per state. Choose x = [h, v]ᵀ. The rate of height is velocity. The rate of velocity is net vertical acceleration. If I know that acceleration over the next interval, I can call it the input u. Putting those two sentences into rows gives ẋ = Ax + Bu. The dot means a rate per second. If the known input is thrust in newtons instead, I need a force model and mass before I can predict acceleration. The hover example below makes that choice.

Predict to the instrument’s timestamp. With constant net acceleration of −1 m/s² over half a second, the new height is 3 + 2 × 0.5 − ½ × 0.5² = 3.875 m. The new velocity is 1.5 m/s. This is what the discrete transition matrix F and input matrix Bᵈ compute together. Process covariance Q describes how uncertain we are about that step. A longer interval can change the transition, the input contribution and its uncertainty.

Ask what the sensor observes. On a level fixture, a vertical range channel selects height with H = [1, 0]. A vertical-speed channel selects velocity with H = [0, 1]. We can swap instruments and keep the same motion equations. There is a catch: a log of speed alone can tell me how far I moved, but it cannot tell me the starting height. Change the mount angle and even the range observation changes. The mounting experiment makes that geometry visible.

Expand the state when the question calls for it. Attitude and altitude can be enough to draw a horizon and an altimeter. To follow translation as well, carry world-frame position and velocity and keep the orientation that connects the body and world frames. Rotate calibrated body specific force into the world frame, add world gravity, then integrate velocity and position. At rest on the pad the acceleration should come out near zero. That one check can reveal a gravity sign or frame error before I spend an afternoon tuning the filter. For the linear hover model, the Laplace diagram follows the same vertical dynamics from input to output.

What does a point in state space mean?

Take a 1 kg drone near level hover. Gravity is already balanced by hover thrust. Let u be the extra upward thrust in newtons and model vertical drag as 0.6 times climb rate. For a short vertical manoeuvre, h″ = u − 0.6 h′ in these units. Choose the state x = [h, v]ᵀ, with height measured relative to hover and velocity positive upward. One dot in state space is a height and a climb rate at the same instant.

Read ẋ = Ax + Bu one row at a time. For this model A = [[0, 1], [0, −0.6]] and B = [[0], [1]]. Row one says velocity changes height. Row two says extra thrust changes velocity while drag opposes it. A level downward range sensor over flat ground sees height; subtract the initial hover reading to get the relative output y = Cx with C = [1, 0].

Height versus time and the same manoeuvre in height–climb-rate coordinates.
One simulated vertical manoeuvre. Apply 1 N above hover for a second, then 1 N below hover for a second, then return to hover thrust. The state plot shows when the drone is still rising after the input changes. Open full size.
Explore the drone state-space model
Explore the drone state-space model. Select Height and rates, State derivative, Advance state or Sensor output. Open each symbol to see the scalar calculation and matrix dimensions.

Where does the Laplace transform fit?

For zero initial height deviation and zero climb rate, take the Laplace transform of the same equations. The extra-thrust-to-height transfer function is G(s) = 1 / [s(s + 0.6)]. The factor 1/s comes from integrating velocity to obtain height. When thrust returns to its hover value, the model can settle at a different altitude. The transfer function and state-space simulations agree at all 401 plotted time samples.

These are two descriptions of the same plant. The transfer function is handy for asking what an input does to an output at different frequencies. State space also lets me initialize the drone two metres above its hover reference, give it a velocity, and attach uncertainty to either quantity. To recover the zero-initial-state transfer map from a continuous linear model, use G(s) = C(sI − A)⁻¹B + D. For several inputs and outputs, G is a matrix of transfer functions.

Explore the Laplace transform
Explore the Laplace transform. Select the derivative rule to see where the initial height enters. Then follow the two transfer factors from thrust to height.

How many inputs and outputs does the drone model have?

The vertical example has one input (extra thrust) and one output (height). That makes it SISO despite having two states. Now group the rotors on the left and right of a quadrotor. In a small-angle model, increasing thrust on either side adds lift; the two sides produce opposite roll torques. Choose two outputs, height change and roll angle. Two inputs and two outputs make this MIMO.

Left and right thrust produce equal height responses and roll responses with opposite signs.
Two separate simulated tests starting at level hover. Step one side by 0.04 N for one second. Read down each column to see the two outputs of the same input. Open full size.

In the vertical acceleration row of B, the two thrust increments add. In the roll acceleration row their difference is multiplied by arm length divided by roll inertia. Add equal thrust on both sides and roll cancels in this model. The height and roll outputs stand for ideal observations in this short simulation; in flight, attitude itself typically comes from an estimate using inertial measurements.

Python
import numpy as np
from scipy import signal

# State: height deviation, climb rate, roll angle, roll rate.
# Inputs: left and right thrust increments (N). Positive roll = right thrust up.
mass, arm, inertia = 1.0, 0.15, 0.025
A = [[0, 1, 0, 0], [0, -0.6, 0, 0],
     [0, 0, 0, 1], [0, 0, 0, -1.2]]
B = [[0, 0], [1/mass, 1/mass],
     [0, 0], [-arm/inertia, arm/inertia]]
C = [[1, 0, 0, 0], [0, 0, 1, 0]]
plant = signal.StateSpace(A, B, C, np.zeros((2, 2)))
t = np.linspace(0, 1, 101)
for side in (0, 1):
    thrust = np.zeros((len(t), 2))
    thrust[:, side] = 0.04
    _, y, _ = signal.lsim(plant, thrust, t)
    print(side, y[-1, 0], np.degrees(y[-1, 1]))

From simulated states to estimated states

SciPy can show all four internal states because it integrates the equations. In a flight log we instead have time-stamped observations and uncertain inputs. Sample the continuous model at interval Δt to get xₖ = F xₖ₋₁ + B_d uₖ₋₁ + wₖ. For thrust held constant across an interval, scipy.signal.cont2discrete((A,B,C,D), dt, method="zoh") computes F and B_d. Choose Q separately to describe disturbances and input errors. Here D is zero and H selects height and roll.

The innovation now has two components: a height discrepancy in metres and a roll discrepancy in radians. Each column of the 4 × 2 gain tells us how to use one discrepancy. In this symmetric, linearized model with independent sensor and state errors, the height measurement corrects height and climb rate; the roll measurement corrects roll angle and roll rate. Which corrections carry across the states depends on the correlations in this model.

Can we recover the two hidden rates? C selects height and angle. CA selects their rates. The four rows of C and CA together span all four state coordinates in this ideal model. In an actual log, sparse updates and noisy angles still limit how well we can estimate the rates. Observability answers whether the rates can, in principle, be inferred. I’d use the timestamps and noise in the actual log to judge the accuracy.

One flight, four sensors. What changes in the estimate?

Imagine a drone above a level landing pad. It rolls ten degrees. Its downward rangefinder now reads 2.00 m. Did the drone climb, or did the beam just get longer? Start with one number, then add only the coordinates we need to answer that question.

Read the sensors in the order they arrive

  1. Accelerometer · establish up. On the pad, with its axes aligned to an up-positive world frame, the accelerometer reads about [0, 0, 9.81] m/s². Those three numbers form one vector. Their direction gives us an initial tilt. Spin the drone flat on the table and the vector stays the same: gravity gives us no compass heading. Once the drone accelerates, motion also contributes to that reading.
  2. Gyroscope · carry the attitude forward. Starting level, suppose the bias-corrected roll rate is 20°/s for half a second. The estimated roll is now 10°. For a pure roll the scalar-first quaternion is [cos 5°, sin 5°, 0, 0]. For a general turn we compose rotations at the gyro timestamps. A small gyro bias accumulates over time. A quiet accelerometer sample can correct tilt again; absolute yaw still needs a heading reference. Why the quaternion uses half the turn angle.
  3. Time of flight · connect attitude to height. The rangefinder measures 2.00 m along its beam. At 10° from vertical that gives 2.00 cos(10°) ≈ 1.97 m above the pad. The missing three centimetres are geometry. This assumes a flat, level surface, a valid return and a known beam direction. With uncertain tilt, a joint filter can predict the slant reading from both height and orientation.
  4. Barometer · measure a climb from the pad. Record the pressure before lifting the fixture. As it rises through still air, the pressure falls. That difference gives a height change relative to the starting point. Slide the ambient pressure down while keeping the height fixed to see how weather can look like a climb.
  5. Humidity · decide what belongs in the state. Next comes 55% relative humidity. What height or roll would predict that reading? Our flight model has no such relationship. We timestamp it alongside the flight. A separate environmental estimate could smooth humidity over time without pulling the aircraft up or tilting it.
A quiet accelerometer reading initializes roll. The gyro advances that angle. Range and pressure provide height observations. Humidity is logged separately.
Explore the five sensor readings. Select Accelerometer or Gyroscope to try the same roll with both instruments. Select Time of flight, Barometer or Humidity to try that sensor on its own.

What travels along the arrow from accelerometer to gyro? An initial angle. Think of holding the board level, then slowly rolling it 10° in five seconds about its X axis. The gyro measures angular velocity. If it reads a steady 2°/s, its accumulated angle is 0° + 2°/s × 5 s = 10°. Meanwhile, the direction of the accelerometer’s specific-force vector changes as the board tilts. With negligible translational acceleration, its Y and Z channels give a roll angle through atan2(fᵧ, f𝓏). Start at 0°, finish at 10°, and the average rate inferred from those angles is (10° − 0°) / 5 s = 2°/s. That shared motion explains why the two readings agree once we put them in the same units.

Try holding the board at 30°. Set starting roll to 30° and true roll rate to zero. The accelerometer still sees tilt while the ideal gyro reads zero. Add a 0.5°/s gyro bias and wait ten simulated seconds: the integrated estimate says 35°. Now try a sideways acceleration and watch the gravity-based tilt move instead. Differencing the raw accelerometer channels gives change in specific force in m/s³. It’s the derived tilt angle we difference to estimate a roll rate, and even a little noise gets amplified over short intervals. This example uses a single roll axis; general three-axis body rates need the current attitude to relate them to roll, pitch and yaw rates. Accelerometer inclination sensing · Analog Devices.

One number comes in. How can two estimates move?

Scalar. Suppose we predicted 1.90 m. The tilt-corrected observation is 1.97 m. Subtract the prediction and we get a residual of +0.07 m. A height-only filter with gain 0.5 moves up by 0.035 m, to 1.935 m.

Vector (a 1D array). Keep two values now: [height, climb rate]. Start at [1.90 m, 0.10 m/s]. The sensor still gives us just one height. In NumPy the state can have shape (2,); on paper we write it as a two-entry column.

Matrix (a 2D array). Suppose the predicted covariance is P = [[0.04, 0.016], [0.016, 0.09]], in the corresponding height and climb units, and the height observation variance is 0.04 m². The observation row H = [1, 0] picks out height. The residual variance is 0.04 + 0.04 = 0.08 m². Divide the first column of P by 0.08 and the gain is [0.5, 0.2/s]. Multiply each entry by the same +0.07 m. The updated state is [1.935 m, 0.114 m/s]. If the cross term were zero, this reading would leave climb rate alone.

To carry attitude too, one possible design stores a unit quaternion, height and climb rate. Its uncertainty can use three small rotation errors plus height and climb errors: five error coordinates and a 5 × 5 covariance. A single range return then has a 1 × 5 local measurement row. Each column asks how much the predicted range would change if that coordinate changed a little. Process each sensor at its own timestamp. If the rangefinder misses a return, carry the prediction forward until another usable measurement arrives. This is a worked design example. The following sections explain the nonlinear update; the repository guide below identifies the implemented pieces. Quaternion attitude prediction and measurement updates.

Extended Kalman filter: when the sensor sees a curve

Now the drone flies horizontally at a known height of 3 m above a radio beacon on the ground. Keep the flight on one horizontal line through the beacon and let x be the signed horizontal displacement. A radio range measurement follows h(x) = √(x² + 3²). At x = 4 m it reads 5 m; directly overhead it reads 3 m. A metre of horizontal travel produces different changes in measured range depending on where the drone starts. A constant H no longer describes the observation.

Suppose the predicted horizontal position is 4 m with variance 4 m². The sensor reports 6 m, with R = 0.25 m². The EKF evaluates the actual sensor function to predict the reading, then uses its local slope to translate uncertainty: H = dh/dx = x / √(x² + 9) = 0.8. The innovation is 6 − 5 = 1 m. Its variance is 0.8² × 4 + 0.25 = 2.81. The gain is 4 × 0.8 / 2.81 ≈ 1.139. The corrected position is 5.139 m, with variance about 0.356 m². A gain above one makes sense here: near this point a metre of horizontal motion produces only 0.8 m of range change.

A curved range measurement and its tangent agree at four metres, but separate on either side. Three points on the curve show the inputs used for the UKF calculation.
Both methods start from the same horizontal position and variance. The EKF uses the slope at the centre. The UKF evaluates the sensor model at the three marked positions.

For a nonlinear motion model the same idea applies on prediction. Advance the mean with f(x); propagate covariance with F P Fᵀ + Q, evaluating the Jacobian F at the previous estimate. For the measurement, evaluate h and its Jacobian H at the predicted state. Each Jacobian entry is a local slope: change one input a little and ask how much one output changes. Analytic derivatives can be checked against small finite differences. This treatment assumes additive noise.

Unscented Kalman filter: send a few positions through the curve

What if the model is easy to evaluate but awkward to differentiate? Keep the same prior, sensor and reading. This time choose positions whose weighted spread reproduces the prior variance. These are sigma points. They are deterministic, so anyone repeating this calculation gets the same points.

When the sensor draws a curve. Amber is the EKF tangent at the predicted position. The three teal positions are the UKF sigma points evaluated through the range equation.
Beacon range curve, tangent at four metres and three sigma points
I can draw the beacon geometry with one call to hypot. The teal points sit on the curve. The dashed tangent follows it closely near 4 m and separates from it farther away. Open full-size plot.
  1. Place the points. For this one-dimensional scaled unscented transform choose α = 1, κ = 0 and β = 2. The centre is 4 and one standard deviation is 2, giving the points 4, 2 and 6 m. Their mean weights are 0, ½, ½. Their covariance weights are 2, ½, ½. The centre still contributes to the transformed covariance even though its mean weight is zero.
  2. Predict what the sensor sees. Evaluate h at all three points: 5.000, 3.606 and 6.708 m. The weighted mean is 5.157 m. The EKF predicted 5.000 m. Both used the same geometry; taking a mean before applying a curved function can give a different answer from taking it afterward.
  3. Recover the gain. Sum the weighted squared range deviations from 5.157 and add R to get S ≈ 2.706 m². Sum the weighted products of horizontal and range deviations to get their cross-covariance C ≈ 3.103 m². The gain C/S is 1.147.
  4. Correct. The innovation is now 6 − 5.157 ≈ 0.843 m. The updated horizontal position is 4.967 m and its variance is P − K S Kᵀ ≈ 0.442 m². A slightly different gain and a different predicted reading produce a different final estimate.

In n dimensions, the common scaled construction uses a centre and two points along each column of a scaled matrix square root of P, giving 2n + 1 points. The columns encode correlations as well as spread. In an additive-noise UKF, propagate these points through f, recombine their mean and covariance, and add Q. To update, form points for the predicted mean and covariance (including Q), run them through h, accumulate S and the cross-covariance, and add R to S. The correction then has the same recognizable form. Implementations need a numerically sound covariance factorization and weights appropriate for the model. Julier and Uhlmann, Unscented Filtering and Nonlinear Estimation.

Try both corrections with the same measurement

One nonlinear measurement update · Python
from math import hypot, sqrt

x, p, z, r = 4.0, 4.0, 6.0, 0.25
def sensor(x):
    return hypot(x, 3.0)

# EKF: use the slope at the predicted state.
h = x / sensor(x)
s = h*h*p + r
k = p*h / s
print("EKF", round(x + k*(z - sensor(x)), 3), round(p - k*k*s, 3))

# UKF: one-dimensional points and weights for alpha=1, kappa=0, beta=2.
points = [x, x - sqrt(p), x + sqrt(p)]
wm, wc = [0, 0.5, 0.5], [2, 0.5, 0.5]
ranges = [sensor(v) for v in points]
mean = sum(w*y for w, y in zip(wm, ranges))
s = r + sum(w*(y-mean)**2 for w, y in zip(wc, ranges))
cross = sum(w*(v-x)*(y-mean) for w, v, y in zip(wc, points, ranges))
k = cross / s
print("UKF", round(x + k*(z - mean), 3), round(p - k*k*s, 3))

The two estimates differ by about 17 cm. Which one is closer? I’d need an independent position measurement to tell. There’s another wrinkle I like about this example. A single beacon gives exactly the same range at x and −x. If either side is plausible, the position distribution can have two peaks. At zero the EKF slope vanishes, and for a symmetric prior there the UKF’s cross-covariance cancels too. A second beacon in a different location could tell those positions apart.

Which filter would I start with?

  • Moving average: a steady signal, a tolerable window delay, and a need for a transparent baseline. Use the exponential version when you want one stored estimate and a fixed gain.
  • Linear KF: the state transition and measurement are well represented by linear maps, and you need a state estimate with uncertainty. Under linear Gaussian assumptions it gives the conditional mean and covariance exactly.
  • EKF: the geometry is nonlinear but smooth over the plausible state range. A checked Jacobian can make each step economical.
  • UKF: curvature across the uncertainty region matters, evaluating the model several times is affordable, and a single mean and covariance still describe the belief reasonably well. Compare it with the EKF on the same timestamped replay.

Where does each sensor go in the filter?

Suppose a level drone hovers 3 m above a flat pad. Now bank it 30° without climbing. A downward body-mounted time-of-flight rangefinder should report about 3.46 m: the beam travels diagonally. If I put that number directly into an altitude slot, my software will invent a 46 cm climb. Turning up the range variance can hide some of the mistake. Writing down what the sensor actually measures fixes the geometry.

For the flight bench below, the state is x = [roll φ, pitch θ, yaw ψ, height h]. The angles use radians inside the filter, height uses metres above the pad, and the body axes point forward, right and down. Here’s how I’d wire three sensors to that particular state.

One sensor record, three ways into the equations
InstrumentQuantity, frame and timingWhere it enters
GyroscopeThree body angular rates in rad/s over the last 0.1 s.Input u to the prediction x⁻ = f(x,u). Convert body rates to angle rates, then integrate over Δt. Rate noise passes through that same map into process covariance Q.
AccelerometerThree body specific-force components in m/s² at the end of the interval.Under the gravity assumption, derive roll and pitch from the direction of the force. Their observation rows select φ and θ. Here R describes tilt error in rad². A sideways disturbance biases the direction. Yaw is absent from both rows.
ToF rangefinderOne distance in metres along the downward body beam, observed at the same timestamp.Over a flat pad the predicted range is s(x) = h / (cos φ cos θ). Subtract it from the observed range. Its measurement variance is in m². A real rangefinder also needs a valid return within its operating range.

There’s a quick check for a new sensor: given the current state, could I predict what that instrument would read, in its own units and frame, at its timestamp? If so I can form an innovation. If it describes motion between timestamps, it may belong in the prediction instead. In a larger navigation filter I could use specific force to predict velocity after rotating it to the world frame and accounting for gravity. Reusing the very same sample as independent tilt evidence would double-count information unless I also modelled the correlation.

One range beam through KF, EKF and UKF

  • Linear KF. Near level the bench approximates the body rates as angle rates and the range as height. The range row is H = [0, 0, 0, 1]. A 3.46 m observation against a 3 m prediction gives a +0.46 m innovation. This is a useful baseline for seeing where the approximation breaks during a bank.
  • EKF. Predict the actual slant distance, then take the local slopes. If s = h / (cos φ cos θ), its Jacobian is H = [s tan φ, s tan θ, 0, 1/(cos φ cos θ)]. At 30° roll, zero pitch and 3 m height, this is approximately [2.00, 0, 0, 1.155]. A small roll error changes the predicted range by about 2 m per radian. A 1 cm height error changes it by about 1.15 cm. The filter uses these slopes in S = H P⁻ Hᵀ + R; the innovation itself uses the curved range function. The prediction likewise uses the Jacobian of the motion model to transport the covariance.
  • UKF. From the same four-state mean and covariance, choose nine sigma points. Apply the motion model to each point. At the range update, pass the new points through the beam geometry. Their weighted predicted ranges give the expected measurement. The cross-covariance between the state points and their ranges gives the gain after division by the innovation variance. This samples the curvature without computing a range Jacobian. The tilt observations are linear in our chosen angle coordinates, so their ordinary linear update already gives the same moments.

The Jacobian here answers the same question as in backpropagation: if I change one input slightly, how much does each output move? In backprop we send a loss gradient through that map. Here we use it to move uncertainty into sensor coordinates. The Jacobian and backprop through a matrix multiplication · Backpropagation from Wx + b.

Try the sensor fusion flight bench

Start at 7 seconds. The drone is banking over the pad, and I’ve added a sideways disturbance to the accelerometer from 6 to 8 s. The left cockpit shows the known simulated flight. The right cockpit and the drone drawing show the estimate. Switch estimators or change a sensor setting and the bench replays the same readings up to the same instant.

At seven seconds the fixture banks 22 degrees. The estimated drone and cockpit show about 28 degrees during the accelerometer disturbance.
Open the sensor fusion flight bench. Play, pause or scrub the flight. Expand the sensor panel to compare the raw measurements with the current state covariance.
  1. Give the disturbed tilt too much weight. Keep EKF selected. Reduce accelerometer noise to 0.15°. The roll gain rises and the estimated horizon follows the false tilt. Raise it to 80°, then switch the tilt update off. A large variance gives a small correction. Switching it off skips the observation entirely. Now scrub to the end to see what the gyro offset does over time.
  2. Change how certain the prediction is. Restore the defaults and increase gyro noise to 10°/s. More angular uncertainty enters Q at each prediction. With tilt updates enabled, watch the roll correction gain. This setting describes uncertainty in the rate used for prediction. It leaves the recorded gyro samples intact.
  3. Take away the height reference. Reset, choose Height on the flight trace, then uncheck the range update. This bench predicts that height persists, with some uncertainty accumulated at each tick. The height estimate stays at its initial 2 m as the fixture climbs, and the height variance grows. Re-enable the ToF sensor and compare KF with EKF during the bank.

Ask for a turn. What does the estimator actually see?

Choose Replay → Choose target attitude. Start with 20° of roll, zero pitch and zero yaw. That target has quaternion [0.9848, 0.1736, 0, 0]. Scrub to 1.9 s and press Play. At 2 s the requested angle jumps. The virtual fixture takes three seconds to turn. Its gyroscope senses the turn as it happens, and its accelerometer senses the changing gravity direction. The estimator only receives the sensor readings. Switch the flight trace to Roll to compare the dotted target, dashed fixture and solid estimate.

Now pause during the disturbance at 7 s. Keep the target fixed and move the accelerometer noise slider. Under the slider, the teal bell shows the filter’s assumed distribution of tilt error around zero. The dashed amber bell keeps the default setting for comparison. Raising σ from 4° to 10° widens the central 68% interval from ±4° to ±10°. The same discrepancy now produces a smaller correction. The fixture and its recorded readings stay put. Each sensor’s bell uses its own units; the gyro’s rate noise enters the prediction, while tilt and range noise weight the observations.

Try adding pitch and yaw to the target. The fixture follows the shortest rotation between its starting and target quaternions. Target to estimate includes the time the fixture needs to turn. Fixture to estimate isolates the estimation error because this simulation knows the actual orientation. The setpoint drives a prescribed bench motion; the Kalman estimate is used for the display.

What can two or four rangefinders see?

The fixture below starts 0.6 m above a flat pad, banked 20° with two downward sensors, 20 cm either side of centre. The left beam travels about 0.711 m and the right about 0.566 m. Level the fixture and both read 0.600 m. These are ideal geometric distances. The full flight bench above adds sensor noise so you can compare geometry with estimation.

Two downward beams from a banked fixture meet the same level pad at different distances.
Move the rangefinder mounts. Change roll from +20° to −20°. Watch the longer and shorter beams exchange sides. Try a shorter arm, then point the nose sensor forward to see its return move to the wall.
What a range observation can tell us in this room
Mount and directionWhat we can infer
One downward beamOne slant distance to the pad. To turn it into vertical height, supply the beam’s orientation and the mount offset.
Left and right, both downOn a level plane, tan(roll) = (left range − right range) / baseline. At 20 cm from the centre on either side, the baseline is 0.40 m. A 20° bank produces about 0.146 m of range difference. The pair alone leaves tilt along the other direction unresolved.
Four arms, all downThree non-collinear returns suffice to fit a plane; the fourth gives a redundant observation. The left–right and nose–tail slopes together yield roll, pitch and vertical height relative to that plane. Turning around the plane’s normal leaves the distances unchanged, so floor ranges alone cannot reveal yaw.
Nose beam facing forwardThe first surface in the beam can be a wall. That reading gives clearance along the beam. A single beam sees only its own line of sight. The bench displays this return separately and excludes it from the floor update.

In body axes, take a downward sensor at position (x, y, 0), measured forward and right from the centre. Its expected range is h / (cos φ cos θ) + x tan θ / cos φ − y tan φ. Each mount gets its own measurement function. The bench sends its valid downward floor returns to the selected filter one at a time, using the centre or arm coordinates for each update. The displayed floor-only fit comes straight from this tick’s ranges, so you can compare it with the estimate that also uses the gyro and accelerometer.

Try shortening the arms to 10 cm. The same roll produces half the left–right difference while the range errors stay the same size. This simulated room has a flat floor and a wall 2 m ahead; the simulated useful distance is 0.05–4 m. The room supplies the identity of the surface that each ray hits. A real ToF reading supplies a distance, and a sloping landing pad, a table edge or a blocked beam can change what that distance means. Here the arm channels have independent simulated 0.012 m noise and the original centre channel keeps its 0.12 m noise. The range noise slider sets the assumed uncertainty for each accepted floor update.

The sliders use standard deviation σ in sensor units; the filter squares it to get a variance. The displayed gains are the current roll-from-tilt and height-from-range entries of the gain vectors. The quaternion readout is the estimated orientation expressed as [w, x, y, z], body to world. This bounded example estimates three local angles internally and converts them to a unit quaternion for display. It has no absolute heading sensor, no gyro-bias state and no vertical-speed state. The earlier bench example shows what changes when we explicitly add a bias state.

What I’d check on real sensor data

I’d start on the bench with a target at a measured distance. I’d keep the timestamps and look at two numbers separately. How far is the mean from the tape measurement? How widely do the readings scatter around that mean? A 20 cm standard deviation gives a starting R of 0.04 m². A mean that stays 20 cm too high points me toward calibration.

During a climb, I’d plot the innovations against time. A sustained run of positive values means the rangefinder keeps seeing the drone higher than predicted. Sensor timestamps, frame conventions and calibration would be my first checks. When intervals vary, the motion prediction and its process covariance both need to reflect the elapsed time.

Finally I’d remove a few range samples from a replay. The estimator can keep predicting until a fresh reading arrives. I’d plot the uncertainty alongside height and mark the gap. Even if the height trace barely moves, the growing uncertainty tells me how much of that interval the estimate spent on its own. An independent reference trace, when available, gives me a way to measure the error.

Follow the linear filter into our C repositories

Here are the two examples I’d run side by side. Both use the public se_linear_kf_predict and se_linear_kf_correct functions from our library. The first carries height. The second carries height and climb rate, while the rangefinder still reports just one number.

With Git and a C99 compiler installed, open a fresh checkout at the revision used here. Save the two listings below as height.c and climb.c in the root of that checkout.

Get the library revision used for these examplesbash
git clone https://github.com/antshiv/stateEstimation.git
cd stateEstimation
git checkout --detach 3d209b5e3c883cfd2bcb266a92b3a813fde78f72

One height, three readings

The state and its variance each occupy one double. Passing their addresses lets the caller see both values after each update. gap is the innovation, the distance from the predicted height to the new reading, in metres.

height.cc
#include <stdio.h>
#include "filters/linear_kalman.h"

int main(void) {
    // One state (metres), one observation (metres).
    const double initial_height = 0.0, initial_variance = 4.0;
    const double F = 1.0, H = 1.0, Q = 0.08, R = 1.0;
    const double readings[] = {4.2, 2.6, 3.8};
    double height, variance, work[32];
    se_linear_kf_t filter;
    if (se_linear_kf_init(&filter, 1, 1, &height, &variance,
                          work, 32, &initial_height, &initial_variance) != SE_KF_OK)
        return 1;

    puts("range   gap   height   variance");
    for (size_t i = 0; i < sizeof readings / sizeof readings[0]; ++i) {
        double gap;
        if (se_linear_kf_predict(&filter, &F, &Q) != SE_KF_OK)
            return 2;
        if (se_linear_kf_correct(&filter, 1, &H, &R, &readings[i], &gap) != SE_KF_OK)
            return 3;
        // gap uses the prediction. height and variance now contain the correction.
        printf("%4.1f  %+5.3f  %5.3f    %5.3f\n", readings[i], gap, height, variance);
    }
    return 0;
}
Build and run the scalar examplebash
cc -std=c99 -Wall -Wextra -Iinclude height.c src/filters/linear_kalman.c -lm -o height
./height
Output · height in metres, variance in square metrestext
range   gap   height   variance
 4.2  +4.200  3.373    0.803
 2.6  -0.773  3.011    0.469
 3.8  +0.789  3.290    0.354

Read the middle row. The sensor reports 2.6 m after the estimate had reached 3.373 m. The gap turns negative, so the update brings height down to 3.011 m. You can follow the sign change directly in the output.

One range reading updates two state entries

Keep the same API. Now state[0] holds height, state[1] holds climb rate, and P[1] is the top-right entry of the row-major covariance matrix. The observation row H = {1, 0} tells the library exactly what the rangefinder can see.

climb.cc
#include <stdio.h>
#include "filters/linear_kalman.h"

int main(void) {
    const double start[] = {0, 1};          // 0 m, climbing at 1 m/s
    const double initial_P[] = {1, 0, 0, 1};
    const double F[] = {1, 1,               // height += 1 second * climb rate
                        0, 1};              // climb rate stays constant
    const double Q[] = {0, 0, 0, 0};        // isolate one motion step
    const double H[] = {1, 0};              // rangefinder observes height
    const double R = 1, range = 2.5;
    double state[2], P[4], work[32], gap;
    se_linear_kf_t filter;
    if (se_linear_kf_init(&filter, 2, 1, state, P, work, 32, start, initial_P) != SE_KF_OK)
        return 1;
    if (se_linear_kf_predict(&filter, F, Q) != SE_KF_OK)
        return 2;
    printf("Predicted: %.2f m, %.2f m/s, cross-covariance %.2f m^2/s\n",
           state[0], state[1], P[1]);
    if (se_linear_kf_correct(&filter, 1, H, &R, &range, &gap) != SE_KF_OK)
        return 3;
    printf("Range gap: %+.2f m. Corrected: %.2f m, %.2f m/s\n",
           gap, state[0], state[1]);
    return 0;
}
Build and run the two-state examplebash
cc -std=c99 -Wall -Wextra -Iinclude climb.c src/filters/linear_kalman.c -lm -o climb
./climb
Output · one second and one range observationtext
Predicted: 1.00 m, 1.00 m/s, cross-covariance 1.00 m^2/s
Range gap: +1.50 m. Corrected: 2.00 m, 1.50 m/s

Look at the cross-covariance before the range reading arrives. It started at zero. After one second, an error in the starting climb rate also affects the predicted height, and that entry has grown to 1 m²/s. That is how a single range reading can move the speed estimate from 1.00 to 1.50 m/s.

Follow the calls into the library

In stateEstimation, the caller owns three flat arrays: the state, the covariance and the scratch workspace. The interface takes the state dimension and maximum measurement dimension. For our height-and-climb-rate estimate that means two state entries, four row-major covariance entries, and room to correct from one range reading. The default numerical path uses doubles. The EKF and UKF range example above is a Python teaching example; the repository lists nonlinear paths as experimental. Implementation scope · C interface.

  1. Prediction. Open se_linear_kf_predict. Follow the row-times-vector loop into the state, then the two row-times-column loops for the covariance. The transpose changes which index is read in the second multiplication. Q is added after the covariance is transported. Prediction loops.
  2. Correction. Follow the measured-minus-predicted subtraction, the products for the state–measurement covariance and S, and the gain. This reference implementation explicitly inverts the small innovation matrix. It forms the Joseph update and restores symmetry before committing the result. Correction loops.
  3. Independent replay. The native tests exercise the C API. A separate C trace is compared with GNU Octave on a trajectory whose measurement dimension changes. Both Kalman test targets passed in a fresh local build for this article. That evidence concerns the linear filter. Native cases · Octave comparison.

The neighbouring repositories answer different questions. dynamic_models is where I’d look for point-mass dynamics. attitudeMathLibrary holds quaternion arithmetic when orientation enters the state. The INS estimation wrapper shows the integration boundary. A controller has a further job: given an estimate and a target, compute a command. See the PID implementation in controlSystems. These are related pieces you can read separately.

Go one level deeper

For a book-length treatment, Phil Kim’s Kalman Filter for Beginners also starts with recursive averages before building up to linear and nonlinear estimation. Book details and MATLAB examples.