Mathematical Foundations

IV.5 · Probability

Does knowing B change the chance of A?

Compare joint mass with the product of the two marginal masses. Independent events may overlap; mutually exclusive positive-mass events cannot be independent.

Test the product condition

HHOriginal P = 0.25
HTOriginal P = 0.25
THOriginal P = 0.25
TTOriginal P = 0.25
HH= 0.25
HT= 0.25
TH= 0.25
TT= 0.25

Sample space: HH, HT, TH, TT. Equal weights explicitly assume equiprobable outcomes. A = {HH, HT}; B = {HH, TH}. Independent: P(A∩B) = P(A)P(B). The sets overlap. Disjointness and independence answer different questions.

Total probability
1
Event A
0.5
Event B
0.5
Intersection
0.25
Product for comparison
0.25

= exact model quantity · ≈ numerical companion or observed estimate

from 0 to 100, whole numbers only

Independent: P(A∩B) = P(A)P(B). The sets overlap. Disjointness and independence answer different questions.
P(A)=∑ω∈Apω=0.5P(A)=\sum_{\omega\in A}p_\omega=0.5
P(A∩B)=0.25=P(A)P(B)=0.25P(A\cap B)=0.25\quad=\quad P(A)P(B)=0.25

Start with total mass one

Equal weights explicitly assume equiprobable outcomes.

∑ωpω=1\sum_\omega p_\omega=1
HH= 0.25
HT= 0.25
TH= 0.25
TT= 0.25

Change memberships of A and B, then compare P(A ∩ B) with P(A)P(B). Try overlapping and disjoint selections and inspect whether the exact equality holds.

The opening model uses Two fair coins: A means first coin H, and B means second coin H. Compare the joint mass 1/41/4 with the marginal product. Then choose Fair die for the even faces and top three faces. Both still have mass 1/21/2: predict whether that fact alone makes them independent, then inspect the changed shared mass.

Intuition: compare information, not diagram separation

If learning that B happened leaves the chance of A unchanged, the events provide no probability update about each other. This can happen even though they share outcomes. Two independent fair coins illustrate it: knowing the second coin is heads leaves the first coin’s chance of heads at 1/21/2.

By contrast, mutually exclusive events forbid each other. Knowing a die roll is odd makes its chance of being even zero. Their drawn regions may be separate, but that separation encodes strong information.

Definition

Events A and B are independent exactly when

P(A∩B)=P(A)P(B).P(A\cap B)=P(A)P(B).

The probabilities of A and B alone are their marginal masses; the intersection is their joint mass. If P(B)>0P(B)>0, the product equality is equivalent to P(A∣B)=P(A)P(A\mid B)=P(A). If P(A)>0P(A)>0, it is also equivalent to P(B∣A)=P(B)P(B\mid A)=P(B).

The product definition includes zero-mass cases without division. Independence of two events is a statement about those events under a specified model. It does not imply that every pair of events in the same experiment is independent.

Mechanics: test the equality from one model

The stage sums original weights for A, B, and their intersection. Its comparison uses these derived masses. Change membership and read the joint term and product separately before looking at the classification. Equal-sized event drawings alone cannot determine it.

Replay the trace: collect marginal weights, collect shared weights, multiply the marginals, and compare. Where a conditioning mass is positive, relate the result to the conditional inspector. Where it is zero, use the product comparison and keep the corresponding conditional probability undefined.

Derivation: the conditional equivalence

With positive B mass,

P(A∣B)=P(A)⟺P(A∩B)P(B)=P(A)⟺P(A∩B)=P(A)P(B).P(A\mid B)=P(A) \quad\Longleftrightarrow\quad \frac{P(A\cap B)}{P(B)}=P(A) \quad\Longleftrightarrow\quad P(A\cap B)=P(A)P(B).

The last condition is symmetric even though the original conditional expression is directional. Independence also extends to complements: subtract the joint mass from P(A)P(A) to obtain

P(A∩Bc)=P(A)−P(A∩B)=P(A)(1−P(B))=P(A)P(Bc).P(A\cap B^c)=P(A)-P(A\cap B) =P(A)(1-P(B))=P(A)P(B^c).

For disjoint events with positive marginals, joint mass is zero and the product is positive, so equality fails. If one marginal is zero, its intersection is a subset of a zero-mass event and also has zero mass; equality then holds.

