Mathematical Foundations

IV.12 · Probability

How much probability-weighted spread remains after removing the center?

Square each distance from the mean, weight its contribution, and add. Shift and scale the same distribution to separate location from spread.

Measure spread around the expectation

The original population and its balance point
The original population and its balance pointDashed marker at expectation 0.5. Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The theoretical variance is 4.75. Scaling by 1 changes it by a²; shifting by 0 changes location and leaves spread unchanged.1-2: approximately 0.250: approximately 0.54: approximately 0.25-204

X values · bar height is probability mass · dashed line is E[X]

Outcome 1
Area = 6.25
Weighted area = 1.5625
Outcome 2
Area = 0.25
Weighted area = 0.125
Outcome 3
Area = 12.25
Weighted area = 3.0625
Exact distances and weighted squared contributions
xpx − μp·(x − μ)²
−20.25−2.51.5625
00.5−0.50.125
40.253.53.0625

Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The theoretical variance is 4.75. Scaling by 1 changes it by a²; shifting by 0 changes location and leaves spread unchanged.

Population expectation
0.5
Second moment
5
Population variance
4.75
Standard deviation
√19/22.179449…
Transformed expectation
0.5
Transformed variance
4.75

= exact model quantity · ≈ numerical companion or observed estimate

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from −3 to 3, up to 2 decimal places

from −4 to 4, up to 2 decimal places

The theoretical variance is 4.75. Scaling by 1 changes it by a²; shifting by 0 changes location and leaves spread unchanged.
E[X]=∑ipixi=0.5E[X]=\sum_i p_ix_i=0.5
Var⁡(X)=∑ipi(xi−μ)2=4.75\operatorname{Var}(X)=\sum_i p_i(x_i-\mu)^2=4.75
E[aX+b]=aE[X]+b=0.5,Var⁡(aX+b)=a2Var⁡(X)=4.75E[aX+b]=aE[X]+b=0.5,\quad\operatorname{Var}(aX+b)=a^2\operatorname{Var}(X)=4.75

Assign population probability mass

Weights divide by their positive total; these are theoretical probabilities, not sample estimates.

∑ipi=1\sum_i p_i=1
Outcome 1: X = −2= 0.25
Outcome 2: X = 0= 0.5
Outcome 3: X = 4= 0.25

Inspect values [−2, 0, 4] with weights [1, 2, 1]. Compare squared distances from mean 1/2 and their weighted contributions to variance 19/4.

Predict which value contributes the largest weighted squared distance. Shift the distribution and decide which table columns should change and which should stay fixed.

Intuition: location does not specify spread

Two distributions can share a mean and have different spreads. A constant at 22 and a fair choice between 00 and 44 both have mean 22, but only the latter varies. We need a quantity that measures distance from the center rather than distance from zero.

Signed distances average to zero: negative deviations cancel positive ones. Squaring makes every distance contribution nonnegative and gives larger deviations greater influence. Weighting those squares by probability produces the variance; taking its nonnegative square root returns a spread in the original units.

Definition

Write μ=E[X]\mu=\mathbb E[X]. The variance and standard deviation are

Var⁡(X)=E[(X−μ)2]=∑ipi(xi−μ)2,σ=Var⁡(X).\operatorname{Var}(X)=\mathbb E[(X-\mu)^2] =\sum_i p_i(x_i-\mu)^2, \qquad \sigma=\sqrt{\operatorname{Var}(X)}.

Variance is nonnegative. In a finite model it is zero precisely when every positive-mass value equals the mean; arbitrary zero-mass labels do not change it. If XX has units of milliseconds, variance has units of milliseconds squared, while standard deviation has units of milliseconds.

Finite models have finite moments. More generally, finite second moment guarantees a finite first moment and variance; distributions without a finite second moment require a separate discussion of infinite or undefined quantities.

Mechanics: compare distances on one scale

The canonical values are [−2,0,4][-2,0,4] with raw weights [1,2,1][1,2,1], affine scale 11, and shift 00. Read the table’s mass, signed distance from the mean, and weighted squared contribution. The square drawings compare squared distances on one common length scale; the table shows how probability weights alter their contributions.

