Random Variables & Expectation
Random Variables & Expectation
Every number you ever read off a quantum computer is an estimate of an expectation value from a finite number of repetitions. This lesson builds the machinery — expectation, variance, concentration — that tells you exactly how good that estimate is, and how many shots you must pay for.
Learning Objectives
By the end of this lesson you will be able to:
- Define discrete and continuous random variables and their PMF/PDF/CDF, and compute expectation and variance from each.
- Use linearity of expectation and the variance of a sum to analyze estimators.
- Identify and parameterize the Bernoulli, Binomial, Geometric, and Gaussian distributions and state their means and variances.
- State the Law of Large Numbers and the Central Limit Theorem and explain the standard-error scaling of a sample mean.
- Apply Markov, Chebyshev, and Hoeffding inequalities to bound deviation probabilities and derive a shot count for a target confidence.
- Simulate sample-mean convergence in NumPy and verify the error scaling empirically.
Intuition
A random variable is a number attached to each outcome of an experiment — the measurement of the random world. Roll two dice; the sum is a random variable. Run a circuit and assign to outcome and to outcome ; that reading is a random variable, and its expectation value is precisely , the quantity variational algorithms minimize.
Two questions dominate everything downstream:
- Where is it centered? The expectation — the long-run average.
- How much does it wobble? The variance — the spread around the center.
The punchline of the whole lesson is this. You cannot read off a quantum computer directly; you can only sample a finite number of times ("shots") and average. That sample average is itself random. The Law of Large Numbers says it converges to ; the Central Limit Theorem says its fluctuations shrink like ; and concentration inequalities (Hoeffding) turn that into a hard promise: "with probability , my estimate is within of the truth, provided ". That inequality is, quite literally, the cost model for running on a QPU.
Theory
Random variables, PMF, PDF, CDF
Given a probability space , a random variable is a (measurable) function . Measurability means for every , so we may assign it a probability. The cumulative distribution function (CDF) is
non-decreasing, right-continuous, with , .
A discrete RV takes values in a countable set; its probability mass function (PMF) is , with and .
A continuous RV has a probability density function (PDF) with and . Note is a density, not a probability — it can exceed ; only its integral over a set is a probability. The CDF and PDF are linked by (where the derivative exists).
Expectation
The expectation (mean) of is its probability-weighted average:
when the sum/integral converges absolutely. For any (measurable) function , the law of the unconscious statistician gives — you do not need the distribution of , just that of .
Quantum tie-in. For a Pauli- measurement with outcomes , $\langle Z\rangle = \mathbb E[\text{reading}] = (+1)p_0 + (-1)p_1 = p_0 - p_1\langle Z\rangle$ on hardware is estimating an expectation from samples. We meet formally in Term 1.3.
Linearity of expectation
For any random variables (independent or not) and constants ,
Derivation (discrete, finite ). Expectation can be written as a sum over outcomes, . Then
The power of linearity is that it needs no independence — it is the single most useful identity in applied probability.
Variance and standard deviation
The variance measures spread about the mean:
where the second form follows by expanding the square and using linearity: with . The standard deviation is , in the same units as . Scaling: (shifts don't change spread; scales square).
For the sum of random variables,
When the are pairwise uncorrelated (in particular, independent), the covariance terms vanish and variances add: . This single fact drives the scaling below.
Key distributions
| Distribution | PMF / PDF | Mean | Variance | Models |
|---|---|---|---|---|
| Bernoulli | one shot, one bit | |||
| Binomial | # of s in i.i.d. shots | |||
| Geometric | # shots until first success | |||
| Gaussian | CLT limit; measurement noise |
Bernoulli variance derivation. for a variable, so $\mathbb E[X^2] = \mathbb E[X] = p\mathrm{Var}(X) = p - p^2 = p(1-p)p=\tfrac12$ (a fair coin / an equal superposition is the noisiest single bit). A Binomial is a sum of independent Bernoulli, so by linearity and additivity of variance its mean is and variance — no binomial-coefficient sums required.
Law of Large Numbers (LLN)
Let be i.i.d. with mean and finite variance . Define the sample mean . The (weak) law of large numbers states that for every ,
Derivation via Chebyshev. By linearity, . By additivity of variance for independent terms,
Chebyshev's inequality (below) gives $\mathbb P(|\bar X_M - \mu| \ge \varepsilon) \le \sigma^2/(M\varepsilon^2) \to 0\blacksquare$ This is why averaging more shots works.
The standard error — derived
The line is the most important formula in this whole course for practical work. The standard error of the sample mean — the standard deviation of the estimator — is its square root:
So to halve your statistical error you must quadruple your shots. To estimate a Pauli expectation with outcomes , the per-shot variance is $\sigma^2 = 1 - \langle Z\rangle^2 \le 1\mathrm{SE} \le 1/\sqrt M1/\sqrt M$ wall is fundamental: it governs runtime and dollar cost of every expectation-value estimation on a QPU, and it is the reason variational algorithms are shot-hungry.
Central Limit Theorem (CLT)
The LLN says ; the CLT says how the fluctuations are shaped. For i.i.d. with mean and finite variance , the standardized sample mean converges in distribution to a standard Gaussian:
Equivalently, for large . Two consequences we use constantly: (i) the error bars on a sampled expectation are Gaussian, so a interval is an approximate confidence interval; (ii) the width of that interval is , consistent with the standard error above.
Concentration inequalities
These bound the probability of large deviations and let us choose before running.
Markov's inequality. For a non-negative RV and ,
Derivation. pointwise (check both cases and ). Take expectations: .
Chebyshev's inequality. Apply Markov to with :
Weak (polynomial) but assumption-light — only finite variance needed.
Hoeffding's inequality. For independent with almost surely, and with mean ,
For identically bounded variables, with range , this simplifies to the form we will use:
This is exponentially stronger than Chebyshev for bounded variables (Chernoff-type bound). It is the right tool for shot counting because measurement readings are bounded (a Pauli reading has range ).
Shot count for a target confidence (the QPU cost model). Demand . Set the Hoeffding bound equal to and solve for :
For a Pauli observable (): . Want to with confidence ()? Then shots. That number — over a hundred thousand shots for two decimal places — is exactly why estimating many expectation values is the dominant cost in variational quantum algorithms, and why shot budgeting is a first-class design concern in Term 5.
Worked Examples
Example 1 — Expectation and variance of a Pauli reading
A qubit measured in the -basis yields outcome with probability and with probability . Assign the observable value to outcome and to outcome . Compute and in terms of .
Since always, , hence
The per-shot variance is largest () when , i.e. — the equal-superposition state is the hardest to estimate, needing the most shots. By the standard error formula, an -shot estimate of has $\mathrm{SE} = \sqrt{(1-\langle Z\rangle^2)/M} \le 1/\sqrt M$.
Example 2 — How many shots for a target precision?
You want to estimate for an unknown state to within with confidence (). The reading is bounded in so . Use Hoeffding:
So shots guarantee (with confidence) the estimate is within — worst-case, distribution-free. The CLT gives a typical-case estimate that's often smaller: setting with the worst-case gives $M = (1.96/0.02)^2 = 9604$. Hoeffding is the conservative promise; the CLT is the realistic expectation. Engineers quote both.
Hands-on (Python)
We simulate the sample mean of a Pauli reading, watch it converge to the true , and confirm the empirical error scales as .
import numpy as np
rng = np.random.default_rng(42)
# A qubit with P(outcome 0)=p0; reading z=+1 for outcome 0, z=-1 for outcome 1.
p0 = 0.7
true_expectation = (+1) * p0 + (-1) * (1 - p0) # <Z> = p0 - p1 = 0.4
per_shot_var = 1 - true_expectation**2 # = 1 - 0.16 = 0.84
def sample_readings(M, rng, p0):
"""Return M samples of the +/-1 reading for a qubit with P(0)=p0."""
bits = rng.random(M) < p0 # True (outcome 0) with prob p0
return np.where(bits, +1.0, -1.0) # map 0 -> +1, 1 -> -1
# Sample-mean convergence: estimate <Z> at increasing shot counts.
print(f"true <Z> = {true_expectation:.4f}\n")
print(f"{'M':>9} {'estimate':>10} {'|error|':>10} {'SE = sqrt(var/M)':>18}")
for M in (10, 100, 1_000, 10_000, 100_000, 1_000_000):
est = sample_readings(M, rng, p0).mean()
se = np.sqrt(per_shot_var / M) # predicted standard error
print(f"{M:>9} {est:>10.4f} {abs(est-true_expectation):>10.4f} {se:>18.5f}")# Verify the 1/sqrt(M) scaling: estimate the EMPIRICAL standard error by repeating
# the whole experiment many times at each M and taking the std of the estimates.
# A clean 1/sqrt(M) law means error * sqrt(M) is (approximately) constant.
Ms = np.array([16, 64, 256, 1024, 4096, 16384])
trials = 2000
emp_se = np.empty(len(Ms))
for i, M in enumerate(Ms):
estimates = np.array([sample_readings(M, rng, p0).mean() for _ in range(trials)])
emp_se[i] = estimates.std(ddof=1) # spread of the estimator
theory_se = np.sqrt(per_shot_var / Ms)
print(f"\n{'M':>7} {'empirical SE':>14} {'theory SE':>12} {'SE*sqrt(M)':>12}")
for M, e, t in zip(Ms, emp_se, theory_se):
print(f"{M:>7} {e:>14.5f} {t:>12.5f} {e*np.sqrt(M):>12.5f}")
# The last column ~ sqrt(per_shot_var) = sqrt(0.84) ~ 0.9165 for every M,
# confirming SE ∝ 1/sqrt(M).
print(f"\nsqrt(per-shot var) = {np.sqrt(per_shot_var):.5f} (the 1/sqrt(M) constant)")Plot description. Plot emp_se against Ms on log–log axes: the points fall on a straight
line of slope , the signature of decay. Overlaying theory_se gives a line
the empirical points sit on. (To render: plt.loglog(Ms, emp_se, 'o'); plt.loglog(Ms, theory_se, '-'); plt.xlabel("shots M"); plt.ylabel("standard error").) Equivalently, the rightmost column of
the table is flat at — error times is constant, which is the
law restated.
# Sanity-check the Hoeffding shot count from Example 2.
def hoeffding_shots(eps, delta, R=2.0):
return (R**2) / (2 * eps**2) * np.log(2 / delta)
print(f"\nShots for eps=0.02, delta=0.05 (95% conf): {hoeffding_shots(0.02, 0.05):.0f}")
print(f"Shots for eps=0.01, delta=0.01 (99% conf): {hoeffding_shots(0.01, 0.01):.0f}")Expected output (abridged; reproducible under the seed):
true <Z> = 0.4000
M estimate |error| SE = sqrt(var/M)
10 0.0000 0.4000 0.28983
100 0.4600 0.0600 0.09165
1000 0.3900 0.0100 0.02898
10000 0.4080 0.0080 0.00917
100000 0.3977 0.0023 0.00290
1000000 0.4005 0.0005 0.00092
M empirical SE theory SE SE*sqrt(M)
16 0.22689 0.22913 0.90756
64 0.11403 0.11456 0.91227
256 0.05776 0.05728 0.92421
1024 0.02923 0.02864 0.93545
4096 0.01445 0.01432 0.92453
16384 0.00692 0.00716 0.88535
sqrt(per-shot var) = 0.91652 (the 1/sqrt(M) constant)
Shots for eps=0.02, delta=0.05 (95% conf): 18444
Shots for eps=0.01, delta=0.01 (99% conf): 105966This is the simulated version of running a circuit with shots=M on Braket and computing an
expectation value from the counts — the convergence you see here is the convergence you pay for there.
Exercises
1. (Easy) Mean and variance of a die. Let be the result of a fair six-sided die. Compute and .
Solution
. . .
2. (Easy) Binomial via linearity. A circuit is run times; each shot reads with probability independently. Let be the number of s. Give and without summing any binomial coefficients.
Solution
with independent. By linearity $\mathbb E[K] = np = 300\mathrm{Var}(K) = np(1-p) = 1000(0.3)(0.7) = 210\sigma_K = \sqrt{210}\approx 14.5$.
3. (Medium) Geometric mean. Shots are repeated until the first appears; each shot is with probability . Let be the shot index of the first . Show .
Solution
Geometric with . Let . Then
using $\sum_{k\ge1} k q^{k-1} = \frac{d}{dq}\sum_{k\ge0}q^k = \frac{d}{dq}\frac{1}{1-q} = \frac{1}{(1-q)^2}|q|<1p1/p$ shots on average — e.g. amplitude needs repetitions, the intuition behind why Grover's is a real speedup over the classical .
4. (Medium) Chebyshev vs. Hoeffding shot counts. You estimate the mean of a -bounded reading to within with failure probability . (a) Use Chebyshev with the worst-case variance for a variable to bound . (b) Use Hoeffding (). Compare.
Solution
(a) Worst-case variance of a variable is (Bernoulli at ). For the sample mean, . Chebyshev: gives . (b) Hoeffding with : $M \ge \frac{R^2}{2\varepsilon^2}\ln\frac{2}{\delta} = \frac{1}{2(0.0025)}\ln(40) = 200\times3.689 \approx 738$. Hoeffding needs vs. Chebyshev's — for bounded variables the exponential bound is much tighter (here fewer shots). Chebyshev wins only when you can't bound the range.
5. (Hard) Variance reduction by negation/antithetic pairing. Suppose you can sample a reading and also its "mirror" with the same mean but . Show the average has variance strictly less than , and explain why negatively correlated samples beat independent ones for fixed shot count.
Solution
With and ,
If this is , which is what independent pairs would give (). Negatively correlated samples cancel each other's fluctuations, so you reach a target precision in fewer total samples. This is the principle behind antithetic variates and, in quantum estimation, behind clever measurement groupings that lower the effective shot count for a fixed precision.
6. (Hard) CLT confidence interval coverage. Simulate (in NumPy) the estimation of $\langle Z\ranglep_0 = 0.6M = 50010{,}000$ times. For each repetition form the CLT interval (using the sample std ). What fraction of intervals contain the true ? Should it be near ?
Solution
import numpy as np
rng = np.random.default_rng(7)
p0, M, reps = 0.6, 500, 10_000
true_Z = 2*p0 - 1 # = 0.2
covered = 0
for _ in range(reps):
x = np.where(rng.random(M) < p0, 1.0, -1.0)
xbar, s = x.mean(), x.std(ddof=1)
half = 1.96 * s / np.sqrt(M)
if xbar - half <= true_Z <= xbar + half:
covered += 1
print(covered / reps) # ~0.95The coverage is close to because, by the CLT, is approximately at , and the band of a Gaussian captures of its mass. Slight under-coverage can appear because we plug in the estimated ; for small a Student- critical value would be more honest, but at the difference is negligible. This is exactly how you'd report error bars on a measured expectation value.
Checkpoint
- State linearity of expectation. Does it require independence? What about additivity of variance?
- Write the standard error of a sample mean of i.i.d. samples, and explain in one sentence why halving the error costs the shots.
- For a Pauli reading, what is the per-shot variance in terms of , and which state maximizes it?
- Contrast what the LLN and the CLT each tell you about .
- When is Hoeffding's bound preferable to Chebyshev's, and why is it so much tighter there?
- Give the Hoeffding shot count to reach precision with confidence for a observable.
Answers
- , for any — no independence needed. Additivity of variance, , does require the terms to be uncorrelated (independence suffices); otherwise covariance terms appear.
- . Error , so to cut it in half you need times as many samples.
- , maximized () at , i.e. the equal-superposition state .
- LLN: (the estimate converges to the truth). CLT: the fluctuations of $\bar X_M\mu\sigma/\sqrt M$ — it shapes the error bars.
- When the variables are bounded. Hoeffding then gives an exponential (in ) tail bound vs. Chebyshev's merely polynomial , so it needs far fewer samples for a target . Chebyshev only needs finite variance, so it wins for unbounded variables.
- with , i.e. .
Further Reading
- [CT, §2.1, 3.1] Cover & Thomas — expectation, AEP, and the LLN as a warm-up to entropy.
- [NC, §2.2.5–2.2.6, Box 2.1] Nielsen & Chuang — expectation values of observables and measurement statistics.
- [Pre, Ch. 10] Preskill — sampling, estimation, and the role of shot noise in quantum experiments.
- Hoeffding's original: W. Hoeffding, "Probability inequalities for sums of bounded random variables", J. Amer. Statist. Assoc. 58 (1963) — the source of the concentration bound used here.
← Prev: Probability Spaces · Up: Term 0 · Next: Classical Information Theory →