Worked examples

For the canonical fair die, A={2,4,6}A=\{2,4,6\} and B={4,5,6}B=\{4,5,6\}. The joint mass is 1/31/3, while the product is (1/2)(1/2)=1/4(1/2)(1/2)=1/4. They are dependent; indeed P(A∣B)=2/3≠1/2P(A\mid B)=2/3\ne1/2.

Worked example: Test the product condition

HHOriginal P = 0.25
HTOriginal P = 0.25
THOriginal P = 0.25
TTOriginal P = 0.25
HH= 0.25
HT= 0.25
TH= 0.25
TT= 0.25

Sample space: HH, HT, TH, TT. Equal weights explicitly assume equiprobable outcomes. A = {HH, HT}; B = {HH, TH}. Independent: P(A∩B) = P(A)P(B). The sets overlap. Disjointness and independence answer different questions.

Total probability
1
Event A
0.5
Event B
0.5
Intersection
0.25
Product for comparison
0.25

= exact model quantity · ≈ numerical companion or observed estimate

from 0 to 100, whole numbers only

Independent: P(A∩B) = P(A)P(B). The sets overlap. Disjointness and independence answer different questions.
P(A)=∑ω∈Apω=0.5P(A)=\sum_{\omega\in A}p_\omega=0.5
P(A∩B)=0.25=P(A)P(B)=0.25P(A\cap B)=0.25\quad=\quad P(A)P(B)=0.25

Start with total mass one

Equal weights explicitly assume equiprobable outcomes.

∑ωpω=1\sum_\omega p_\omega=1
HH= 0.25
HT= 0.25
TH= 0.25
TT= 0.25

Choose Fair die in this worked explorer, then manipulate A and B and follow the joint-product comparison. Restore the even faces and top three faces to verify 1/3 ≠ 1/4; switch to Two fair coins to compare the independent events.

For two independent fair coins, Ω={HH,HT,TH,TT}\Omega=\{HH,HT,TH,TT\} with masses 1/41/4. Let A mean first coin H and B mean second coin H. Then A={HH,HT}A=\{HH,HT\}, B={HH,TH}B=\{HH,TH\}, and A∩B={HH}A\cap B=\{HH\}. The joint mass 1/41/4 equals the marginal product. Given B, HHHH and THTH remain equally weighted, so the first coin still has heads probability 1/21/2.

For a counterexample within the same coin model, let C mean “both coins H.” Then P(C∣A)=1/2P(C\mid A)=1/2 but P(C)=1/4P(C)=1/4. Independent component tosses do not make arbitrary derived events independent.

Executable reference code

Python checks the exact product definition by summing Fraction weights over sets. It verifies the dependent die, independent coin events, mutually exclusive positive events, and a zero-mass event with undefined reverse conditioning. NumPy computes the same small event masses with masks and prints the numerical joint-minus-product difference; exact fractions remain the reference for classification.

code/python/probability_independence.py
"""Exact independence tests include zero-mass events without dividing by zero."""
from fractions import Fraction as F


def compare(weights, a, b):
    if not weights or any(not isinstance(p, F) or p < 0 for p in weights.values()):
        raise ValueError("Use a nonempty model of nonnegative Fraction masses")
    if sum(weights.values(), F(0)) != 1:
        raise ValueError("Masses must sum exactly to one")
    a, b = set(a), set(b)
    if not (a | b) <= weights.keys():
        raise ValueError("Events must be inside the sample space")
    pa = sum((weights[x] for x in a), F(0))
    pb = sum((weights[x] for x in b), F(0))
    joint = sum((weights[x] for x in a & b), F(0))
    return {"P(A)": pa, "P(B)": pb, "joint": joint, "product": pa * pb,
            "independent": joint == pa * pb,
            "P(A|B)": joint / pb if pb else None,
            "P(B|A)": joint / pa if pa else None}


