08 / 22 · Random Variables
Expectation and variance
Summarize a distribution without losing its assumptions: exact weighted costs, dependent indicator counts, a three-stage retry process, Jensen's inequality and the difference between observation spread and uncertainty of an average. Optional transforms connect moments to distributions.
On this page 6
A complete distribution can answer many questions, but a budget often needs an average cost, and a measurement needs a description of its variability. We will calculate both from an explicit probability model, then distinguish the variation of one outcome from the uncertainty of an estimated average. The previous topic transformed variables; here we average their values or transformations.
Our main fictional experiment selects one of four labelled job plans uniformly. Their costs are 0, 2, 2 and 7 work units. The two plans costing 2 remain different outcomes, so the three cost values are not equally likely. The costs, separate retry process, diagrams and exact code were composed for this project with AI assistance. They are not observed workloads or an external dataset. Repeated selections, when used below, are independent with replacement.
| Cost | 0 | 2 | 7 |
|---|---|---|---|
Expectation#
For a real random variable with , its expectation, or mean, is the probability-weighted average. For a countable support and for a distribution with a density, respectively,
Absolute integrability makes these finite values well-defined, without relying on a particular cancellation order. A nonnegative variable can also have expectation ; that is not a finite mean. For signed variables, subtracting two infinite parts does not define an expectation.
For our cost,
No plan costs 2.75 units. The mean balances probability weights, rather than selecting a possible outcome. Under independent identically distributed repetitions with finite absolute mean, the law of large numbers says that the sample average converges to this value. It does not say every short run is close, or that each outcome approaches the mean.
A median satisfies and . Here it is 2. A discrete mode maximizes the probability of a value; it is also 2 here. Medians and modes need not be unique. A continuous mode refers to a chosen density version, not a positive probability of one point. For a distribution symmetric about a centre, that centre is a median; it is also the mean if the mean is finite. Symmetry alone cannot create a missing expectation.
The centre depends on the question
The choice of centre can reflect a loss. With a finite second moment, a constant forecast minimizing expected squared error is the mean. With a finite first absolute moment, medians minimize expected absolute error. For a discrete variable, choosing a mode minimizes the probability of guessing its value incorrectly. These are different questions, even when their answers coincide.
Linearity#
For integrable and finite constants,
Independence is unnecessary. On a finite outcome space, expand the sum over outcomes and distribute the multiplication; the general result uses the same linearity of integration. For example, a fixed two-unit overhead and three units per unit of X give mean total cost .
An event indicator equals one on A and zero otherwise, so . Therefore the expected count of events is the sum of their probabilities. In the four-plan example, mark a plan when its cost is positive, and separately when its cost is exactly 2. The two marks are dependent: the second implies the first. Nevertheless, the number C of present marks has
The four counts are 0, 2, 2 and 1. Their direct average confirms the result. Linearity did not require a joint independence assumption.
A different fictional process makes the same principle useful for waiting. A job must pass three stages in order. Each attempt costs one time unit. At stage j it succeeds with probability and advances to the next stage; failure stays at the current stage. Attempts use fresh independent randomness, with constant success probabilities , and . There is no restart of completed stages and no parallel work. Let count all attempts at stage j, including its successful attempt. Thus has the geometric convention on positive integers.
The tail probability is for nonnegative integers k. Summing the geometric series gives . For total attempts ,
Sequential stages retry the current step
Stage 1
Success: 3/4
Retry: 1/4
E[T1] = 4/3
Success → next stage
Stage 2
Success: 1/3
Retry: 2/3
E[T2] = 3
Success → next stage
Stage 3
Success: 2/5
Retry: 3/5
E[T3] = 5/2
Success → done
E[T] = 4/3 + 3 + 5/2 = 41/6 ≈ 6.833
Once the individual means are known, adding them uses only linearity. Our fresh-randomness mechanism also makes the stage waits independent, but independence is a separate property, not the reason their means add. If attempts depended on their history or success probabilities changed, the geometric means would need a new justification. The exact companion calculation finds completion within six attempts with probability about 0.552. A mean near 6.833 is neither a fixed deadline nor a statement that every job finishes after seven attempts.
The expectation of a function#
To average a measurable transformation g, reuse the original distribution. Provided ,
There is no need to derive the distribution of g(X) first. For the squared cost,
These differ by . Squaring after averaging loses the spread of the original values. More generally, Jensen’s inequality says
when g is convex on an interval containing the values of X and both expectations are finite. A sufficient geometric description of convexity is that the graph lies below each chord joining two of its points. For a differentiable convex function, a tangent at the mean lies below the graph; taking expectations of that affine tangent gives its value at the mean, which proves this version of the inequality. Concavity reverses the inequality.
For strictly positive X with finite mean and integrable logarithm, . The extra positivity condition matters: our cost distribution has mass at zero, so this finite-log form does not apply to it. Jensen’s inequality underlies variational bounds, but the support and integrability conditions of a particular variational-inference derivation still need checking. A formula for an average loss should likewise not be replaced by the loss at an average prediction without justification.
Variance#
Assume . This also ensures a finite first absolute moment. Variance measures mean squared deviation from the mean:
The second form follows by expanding the square and applying linearity. For the four costs,
Variance has squared cost units; standard deviation has cost units. Both describe the probability distribution, not yet uncertainty in an estimated mean. The squared-error identity promised above is
The cross term vanishes because , so a constant a cannot improve on the mean. At the median 2 the squared error is , larger than at the mean. Conversely, the expected absolute error is minimized at 2, where it equals .
The standard distribution summaries fit these definitions. Geometric here counts the successful trial and has . For Bernoulli and binomial, , and n is a nonnegative integer. Rates are positive, the normal variance is positive, and the uniform distribution has finite endpoints .
| Distribution | Mean | Variance |
|---|---|---|
| on | ||
Scaling gives . For independent finite-variance variables, variances add. Dependence can contribute covariance terms, developed in joint distributions; independence is sufficient, not necessary, for those terms to vanish.
For independent identically distributed with finite variance, define . Then
This standard deviation of the estimator is its standard error. It measures variation across repeated samples, not the spread of the individual observations. For our model, one cost has variance ; an average of four independent costs has variance , and an average of sixteen has . Quadrupling the sample size halves the standard error. It does not remove systematic bias or guarantee a particular confidence level without further analysis. Repeating the same observed cost four times would leave the variance of the average unchanged.
Moment and characteristic functions#
This optional section explains how distributions can be encoded by functions. The mean and variance use the first two moments. Higher standardized moments require the corresponding absolute moments and a positive finite standard deviation: describes skewness, and is kurtosis, without subtracting three. Kurtosis weights large standardized deviations; it is not a probability of an extreme event.
The moment generating function is , which may be infinite. If it is finite on an open interval around zero, derivatives there encode moments, with . That finite-neighbourhood condition justifies interchanging derivatives and expectation; a formal derivative of the integrand alone does not. Our finite-support cost has
Independence gives wherever the factors are finite. For an independent copy X’, the generating function of X+X’ is the square of this expression. Its terms group the possible summed costs; the companion code enumerates all sixteen labelled pairs. An MGF finite near zero determines the distribution uniquely.
A separately defined tail model shows the limit of this tool. Let for integers . Its probabilities sum to one and
For every positive t, the terms do not even tend to zero, so the MGF is infinite there. The mean exists, but neither a finite variance nor the standard-error formula above is available. Under independent identically distributed sampling the finite-mean law of large numbers still applies; it promises no universal square-root rate here.
The characteristic function avoids the exponential-integrability requirement:
It always exists for a real random variable because . It determines the distribution, and independent sums again give products. For the finite cost, ; for the dyadic heavy tail it remains well-defined even though positive-t exponential moments diverge.
Lévy’s continuity theorem relates these functions to weak convergence: convergence in distribution implies pointwise convergence of characteristic functions for every real t. Conversely, if characteristic functions converge at every real t to a function continuous at zero, that limit is a characteristic function and the distributions converge to its distribution. The all-t condition and continuity at zero are part of the theorem. For instance, a uniform variable on has characteristic function for nonzero t and value one at zero. As m grows it tends to zero at every nonzero t and stays one at zero. The discontinuous limit is not a characteristic function; mass is escaping every fixed bounded interval. Sheffield’s cited continuity-theorem passage states the theorem; the expanding-interval calculation here is direct.
What changed#
| Question | Quantity and conditions |
|---|---|
| What is the average cost? | Expectation, with a finite absolute first moment for a finite mean. |
| How do average costs combine? | Linearity; independence is unnecessary. |
| How does a nonlinear cost transform? | Average the transformed values; check Jensen’s conditions. |
| How variable is one outcome? | Variance and standard deviation, with finite second moment. |
| How uncertain is an average? | Standard error under a specified sampling/dependence model. |
| Can a transform identify a distribution? | An MGF finite near zero or a characteristic function on the real line. |
Limitations#
A mean need not exist even for a symmetric distribution. For example, assign for . Total probability is one, but both positive and negative expected parts are infinite. Symmetric partial cancellations give zero without defining E[W]. This is an analytic statement, not a conclusion from a finite simulation.
Finite means do not ensure finite variances, as Z demonstrates. Two moments also do not determine general tail probabilities. The cost and retry examples are exact fictional models; changes in weights, dependence, retries or selection change their answers. A standard deviation is not automatically a confidence interval, and an average of biased measurements can remain biased as its sampling variability shrinks.
What you should remember#
Expectation averages values with their probabilities. Linearity applies to integrable variables regardless of dependence, and indicators turn expected counts into sums of event probabilities. Nonlinear transformations must be averaged explicitly. Variance measures quadratic spread; the standard error of an average needs a sampling model and finite second moments. Transform identities are useful only with their stated existence and independence assumptions.
Code#
This standard-library calculation uses the complete finite cost model and the three specified geometric means. The full companion verifier also enumerates averages, retry completion probabilities and finite partial sums of the two tail models. Finite checks do not prove their infinite-limit statements.
from fractions import Fraction as F
from itertools import product
costs = [0, 2, 2, 7]
mean = F(sum(costs), 4)
second = F(sum(x*x for x in costs), 4)
variance = second - mean*mean
print('mean, second moment, variance:', mean, second, variance)
averages = [F(sum(xs), 4) for xs in product(costs, repeat=4)]
print('variance of four-cost average:', sum((x-mean)**2 for x in averages)/len(averages))
ps = [F(3,4), F(1,3), F(2,5)]
print('expected stage attempts:', [str(1/p) for p in ps])
print('expected total attempts:', sum(1/p for p in ps))
mean, second moment, variance: 11/4 57/4 107/16
variance of four-cost average: 107/64
expected stage attempts: ['4/3', '3', '5/2']
expected total attempts: 41/6
Next#
We summarized one variable and used assumptions about several copies. Joint distributions specifies several variables together, derives their marginals and conditional distributions, and makes the covariance terms in the variance of a sum explicit.
References#
- Kyle Siegrist, Random: Definitions and Basic Properties for integrability, expectation, transformations and linearity; Additional Properties for Jensen’s inequality; Variance for the second-moment identity and squared-error minimizer; Vector Spaces of Random Variables for the absolute-error median; Generating Functions for finite-neighbourhood MGF facts and characteristic-function definitions/products; The Law of Large Numbers for sample-mean moments and the finite-absolute-mean condition. CC BY 2.0 is declared on the author homepage. These are mathematical references; source exercises, figures and code are not imported.
- Scott Sheffield, MIT 18.175, Lecture 15: Characteristic functions and central limit theorem, the “Continuity theorems” passage. Scientific reference to Lévy’s theorem, not reuse of the slide layout, examples, proof text or illustrations. The finite and dyadic fixtures and retry process above are new project constructions.