Use Shift by 2 and Scale by −2 to inspect a companion affine variable in the transformed expectation and variance rows. The plot, squares, and contribution table describe the original XX, enabling comparison with the transformation. Zero variance changes the source values themselves to 22. Reset restores the canonical model. Negative weights or an all-zero total are invalid, whereas zero spread is a valid state.

Derivation: the second-moment identity and affine law

Expand the centered square and use linearity:

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

For Z=aX+bZ=aX+b, its mean is aμ+ba\mu+b, so Z−E[Z]=a(X−μ)Z-\mathbb E[Z]=a(X-\mu). Squaring gives

Var⁡(aX+b)=a2Var⁡(X),σaX+b=∣a∣σX.\operatorname{Var}(aX+b)=a^2\operatorname{Var}(X), \qquad \sigma_{aX+b}=|a|\sigma_X.

A shift changes location and leaves spread unchanged. A negative scale reverses the number line but cannot make variance or standard deviation negative. With scale zero, all values collapse to the shift and the spread is zero.

Worked examples

For the canonical model, μ=1/2\mu=1/2 and E[X2]=5\mathbb E[X^2]=5. The signed deviations are −5/2,−1/2,7/2-5/2,-1/2,7/2, whose squared values are 25/4,1/4,49/425/4,1/4,49/4. Weighting them gives

Var⁡(X)=14254+1214+14494=2516+216+4916=194=5−(12)2.\operatorname{Var}(X)=\frac14\frac{25}4+\frac12\frac14+\frac14\frac{49}4 =\frac{25}{16}+\frac2{16}+\frac{49}{16} =\frac{19}4=5-\left(\frac12\right)^2.

Thus σ=19/2≈2.17944947177\sigma=\sqrt{19}/2\approx2.17944947177. The value 44 contributes the largest weighted square, 49/1649/16, even though its mass is only 1/41/4.

Worked example: Measure spread around the expectation

The original population and its balance point
The original population and its balance pointDashed marker at expectation 0.5. Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The theoretical variance is 4.75. Scaling by 1 changes it by a²; shifting by 0 changes location and leaves spread unchanged.1-2: approximately 0.250: approximately 0.54: approximately 0.25-204

X values · bar height is probability mass · dashed line is E[X]

Outcome 1
Area = 6.25
Weighted area = 1.5625
Outcome 2
Area = 0.25
Weighted area = 0.125
Outcome 3
Area = 12.25
Weighted area = 3.0625
Exact distances and weighted squared contributions
xpx − μp·(x − μ)²
−20.25−2.51.5625
00.5−0.50.125
40.253.53.0625

Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The theoretical variance is 4.75. Scaling by 1 changes it by a²; shifting by 0 changes location and leaves spread unchanged.

Population expectation
0.5
Second moment
5
Population variance
4.75
Standard deviation
√19/22.179449…
Transformed expectation
0.5
Transformed variance
4.75

= exact model quantity · ≈ numerical companion or observed estimate

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from −3 to 3, up to 2 decimal places

from −4 to 4, up to 2 decimal places

The theoretical variance is 4.75. Scaling by 1 changes it by a²; shifting by 0 changes location and leaves spread unchanged.
E[X]=∑ipixi=0.5E[X]=\sum_i p_ix_i=0.5
Var⁡(X)=∑ipi(xi−μ)2=4.75\operatorname{Var}(X)=\sum_i p_i(x_i-\mu)^2=4.75
E[aX+b]=aE[X]+b=0.5,Var⁡(aX+b)=a2Var⁡(X)=4.75E[aX+b]=aE[X]+b=0.5,\quad\operatorname{Var}(aX+b)=a^2\operatorname{Var}(X)=4.75

Assign population probability mass

Weights divide by their positive total; these are theoretical probabilities, not sample estimates.

∑ipi=1\sum_i p_i=1
Outcome 1: X = −2= 0.25
Outcome 2: X = 0= 0.5
Outcome 3: X = 4= 0.25

Recover source variance 19/4 from the weighted square contributions. Compare transformed variance after shift +2 or scale −2 in the inspector.

Shifting by 22 changes the mean to 5/25/2 and preserves variance 19/419/4. Scaling by −2-2 gives mean −1-1, variance 1919, and standard deviation 19\sqrt{19}. Collapsing all values to 22 gives mean 22, second moment 44, and variance 00.

Executable reference code

