Course contents 08 / 22

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 xx027
P(X=x)P(X=x)1/41/41/21/21/41/4

Expectation#

For a real random variable with E[∣X∣]<∞E[|X|]<\infty, its expectation, or mean, is the probability-weighted average. For a countable support and for a distribution with a density, respectively,

E[X]=∑xxP(X=x),E[X]=∫−∞∞xfX(x) dx.E[X]=\sum_x xP(X=x),\qquad E[X]=\int_{-\infty}^{\infty}x f_X(x)\,dx.

Absolute integrability makes these finite values well-defined, without relying on a particular cancellation order. A nonnegative variable can also have expectation +∞+\infty; that is not a finite mean. For signed variables, subtracting two infinite parts does not define an expectation.

For our cost,

μ=E[X]=0⋅14+2⋅12+7⋅14=114=2.75.\mu=E[X]=0\cdot\frac14+2\cdot\frac12+7\cdot\frac14=\frac{11}{4}=2.75.

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 mm satisfies P(X≤m)≥1/2P(X\le m)\ge1/2 and P(X≥m)≥1/2P(X\ge m)\ge1/2. 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.

Figure

The centre depends on the question

Three probability masses and the meanMasses 1/4, 1/2, 1/4 at 0, 2, 7. The mean 11/4 is marked between 2 and 7.1/401/221/47μ = 2.75median = mode = 2
Four equiprobable plans cost 0, 2, 2 and 7. Mode and median are 2; the probability-weighted mean is 2.75. Stem heights represent probability masses, not a continuous density.

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 X,YX,Y and finite constants,

E[aX+bY+c]=aE[X]+bE[Y]+c.E[aX+bY+c]=aE[X]+bE[Y]+c.

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 E[2+3X]=2+3(11/4)=41/4E[2+3X]=2+3(11/4)=41/4.

An event indicator 1A\mathbf1_A equals one on A and zero otherwise, so E[1A]=P(A)E[\mathbf1_A]=P(A). 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

C=1{X>0}+1{X=2},E[C]=34+12=54.C=\mathbf1_{\{X>0\}}+\mathbf1_{\{X=2\}},\qquad E[C]=\frac34+\frac12=\frac54.

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 pjp_j and advances to the next stage; failure stays at the current stage. Attempts use fresh independent randomness, with constant success probabilities 3/43/4, 1/31/3 and 2/52/5. There is no restart of completed stages and no parallel work. Let TjT_j count all attempts at stage j, including its successful attempt. Thus TjT_j has the geometric convention on positive integers.

The tail probability is P(Tj>k)=(1−pj)kP(T_j>k)=(1-p_j)^k for nonnegative integers k. Summing the geometric series gives E[Tj]=1/pjE[T_j]=1/p_j. For total attempts T=T1+T2+T3T=T_1+T_2+T_3,

E[T]=43+3+52=416≈6.833.E[T]=\frac{4}{3}+3+\frac52=\frac{41}{6}\approx6.833.
Figure

Sequential stages retry the current step

  1. Stage 1

    Success: 3/4

    Retry: 1/4

    E[T1] = 4/3

    Success → next stage

  2. Stage 2

    Success: 1/3

    Retry: 2/3

    E[T2] = 3

    Success → next stage

  3. 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

Failure stays at the current stage; success advances. Attempts are independent and probabilities are constant. Mean attempt counts add, but their sum does not specify an individual job’s completion deadline.

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 E[∣g(X)∣]<∞E[|g(X)|]<\infty,

E[g(X)]=∑xg(x)P(X=x),E[g(X)]=∫g(x)fX(x) dx.E[g(X)]=\sum_x g(x)P(X=x),\qquad E[g(X)]=\int g(x)f_X(x)\,dx.

There is no need to derive the distribution of g(X) first. For the squared cost,

E[X2]=02+22+22+724=574,(E[X])2=12116.E[X^2]=\frac{0^2+2^2+2^2+7^2}{4}=\frac{57}{4},\qquad (E[X])^2=\frac{121}{16}.

These differ by 107/16107/16. Squaring after averaging loses the spread of the original values. More generally, Jensen’s inequality says

g(E[X])≤E[g(X)]g(E[X])\le E[g(X)]

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, E[log⁡X]≤log⁡E[X]E[\log X]\le\log E[X]. 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 E[X2]<∞E[X^2]<\infty. This also ensures a finite first absolute moment. Variance measures mean squared deviation from the mean:

Var⁡(X)=E[(X−μ)2]=E[X2]−μ2.\operatorname{Var}(X)=E[(X-\mu)^2]=E[X^2]-\mu^2.

The second form follows by expanding the square and applying linearity. For the four costs,

Var⁡(X)=574−12116=10716,σ=Var⁡(X)=1074.\operatorname{Var}(X)=\frac{57}{4}-\frac{121}{16}=\frac{107}{16},\qquad \sigma=\sqrt{\operatorname{Var}(X)}=\frac{\sqrt{107}}4.

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