def main():
    die = {face: F(1, 6) for face in range(1, 7)}
    a, b = {2, 4, 6}, {4, 5, 6}
    dependent = compare(die, a, b)
    assert dependent["joint"] == F(1, 3)
    assert dependent["product"] == F(1, 4)
    assert dependent["P(A|B)"] == F(2, 3)
    assert not dependent["independent"]
    coins = {outcome: F(1, 4) for outcome in ("HH", "HT", "TH", "TT")}
    first_h, second_h = {"HH", "HT"}, {"HH", "TH"}
    independent = compare(coins, first_h, second_h)
    assert independent["joint"] == independent["product"] == F(1, 4)
    assert independent["P(A|B)"] == F(1, 2) and independent["independent"]
    assert not compare(die, a, set(die) - a)["independent"]
    assert compare(die, a, set())["independent"]
    zero = compare(die, set(), b)
    assert zero["independent"] and zero["P(A|B)"] == 0 and zero["P(B|A)"] is None
    zero_label = {"x": F(1, 2), "y": F(1, 2), "z": F(0)}
    assert compare(zero_label, {"z"}, {"x"})["independent"]
    assert compare(die, a, set(die))["independent"]
    assert not compare(coins, first_h, {"HH"})["independent"]
    cells = (F(1, 6), F(1, 6), F(1, 3), F(1, 3))
    assert sum(cells) == 1 and cells[0] + cells[1] == F(1, 3)
    assert cells[0] + cells[2] == F(1, 2)
    # Pairwise independence does not force the triple product rule.
    matches = {"HH", "TT"}
    assert compare(coins, first_h, matches)["independent"]
    assert compare(coins, second_h, matches)["independent"]
    triple = sum((coins[x] for x in first_h & second_h & matches), F(0))
    assert triple == F(1, 4) != F(1, 8)
    for weights, event in ((die, {7}), ({}, set()),
                           ({1: F(-1), 2: F(2)}, {1}), ({1: F(1, 2)}, {1})):
        try:
            compare(weights, event, set())
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid model or event was accepted")
    print("Dependent fair-die events:", dependent)
    print("Independent fair-coin positions:", independent)
    print("Zero event: product definition holds; reverse conditioning is undefined:", zero)
    print("Pairwise coin events: triple mass 1/4, product 1/8 (not mutually independent)")


if __name__ == "__main__":
    main()
code/python/probability_independence_numpy.py
"""Numerical joint-product comparisons are cross-checks, not exact proofs.

The literal Fraction joint and product supply the mathematical classification.
Absolute error tolerance 1e-12, relative tolerance 0, checks these small arrays.
"""
from fractions import Fraction as F
import numpy as np

ATOL = 1e-12


def compare(weights, a, b):
    p = np.asarray(weights, dtype=float)
    a, b = np.asarray(a), np.asarray(b)
    if p.ndim != 1 or p.size == 0 or np.any(p < 0) or not np.all(np.isfinite(p)):
        raise ValueError("Use a nonempty finite nonnegative mass vector")
    if not np.isclose(p.sum(), 1.0, rtol=0, atol=ATOL):
        raise ValueError("Masses must sum to one within floating-point tolerance")
    if a.dtype != np.bool_ or b.dtype != np.bool_ or a.shape != p.shape or b.shape != p.shape:
        raise ValueError("Events need boolean masks matching the mass vector")
    pa, pb, joint = p[a].sum(), p[b].sum(), p[a & b].sum()
    return np.array([pa, pb, joint, pa * pb]), joint / pb if pb > 0 else None


def check_example(weights, a, b, exact, independent):
    masses, conditional = compare(weights, a, b)
    np.testing.assert_allclose(masses, [float(x) for x in exact], rtol=0, atol=ATOL)
    assert (exact[2] == exact[3]) == independent
    if independent:
        np.testing.assert_allclose(masses[2], masses[3], rtol=0, atol=ATOL)
    print("Marginals, joint, product ≈", masses, "; numerical gap ≈", masses[2] - masses[3])
    print("Exact joint/product:", exact[2], exact[3], "; independent:", independent)
    return conditional