The exact program calculates both centered weighted squares and the second-moment identity using Fraction, asserting that they agree. It verifies literal canonical values and sweeps affine scales and shifts, including collapse and reflection. The square root is reported approximately because 19/2\sqrt{19}/2 is irrational.

The NumPy program exposes a normalized probability vector, a center, and the dot product of centered squared distances. Its large-offset check demonstrates why centered squares are preferable to subtracting nearly equal floating-point moments. These are theoretical distribution calculations, not sample-variance estimates.

code/python/probability_variance.py
"""Exact theoretical variance by centered squares and the moment identity."""
from fractions import Fraction as F
from math import sqrt


def moments(values, weights):
    if not values or len(values) != len(weights):
        raise ValueError("Require matching nonempty values and weights")
    if any(not isinstance(x, (int, F)) or isinstance(x, bool) for x in (*values, *weights)):
        raise ValueError("Use integer or Fraction values and weights")
    total = sum(weights, F(0))
    if any(w < 0 for w in weights) or total <= 0:
        raise ValueError("Weights must be nonnegative with positive total")
    mean = sum((x*w for x, w in zip(values, weights)), F(0)) / total
    second = sum((x*x*w for x, w in zip(values, weights)), F(0)) / total
    variance = sum((w*(x-mean)**2 for x, w in zip(values, weights)), F(0)) / total
    assert variance == second - mean**2 >= 0
    return mean, second, variance


def main():
    x, w = [-2, 0, 4], [1, 2, 1]
    mean, second, variance = moments(x, w)
    assert (mean, second, variance) == (F(1, 2), F(5), F(19, 4))
    assert abs(sqrt(float(variance)) - 2.179449471770337) < 1e-14
    shifted = moments([v+2 for v in x], w)
    assert shifted[0] == F(5, 2) and shifted[2] == variance
    reflected = moments([-2*v for v in x], w)
    assert reflected[0] == -1 and reflected[2] == 19
    assert moments([2, 2, 2], w) == (F(2), F(4), F(0))
    for scale in (-2, 0, 1, 3):
        for shift in (-5, 0, 2):
            transformed = moments([scale*v + shift for v in x], w)
            assert transformed[0] == scale*mean + shift
            assert transformed[2] == scale**2 * variance
    assert moments([10**12 + v for v in x], w)[2] == variance
    assert moments([99, 2], [0, 1])[2] == 0
    for values, weights in (([], []), ([0], [0]), ([0, 1], [1, -1]), ([0, 1], [1]), ([float('nan')], [1])):
        try:
            moments(values, weights)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid exact weighted model accepted")
    print("E[X] =", mean, "E[X²] =", second, "Var(X) =", variance)
    print("σ = √19/2 ≈", sqrt(float(variance)))
    print("Shift +2: same variance; scale -2: variance 19; collapsed X=2: variance 0")


if __name__ == "__main__":
    main()
code/python/probability_variance_numpy.py
"""A centered weighted variance; raw weights describe a model, not a sample."""
import numpy as np


def moments(values, weights):
    x, w = np.asarray(values, dtype=float), np.asarray(weights, dtype=float)
    if x.ndim != 1 or x.size == 0 or w.shape != x.shape or not np.all(np.isfinite(x)):
        raise ValueError("Require finite nonempty values and matching weights")
    if not np.all(np.isfinite(w)) or np.any(w < 0) or not np.isfinite(w.sum()) or w.sum() <= 0:
        raise ValueError("Require nonnegative finite weights with positive finite total")
    p = w / w.sum()
    mean = np.dot(p, x)
    second = np.dot(p, x*x)
    centered = x - mean
    variance = np.dot(p, centered*centered)
    return float(mean), float(second), float(variance), float(np.sqrt(variance))