E[(X−a)2]=Var⁡(X)+(a−μ)2.E[(X-a)^2]=\operatorname{Var}(X)+(a-\mu)^2.

The cross term vanishes because E[X−μ]=0E[X-\mu]=0, so a constant a cannot improve on the mean. At the median 2 the squared error is 29/429/4, larger than 107/16107/16 at the mean. Conversely, the expected absolute error is minimized at 2, where it equals 7/47/4.

The standard distribution summaries fit these definitions. Geometric here counts the successful trial and has 0<p≤10<p\le1. For Bernoulli and binomial, 0≤p≤10\le p\le1, and n is a nonnegative integer. Rates are positive, the normal variance is positive, and the uniform distribution has finite endpoints a<ba<b.

DistributionMeanVariance
Bernoulli⁡(p)\operatorname{Bernoulli}(p)ppp(1−p)p(1-p)
Bin⁡(n,p)\operatorname{Bin}(n,p)npnpnp(1−p)np(1-p)
Geom⁡(p)\operatorname{Geom}(p) on 1,2,…1,2,\ldots1/p1/p(1−p)/p2(1-p)/p^2
Poisson⁡(λ)\operatorname{Poisson}(\lambda)λ\lambdaλ\lambda
U(a,b)U(a,b)(a+b)/2(a+b)/2(b−a)2/12(b-a)^2/12
Exp⁡(λ)\operatorname{Exp}(\lambda)1/λ1/\lambda1/λ21/\lambda^2
N(μ,σ2)N(\mu,\sigma^2)μ\muσ2\sigma^2

Scaling gives Var⁡(aX+b)=a2Var⁡(X)\operatorname{Var}(aX+b)=a^2\operatorname{Var}(X). 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 X1,…,XnX_1,\ldots,X_n with finite variance, define Xˉn=n−1∑iXi\bar X_n=n^{-1}\sum_i X_i. Then

E[Xˉn]=μ,Var⁡(Xˉn)=σ2n,sd⁡(Xˉn)=σn.E[\bar X_n]=\mu,\qquad \operatorname{Var}(\bar X_n)=\frac{\sigma^2}{n},\qquad \operatorname{sd}(\bar X_n)=\frac{\sigma}{\sqrt n}.

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 107/16107/16; an average of four independent costs has variance 107/64107/64, and an average of sixteen has 107/256107/256. 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: E[(X−μ)3]/σ3E[(X-\mu)^3]/\sigma^3 describes skewness, and E[(X−μ)4]/σ4E[(X-\mu)^4]/\sigma^4 is kurtosis, without subtracting three. Kurtosis weights large standardized deviations; it is not a probability of an extreme event.

The moment generating function is MX(t)=E[etX]M_X(t)=E[e^{tX}], which may be infinite. If it is finite on an open interval around zero, derivatives there encode moments, with MX(k)(0)=E[Xk]M_X^{(k)}(0)=E[X^k]. That finite-neighbourhood condition justifies interchanging derivatives and expectation; a formal derivative of the integrand alone does not. Our finite-support cost has

MX(t)=14+12e2t+14e7t,MX′(0)=114,MX′′(0)=574.M_X(t)=\frac14+\frac12e^{2t}+\frac14e^{7t},\qquad M_X'(0)=\frac{11}{4},\quad M_X''(0)=\frac{57}{4}.

Independence gives MX+Y(t)=MX(t)MY(t)M_{X+Y}(t)=M_X(t)M_Y(t) 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 P(Z=2k)=3/4kP(Z=2^k)=3/4^k for integers k≥1k\ge1. Its probabilities sum to one and

E[Z]=3∑k=1∞2−k=3,E[Z2]=3∑k=1∞1=∞.E[Z]=3\sum_{k=1}^{\infty}2^{-k}=3,\qquad E[Z^2]=3\sum_{k=1}^{\infty}1=\infty.

For every positive t, the terms 3et2k/4k3e^{t2^k}/4^k 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:

ψX(t)=E[eitX]=E[cos⁡(tX)]+iE[sin⁡(tX)],t∈R.\psi_X(t)=E[e^{itX}]=E[\cos(tX)]+iE[\sin(tX)],\qquad t\in\mathbb R.

It always exists for a real random variable because ∣eitX∣=1|e^{itX}|=1. It determines the distribution, and independent sums again give products. For the finite cost, ψX(π)=1/2\psi_X(\pi)=1/2; 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 [−m,m][-m,m] has characteristic function sin⁡(mt)/(mt)\sin(mt)/(mt) 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#

QuestionQuantity 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 P(W=2k)=P(W=−2k)=2−k−1P(W=2^k)=P(W=-2^k)=2^{-k-1} for k≥1k\ge1. 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#