def main():
    faces = np.arange(1, 7)
    p = np.full(6, 1 / 6)
    a, b = np.isin(faces, [2, 4, 6]), np.isin(faces, [4, 5, 6])
    die_conditional = check_example(p, a, b, [F(1, 2), F(1, 2), F(1, 3), F(1, 4)], False)
    np.testing.assert_allclose(die_conditional, float(F(2, 3)), rtol=0, atol=ATOL)
    coins = np.array(["HH", "HT", "TH", "TT"])
    first_h, second_h = np.isin(coins, ["HH", "HT"]), np.isin(coins, ["HH", "TH"])
    coin_conditional = check_example(np.full(4, 0.25), first_h, second_h,
                                     [F(1, 2), F(1, 2), F(1, 4), F(1, 4)], True)
    np.testing.assert_allclose(coin_conditional, float(F(1, 2)), rtol=0, atol=ATOL)
    check_example(p, a, ~a, [F(1, 2), F(1, 2), F(0), F(1, 4)], False)
    undefined = check_example(p, a, np.zeros(6, dtype=bool), [F(1, 2), F(0), F(0), F(0)], True)
    assert undefined is None
    for bad_p, bad_a, bad_b in (([-0.1, 1.1], [True, False], [False, True]),
                                 ([0.5, 0.4], [True, False], [False, True]),
                                 ([np.nan], [True], [True]),
                                 ([1.0], [1], [True]), ([1.0], [True], [True, False])):
        try:
            compare(bad_p, bad_a, bad_b)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid model or masks were accepted")
    print("The zero event is independent; conditioning on it is undefined")


if __name__ == "__main__":
    main()

Explore

Choose Fair die, then make B the whole die space: the joint mass equals P(A)P(A) and the product equals P(A)×1P(A)\times1, so independence holds. Make B empty: both terms are zero, so independence again holds, while conditioning on B is undefined. Make A odd and B even: both marginal masses are 1/21/2, but the joint mass is zero and independence fails. Reset in this chapter restores the independent two-coin model.

Use the coin reference to inspect the four joint cells. For independent A and B with masses 1/31/3 and 1/21/2, the cells A-and-B, A-and-not-B, not-A-and-B, and neither have masses 1/6,1/6,1/3,1/31/6,1/6,1/3,1/3. Their row and column sums recover the marginals, and their total is one.

Common mistakes and counterexamples

Independence does not mean disjointness or equal probabilities. Events of mass zero are independent of every event under the product definition, yet conditioning on them remains undefined. An event is independent of itself only if its mass is zero or one, because p=p2p=p^2 then holds.

Do not infer independence from a short empirical run, apparent visual separation, or lack of an obvious causal link. Independence is a property of the specified joint probability model. Correlation, introduced later, summarizes a different feature of numerical variables and is not a general replacement for this definition.

Numerical considerations

The finite rational reference compares joint and product exactly. Decimal formatting cannot turn 1/31/3 into 1/41/4, and an exact small discrepancy remains dependence. NumPy’s absolute tolerance 10−1210^{-12} with zero relative tolerance is appropriate for cross-checking these small hand-worked values; an approximate equality test alone cannot prove exact independence of arbitrary floating-point or measured inputs.

If a larger numerical model reports “approximately independent,” it needs an explicit error and modeling policy. The stage’s exact entered model and uncertainty in a physical data source are separate issues. A sampling fluctuation also need not reflect a defect in a model that assumes independence.

Engineering and ML connections

Independent draws support many simulation and learning algorithms, but repeated use of the same observation, shared sources, or coordinated selection can create dependence. Naive Bayes later assumes certain features are independent conditional on a class, a stronger modeling choice than merely observing small correlations. Test the assumption against the intended joint structure rather than the visual layout of a dataset.

Exercises

calculation

Compare joint mass with a product

For the fair die A = {2, 4, 6}, B = {4, 5, 6}, give P(A ∩ B) and P(A)P(B).

calculation

Verify independent coin events

Two independent fair coins give HH, HT, TH, TT, each mass 1/4. A means first coin H; B means second coin H. Give P(A ∩ B) and P(A | B).

explanation

Compare mutually exclusive events

A and B are disjoint and each has positive probability. Can they be independent?

Choose one answer

explanation

Use the definition at zero mass

P(A) = 0 and P(B) = 1/2. What follows?

Choose one answer

construction

Construct the independent joint table

For independent A and B with P(A) = 1/3 and P(B) = 1/2, give masses of A∩B, A∩Bᶜ, Aᶜ∩B, Aᶜ∩Bᶜ.

Summary and checkpoints

Independence means joint mass equals the product of marginal masses. Check that you can verify the coin example, reject the die example, distinguish independence from mutual exclusion, and apply the zero-mass definition without inventing an undefined conditional ratio.

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