def main():
    x, w = np.array([-2., 0., 4.]), np.array([1., 2., 1.])
    mean, second, variance, sigma = moments(x, w)
    np.testing.assert_allclose([mean, second, variance, sigma], [0.5, 5, 4.75, 2.179449471770337], rtol=0, atol=1e-12)
    assert moments(x+2, w)[0] == 2.5 and moments(x+2, w)[2] == 4.75
    assert moments(-2*x, w)[2] == 19
    assert moments(np.full(3, 2.), w) == (2., 4., 0., 0.)
    for scale in (-2, 0, 1, 3):
        for shift in (-5, 0, 2):
            transformed = moments(scale*x + shift, w)
            np.testing.assert_allclose([transformed[0], transformed[2], transformed[3]], [scale*mean + shift, scale**2*variance, abs(scale)*sigma], rtol=0, atol=1e-12)
    assert moments(10**12 + x, w)[2] == 4.75
    assert moments([99, 2], [0, 1])[2] == 0
    for values, weights in (([], []), ([0], [0]), ([0, 1], [1, -1]), ([np.nan], [1]), ([0], [np.inf])):
        try:
            moments(values, weights)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid weighted model accepted")
    print("Weighted theoretical moments ≈", (mean, second, variance, sigma))
    print("For an observed sample only, np.var(sample, ddof=1) uses m-1 for m>1.")
    print("Centered squares avoid subtracting two large, nearly equal moments.")


if __name__ == "__main__":
    main()

Explore

Before choosing Shift by 2, predict the transformed mean and variance. Before choosing Scale by −2, predict transformed mean −1-1 and variance 1919, then check the transformed inspector rows. On paper, reconstruct that variable’s doubled deviation magnitudes, quadrupled squared distances, and doubled standard deviation from the original table.

Choose Zero variance and explain why a nonzero mean does not imply nonzero spread. Reset and increase an outer value’s weight or move it farther from the center. Track how the mean itself moves; computing deviations from the old mean would answer a different question.

Common mistakes and counterexamples

The second moment measures squares about zero, while variance measures squares about the mean. For a constant X=2X=2, E[X2]=4\mathbb E[X^2]=4 but variance is zero. Adding a constant also does not add its square to the variance: centering removes the same shift from every value.

Standard deviation is the nonnegative square root, not half the variance. For the canonical model it is 19/2\sqrt{19}/2, not 19/219/2. A negative affine scale uses a2a^2 for variance and ∣a∣|a| for standard deviation.

Numerical considerations

The exact identity E[X2]−μ2\mathbb E[X^2]-\mu^2 is convenient algebraically. With large offsets and small spread, floating-point subtraction can lose significant digits or produce a tiny negative result. Centered weighted squares avoid that particular subtraction. Extremely large values can still overflow floating-point squares; finite input alone does not guarantee a representable second moment.

The stage uses a specified theoretical model, so normalize its raw weights by their total. For m>1m>1 independent identically distributed observed samples with an unknown mean, the usual unbiased sample variance estimator is

s2=1m−1∑j=1m(xj−xˉ)2.s^2=\frac{1}{m-1}\sum_{j=1}^m(x_j-\bar x)^2.

This correction concerns estimation from observations, not the number of support labels or the raw model weight total. With one sample, that estimator is undefined. NumPy’s default var uses ddof=0; ddof=1 selects the usual sample denominator when its assumptions apply. Even then, the square root is not generally an unbiased estimator of population standard deviation.

Engineering and ML connections

Standardizing a feature uses its center and a positive spread scale. A zero-variance feature cannot be divided by its standard deviation and needs an explicit handling rule. Measurement-unit changes explain the squared scale law: converting milliseconds to seconds rescales variance by the conversion factor squared. Estimated data statistics and theoretical model moments should be labeled separately.

Exercises

Use exact rational variance answers. The choices test square-root units and the distinction between a model and an estimator.

calculation

Subtract the square of the mean

X has values [−2, 0, 4], weights [1, 2, 1], E[X] = 1/2 and E[X²] = 5. Give Var(X).

prediction

Square a negative scale

For that X, give Var(−2X) and Var(2), where the second variable is the constant 2.

calculation

Move the center without changing spread

Shift the canonical X by +2. Give E[X + 2] and Var(X + 2).

explanation

Take the positive root and restore units

If X is measured in milliseconds and Var(X) = 19/4, which statement is correct?

Choose one answer

explanation

Separate a distribution from an estimator

Known probabilities define a theoretical variance. Four observed samples are used to estimate an unknown population variance. Which denominator rule is justified?

Choose one answer

Summary and checkpoints

Variance is the probability-weighted squared distance from the mean; standard deviation is its nonnegative square root. Check that you can recover 19/419/4 and 19/2\sqrt{19}/2, preserve spread under a shift, square the affine scale, explain collapse, and keep theoretical moments distinct from sample estimates.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available