Probability for Robotics · Theory · M4
M4-T1 — Expectation and Variance
The mean says where a distribution is centred. The variance says how far a typical value strays. Together they are all a Gaussian filter ever stores.
A distribution is a whole curve, but a filter cannot carry a curve around, so it carries two summaries: where the curve is centred and how wide it is. This lesson defines both carefully, proves the rules that let you combine them (the mean of a sum, the variance of a sum of independent quantities, the square-root growth of random drift), and warns about the traps: a function of the average is not the average of the function, and a sample variance computed with the wrong divisor is systematically too small.
Learning objectives
After this lesson, you should be able to:
- Compute the expectation and variance of discrete and continuous random variables, and say what each means physically.
- Use linearity of expectation and the rule that variances of independent quantities add, with proofs.
- Explain why random errors grow like the square root of the number of steps while bias grows in proportion to it, and compute the crossover.
- Distinguish E[g(X)] from g(E[X]), and explain why the sample variance divides by n − 1.
The intuition
Return to the clay of the first lessons: a unit of probability spread along an axis. The expectation (or mean) is where the clay would balance on a knife edge, its centre of mass. For the five camera frames of the Module 2 detector the bars balance at 4.0: on average four of five frames detect the marker. The expectation need not be a value that can occur, and it is a long-run average rather than a prediction: any single run gives 3, 4 or 5.
The variance measures how widely the clay is spread around that balance point. It is the average squared distance from the mean. Squaring has two virtues: it makes distances on both sides positive, and, unlike absolute values, it makes spreads add when independent quantities are combined, which the derivation below proves. The standard deviation is the square root of the variance, which brings it back to the unit of the quantity (a variance of centimetres squared would be hard to picture): for the five frames, 0.89 detections.
The right-hand panel is the single most important consequence in the lesson for a mobile robot. Suppose each metre driven adds an independent error with standard deviation 2 cm. After 100 m the error is not 100 × 2 cm = 200 cm but 2 cm × √100 = 20 cm: independent errors partly cancel, so the total grows only as the square root of the number of steps. A systematic error does not cancel. A bias of just 0.5 cm per metre adds to 50 cm after 100 m and dominates the random error after 16 m. This is why calibration of wheel diameters matters more than buying a quieter sensor, and why “odometry drift” is usually a bias problem.
Random errors add in quadrature, so they grow like √n. Systematic errors add up directly, so they grow like n. Distinguish them before deciding what to fix.
Definitions
- Expectation or
- The probability-weighted average of the values of : the centre of mass of the distribution. Also written or .
- Variance or
- The expected squared distance from the mean. Its unit is the unit of squared.
- Standard deviation
- The square root of the variance, in the unit of . A typical size of a deviation from the mean.
- Expectation of a function
- The probability-weighted average of : first transform each value, then average.
- Sample mean and sample variance
- Estimates of the above computed from readings: the average, and the sum of squared deviations from the average divided by .
The values for the distributions of the last module, worth knowing by heart:
| Distribution | Mean | Variance |
|---|---|---|
| Bernoulli() | ||
| Binomial() | ||
| Uniform on | ||
| Exponential() | ||
| Gaussian() |
Derivation: the rules for combining means and variances
Variance as a difference
Expand the square inside the expectation.
Expectation is linear: it passes through sums and constants (proved next). is a constant.
Use . The variance is the mean of the square minus the square of the mean, and so (always at least ).
Linearity of expectation
The expectation of a function of two variables, summed over the joint table.
Split the sum and marginalize (last module): . No assumption about independence was used, so the mean of a sum is always the sum of the means.
Sums of independent quantities
Expand the square of the sum of the two deviations. The last term is called the covariance of and (next lesson).
For independent variables the expectation of a product is the product of the expectations (the joint table factorizes), and each centred variable has mean zero.
The second formula: .
For independent copies. The spread of the total grows as and the spread of the average shrinks as . The second is the standard error of the Monte Carlo lesson; the first is the odometry drift above.
Why the sample variance divides by n − 1
The true variance is the average squared distance from the true mean, which is unknown. We use the sample mean instead, and that is a closer point to the data than the truth is.
Write , expand, and use . The sum around the sample mean is smaller than the sum around the true mean.
Take expectations: each has mean , and from the previous derivation.
Dividing by makes the estimator unbiased. Dividing by would give : 20% too small for five readings.
The sum of two Gaussians is Gaussian
The mean and variance of a sum follow from the rules above for any distributions. That the sum of independent Gaussians is again a Gaussian needs one more step, a convolution, and completing the square. For zero means, with variances and :
The density of a sum of independent variables is the convolution of the densities: every way of splitting into and .
Complete the square in . The first term depends on and the second does not.
The integral over of the first term is a Gaussian integral, a constant that does not depend on . What remains is a Gaussian in with variance .
The mean of a sum is the sum of the means, always. The variance of a sum is the sum of the variances when the parts are independent. Averaging n independent readings divides the standard deviation by √n; adding n independent errors multiplies it by √n.
A worked example
Four calculations, all printed by the program below.
- Mean and variance from a mass function. For the five-frame count with : and , matching the formulas and .
- Odometry drift. Each metre adds an independent error with standard deviation 2 cm. After 10 m the standard deviation is cm and after 100 m cm (simulation: 6.37 and 19.91). A bias of 0.5 cm per metre gives a mean error of 5.0 cm and 50 cm (simulation: 5.02 and 49.78). The bias overtakes the noise where , at m.
- A function of an average. A robot drives a fixed distance at a speed that varies uniformly between 0.5 and 1.5 m/s, average 1.0 m/s. The time per metre is . Its expectation is s per metre, not : the trip takes on average 10% longer than at the average speed. (Simulation: 1.101.)
- The divisor n − 1. Draw five readings from a distribution with variance exactly 1, compute the sample variance, and average over 20 000 repetitions. Dividing by gives 0.801; dividing by gives 1.005.
- Sum of Gaussians. Adding independent Gaussians with standard deviations 3 and 4 gives 4.986 in simulation: .
import math
from robotprob import Rng, mean, std, variance, binomial_pmf
pmf = {k: binomial_pmf(k, 5, 0.8) for k in range(6)} # detections in 5 frames
m = sum(k * p for k, p in pmf.items())
v = sum((k - m) ** 2 * p for k, p in pmf.items())
print('binomial(5, 0.8): mean', round(m, 4), ' variance', round(v, 4), ' formulas', 5 * 0.8, round(5 * 0.8 * 0.2, 4))
rng = Rng(5) # odometry: 2 cm of independent noise per metre
def drift(n_steps, bias):
return sum(bias + rng.gauss(0.0, 2.0) for _ in range(n_steps))
for n_steps in (10, 100):
noise_only = [drift(n_steps, 0.0) for _ in range(4000)]
with_bias = [drift(n_steps, 0.5) for _ in range(4000)]
print(n_steps, 'm: noise only std', round(std(noise_only), 2), 'cm (theory', round(2 * math.sqrt(n_steps), 2), ')',
' with bias mean', round(mean(with_bias), 2), 'cm (theory', 0.5 * n_steps, ')')
speeds = [rng.uniform(0.5, 1.5) for _ in range(200000)] # E[g(X)] is not g(E[X])
print('mean speed', round(mean(speeds), 3), ' mean of 1/speed', round(mean([1 / s for s in speeds]), 3), ' exact', round(math.log(3), 4))
def avg_var(ddof): # why the sample variance divides by n - 1
t = 0.0
for _ in range(20000):
t += variance([rng.gauss(0.0, 1.0) for _ in range(5)], ddof)
return t / 20000
print('sample variance of 5 readings, true variance 1: divide by n ->', round(avg_var(0), 3), ' divide by n-1 ->', round(avg_var(1), 3))
s = [rng.gauss(0.0, 3.0) + rng.gauss(0.0, 4.0) for _ in range(100000)]
print('sum of N(0, 3^2) and N(0, 4^2): std', round(std(s), 3), ' (sqrt(9 + 16) = 5)')binomial(5, 0.8): mean 4.0 variance 0.8 formulas 4.0 0.8 10 m: noise only std 6.37 cm (theory 6.32 ) with bias mean 5.02 cm (theory 5.0 ) 100 m: noise only std 19.91 cm (theory 20.0 ) with bias mean 49.78 cm (theory 50.0 ) mean speed 0.999 mean of 1/speed 1.101 exact 1.0986 sample variance of 5 readings, true variance 1: divide by n -> 0.801 divide by n-1 -> 1.005 sum of N(0, 3^2) and N(0, 4^2): std 4.986 (sqrt(9 + 16) = 5)
variance(xs, ddof) divides by n - ddof; the default ddof=1 is the unbiased estimator. Under NumPy the default is the opposite: numpy.var divides by n.In robotics
Error budgets: random drift versus bias
Dead-reckoning error after a distance has a random part that grows like and a systematic part that grows like . The estimate of the covariance that a localizer carries between corrections follows the √ law; a calibration error (a wheel radius off by 1%) shows up as a straight line of error that no covariance model describes. Plotting position error against distance on a log-log plot separates the two at a glance: a slope of ½ is noise, a slope of 1 is bias. The SLAM course shows the typical drift curves in Odometry and Motion Models.
Averaging and its limits
Averaging independent readings reduces the standard deviation by . Going from 1 cm to 1 mm takes 100 readings, and each extra digit costs a hundred times more. It does nothing for the bias or for readings that are not independent (M3-T3: Independence and Conditional Independence).
Nonlinear functions of an uncertain quantity
Time is distance over speed, energy is mass times speed squared, a range is the square root of a sum of squares. For a nonlinear function the average of the function is not the function of the average. In the example, a symmetrical spread of speeds makes the trip take 10% longer than at the average speed. A planner that uses the mean speed to predict arrival times is therefore optimistic. M4-T4: Propagating Uncertainty Through Transformations derives how to push a whole distribution through a nonlinear function.
Variance as a performance metric
The root-mean-square error of a trajectory, the spread of repeated trials, and the standard deviation of a controller's tracking error are all variances in disguise. The mean error tells you whether the robot is biased, the standard deviation whether it is repeatable, and both are needed: a robot can be unbiased and useless, or very repeatable and consistently wrong.
Software defaults differ
NumPy's var and std divide by n by default, while Matlab, R and most statistics packages divide by n − 1. For three readings the two standard deviations differ by 22%. State in your code which one you mean.
Common misconceptions
“The expected value is the most likely value.”
It is the average. For a symmetrical single-peaked distribution they coincide; for a skewed one they do not. The expected number of detections in five frames is 4.0 here, but a heavily skewed distribution, such as the time between rare failures, has an average far from its most likely value.
“Errors of 2 cm per metre add up to 200 cm after 100 m.”
Only if they are perfectly correlated (all the same sign). Independent errors partly cancel and add in quadrature: 2 cm × √100 = 20 cm. The opposite mistake, treating a bias as if it were independent noise, underestimates drift by a factor of up to √n.
“The expectation of a function is the function of the expectation.”
Only for linear functions. For 1/v, v², √v, tan and every other nonlinearity the two differ, by an amount that grows with the variance. This difference is the origin of the bias of the extended Kalman filter (module 8).
“The variance of the difference of two independent quantities is the difference of the variances.”
It is the sum: Var(X − Y) = Var(X) + Var(Y), since Var(−Y) = Var(Y). A difference of two noisy readings is noisier than either, which is why differentiating noisy positions to get a velocity amplifies noise.
Key takeaways
- The expectation is the balance point of the distribution, the variance the average squared distance from it, and the standard deviation its square root, in the unit of the quantity.
- Expectation is linear, always. Variance adds only for independent quantities: Var(X + Y) = Var(X) + Var(Y), Var(aX) = a² Var(X).
- n independent errors add to a standard deviation σ√n; their average has σ/√n. A systematic error adds up as n and overtakes the random part after a crossover distance.
- E[g(X)] ≠ g(E[X]) for nonlinear g. The gap is the reason uncertain quantities cannot be pushed through nonlinear functions by their means alone.
- The sample variance divides by n − 1 to be unbiased: dividing by n is too small by a factor (n − 1)/n. Check which one your software uses.
References and further reading
Each source is marked free or paid. Free to read does not mean free to reuse: the course resources page lists every source with its licence.
- J. Tsitsiklis and P. Jaillet, MIT RES.6-012 Introduction to Probability , lectures 5 to 7 (expectation and variance) and lecture 12 (sums of independent random variables). Free videos and notes, licence CC BY-NC-SA 4.0.
- J. Blitzstein and J. Hwang, Introduction to Probability, 2nd edition, CRC Press, 2019 , chapter 4 (expectation) and chapter 6 (moments). Free to read online; the book is copyrighted.
- T. D. Barfoot, State Estimation for Robotics, 2nd edition, Cambridge University Press, 2024 , chapter “Primer on Probability Theory”. Free to read as the author’s PDF; the book is copyrighted.
- C. Piech, Probability for Computer Scientists (Stanford CS109 course reader) , part 2 (expectation, variance). Free to read online.
Knowledge check
Three questions. Write an answer, then reveal the explanation. Your answers stay in your browser.
Question 1
A mobile robot’s odometry adds an independent error with standard deviation 1 cm per metre. After driving 400 m, what are the standard deviation of the error from the random part, and the error from a systematic wheel-radius error of 0.3 cm per metre? At what distance do the two become equal?
Explanation
Random part: 1 cm × √400 = 20 cm. Systematic part: 0.3 cm × 400 = 120 cm, six times larger. They are equal where 0.3 n = √n, so √n = 1/0.3 = 3.33 and n = 11 m. Beyond 11 m the bias dominates, so calibrating the wheel radius is worth far more than a quieter encoder. Note that the two do not simply add: the root-mean-square total is √(20² + 120²) ≈ 122 cm.
Question 2
A sensor reading z has mean 2.00 m and standard deviation 0.10 m. A controller needs the squared distance z² for a cost function. What is E[z²], and why is it not 4.00 m²? How large is the gap, and when would it matter?
Explanation
E[z²] = Var(z) + (E[z])² = 0.01 + 4.00 = 4.01 m². It is larger than 4.00 because the mean of a square is at least the square of the mean; the gap is exactly the variance. Here it is 0.25%, which is negligible. It matters when the standard deviation is a sizeable fraction of the mean: with σ = 1 m and a mean of 2 m, E[z²] would be 5, 25% above the naive value. The same gap, applied to nonlinear measurement functions, is what makes linearized filters biased when the uncertainty is large.
Question 3
You compute the variance of 3 readings of a stationary target as 0.0004, 0.0001 and 0.0016 m² from three different runs, using the divide-by-n formula, and quote the average of them as the sensor variance. By what factor is that quote biased, and how do you correct it?
Explanation
Dividing by n instead of n − 1 gives an estimate that is too small on average by the factor (n − 1)/n = 2/3 for n = 3 readings per run. The average of the three values is 0.0007 m², so the unbiased value is 0.0007 × 3/2 = 0.00105 m², and the standard deviation is 0.032 m instead of 0.026 m. Correct by using the divide-by-(n − 1) estimator, or by multiplying by n/(n − 1). With only 3 readings per run the estimate is also very uncertain: pooling many runs is better than trusting any single one.
What’s next
The variance describes the uncertainty of one quantity. A robot’s pose has three at once, and they are not independent. The next lesson introduces the covariance that describes how uncertainties move together.
Related content
Nothing below is required to finish this lesson.
Other courses on this site treat neighbouring topics from their own angle:
Get notified when the next lesson and new labs are released.
One email per new lesson or lab.