Measure theory I: σ-algebras and measures
Why probability cannot be assigned to every subset of [0,1] and the minimum structure required of events. Construct generated σ-algebras, the Borel σ-algebra, measures and Lebesgue measure via Carathéodory extension, using Dynkin’s π-λ theorem for uniqueness. Interpret a σ-algebra as available information from the outset.
After this lesson you can
- Use the Vitali set to explain why no translation-invariant measure exists on every subset of [0, 1).
- Determine whether a family of sets is an algebra, σ-algebra, π-system or λ-system, and describe the σ-algebra generated by a partition.
- Use the π-λ theorem to show measures agreeing on intervals agree on every Borel set.
- Describe the Carathéodory construction of Lebesgue measure and its null sets.
- Interpret nested σ-algebras as increasing information.
Before you start
Motivation: “choose at random” is incomplete
In the lesson on probability spaces you wrote and called “the family of events”. This lesson explains where that family comes from, why it cannot always be all of and the minimum structure it needs for the Kolmogorov axioms to make sense. There are three reasons, each illustrated by a concrete result.
First: without a measure there is no question. Draw a chord “at random” in a circle. What is the probability it exceeds the side of the inscribed equilateral triangle? Three perfectly reasonable chord-selection recipes give three different answers.
All three values are calculated by hand. A chord is long if its midpoint is from the center (the chord has length exactly when ). For the first recipe symmetry lets you fix one endpoint at a triangle vertex: the chord is long if the other falls in the opposite arc, one third of the circumference, giving . For the second, is uniform on and . In the third, the midpoint is uniform in the disk and probability is the area ratio . None of the calculations is wrong: these are three different probability measures on the same set of chords. The question has an answer only once the measure is fixed. (E. T. Jaynes argued in 1973 that if the answer must not depend on circle position or size, the radius recipe is uniquely consistent. This argues which measure is reasonable, not which is “the” correct one.)
Second: not every subset can have length. Assigning probability to every subset of in a way that makes “choose a uniform point” meaningful is impossible, as shown next.
Third: information. A system observing only part of the world can answer some questions and not others. That structure of “answerable questions” is exactly a σ-algebra, and increasing versions (filtrations) are the language of martingales, partially observable reinforcement learning and much of stochastic calculus.
An obstacle: the Vitali set
We want a “length” function defined on all subsets of with three properties one would accept for uniform sampling: countable additivity, translation invariance (addition modulo 1, to remain in the interval) and .
Proof
On define relation . It is an equivalence relation, and by the axiom of choice a set exists containing exactly one representative per class. For each rational let .
The are disjoint: if , then with , hence , i.e. , and since has one representative per class, and then . They cover everything: given , its representative satisfies , so with .
Since is countable (countability), (i), (ii) and (iii) give
A countable sum of copies of the same number is if that number is , and if positive. It is never .
∎Something must give. Measure theory gives up the one nonessential thing: domain. It retains countable additivity (without it limits do not work) and invariance, but abandons measurement of every subset, restricting to a family large enough for everything we will do and small enough that a measure exists. (Relax countable to finite additivity and invariant extensions to every subset of and do exist, but lose passage to limits; on even finite additivity and rigid-motion invariance clash: the Banach–Tarski paradox.)
σ-algebras
What must the family of sets we will measure satisfy? If is an event, “ does not occur” must also be one. If are events, “at least one occurs” must be one too, not just for finitely many, because we need “ever” and “for every ”. Those three requirements define it.
Immediate consequences: ; is closed under finite unions (pad with ), countable intersections (, by De Morgan) and differences (). In particular sets
are measurable if the are. This is the reason for “σ”: countable operations express “infinitely often”, “always from some point on” and “converges”.
Useful examples:
- , the trivial σ-algebra, and , the discrete one. Everything else lies between.
- for an : the smallest containing .
- With uncountable , countable sets or those with countable complement.
- With , finite or cofinite sets form an algebra but not a σ-algebra: singletons are finite and their countable union, the evens, is neither finite nor cofinite. This canonical counterexample shows why finite versus countable matters, and appears as an exercise.
Generated σ-algebra
A σ-algebra is rarely described element by element: give a family of “important” sets and take the smallest σ-algebra containing them. An elementary fact makes this work.
The proof is the first guided exercise. The intersected family is nonempty because always contains , and the definition is nonconstructive: it does not say how to obtain elements of . Adding complements and countable unions to once is not generally sufficient, nor even twice: iteration must continue transfinitely to the first uncountable ordinal. In practice one therefore reasons via the universal property (“smallest containing ”), never enumeration.
Finite partitions: the simplest σ-algebra
If is finite (or, more generally, the σ-algebra has finitely many elements), everything reduces to combinatorics. A partition of is a collection of nonempty pairwise disjoint subsets whose union is .
Proof
(a) Subfamily unions are distinct sets (because are disjoint and nonempty). They are closed under complements (the complement of a union of is the union of the others) and unions. (b) For let , a finite intersection, hence in . If then ; and since for the same reason (if , would be an element of containing and smaller than ), . Thus the form a partition, and each is the union of with .
∎Two points in one atom cannot be distinguished using events in : every event contains both or neither. This gives our course-wide interpretation.
σ-algebra as information
Imagine outcome has already occurred, but you observe only a function of it (first toss, number of heads, a sensor summary). After observation you know which atom contains , nothing more. Events for which you can say “occurred” or “did not occur” are exactly unions of atoms. A σ-algebra is the set of yes/no questions answered by the observation. Observing more splits atoms into finer pieces, enlarging the σ-algebra.
In the figure has 8 points. Observing the first toss generates a σ-algebra with 2 atoms and events; the first two, 4 atoms and events; all three, 8 atoms and events, all of . Observing only head count also gives 4 atoms (0, 1, 2 or 3 heads, with 1, 3, 3 and 1 outcomes) and 16 events, but not the same 16 as the first two tosses: “second is heads” belongs to one and not the other. The σ-algebras are incomparable. In contrast, those of the first tosses are comparable:
An increasing sequence of σ-algebras like this is a filtration: information that accumulates over time and is never forgotten. When studying filtrations, martingales and stopping times, use this picture; in a POMDP the policy can depend only on what fits in the observed-information σ-algebra.
For functions from to other spaces, “the σ-algebra generated by what I observe” is the concept of measurable function in the next lesson: a function is measurable with respect to a σ-algebra when knowing which events occurred suffices to determine its value (in the finite case, when it is constant on each atom).
The Borel σ-algebra
In we will not work with finite partitions. The desired σ-algebra must at least contain intervals (to discuss length) and everything obtained from them through countable operations.
It contains open sets, closed sets (open complements), countable sets (unions of points), (countable intersections of open sets, such as the irrational set ) and (countable unions of closed sets). Every naturally encountered set is Borel. The next result says we need not start from all open sets.
Proof
We show for ; the rest uses the same argument. () Each is closed, hence Borel. () Show every open set belongs to . First and . Now let be open. For every there is an interval with such that . Rational-endpoint intervals form a countable family (as many as rational pairs, countable), so is the countable union of rational intervals contained in and belongs to .
∎The proof rests on being countable and dense in , so every open set is a countable union of basic intervals. In topological language is separable (has a countable dense subset), and its topology therefore has a countable base; likewise in with rational-vertex boxes, which makes Borel σ-algebras on manageable. For the analogous result uses boxes , and equals product σ-algebra , encountered when constructing product measure.
A matter of size. has continuum cardinality (shown by the transfinite iteration above), while has elements. By Cantor’s diagonal, : almost all subsets of are not Borel, though none can be written explicitly. itself is too large to enumerate, so it is handled through generators.
Measures
With a σ-algebra we can discuss “size of a measurable set”.
In other words Kolmogorov’s axioms are the definition of measure plus . Examples: counting measure on any set (σ-finite if and only if is countable); Dirac delta ; combinations with , the discrete distributions; and Lebesgue measure in the next section, σ-finite but not finite on .
Proof
(1) and additivity. (3) Write with and : they are disjoint and , hence . (2) Apply (3) to , with finite subadditivity from (1) and . (4) The increase to ; by (3), , and by (1) this is (using finiteness of ).
∎Finiteness in (4) is not a technicality. With Lebesgue measure on and , yet for every : limit of measures is and measure of limit is . For probabilities, always finite, continuity holds both ways. The probability continuity lesson proved this for ; now it is a general fact. For finite measures a useful converse holds: a finitely additive set function continuous at (if , then ) is countably additive. If are disjoint and , then . The Kolmogorov axioms lesson showed this equivalence’s role, and it returns when constructing measures from distribution functions.
When two measures are the same: π-systems and λ-systems
Measures are rarely defined by values on every Borel set. Values are given on a small manageable family (intervals), and two questions arise: do those values determine the measure (uniqueness), and does a measure with those values exist (existence)? This section treats uniqueness using a set-theoretic lemma due to Dynkin.
A λ-system requires less than a σ-algebra: countable union only for increasing sequences and difference only for nested sets. It does not require intersections, the gap filled by a π-system.
Lemma. A family that is both a π-system and λ-system is a σ-algebra. Complements follow from (1) and (2) (); π-system intersections and De Morgan yield finite unions ; a countable union is the increasing limit of finite unions , in the family by (3).
The smallest example shows why intersection closure is key. Take and events and . A probability with is not determined: the uniform one and the one assigning mass to and agree on and but differ on , which is in . Adding intersection determines probability completely.
This is the π-λ theorem, a course-wide uniqueness tool: to prove a property throughout a σ-algebra, establish it on a generating π-system and show sets satisfying it form a λ-system.
Proof
Let be the intersection of all λ-systems containing ; it is a λ-system (the three properties pass to intersections, as for σ-algebras) and . It suffices to show is a π-system: by the lemma it is then a σ-algebra containing , so .
Step 1. Fix and let . It is a λ-system: because ; if belong to , is a difference of nested elements of ; and gives . Also because is a π-system. Therefore : for and .
Step 2. Fix and let . The same argument gives a λ-system, which contains by step 1. It therefore contains : the family is closed under intersections.
∎Proof
For each , let . It contains (because and they agree there), (because ), and is closed under differences of nested sets because measures of are finite and subtractable, and under increasing unions by continuity from below. It is a λ-system and by the π-λ theorem contains . For each , and, letting using continuity from below, .
∎The most-used consequence: a probability on is determined by its distribution function , since rays form a π-system () generating by the generator theorem. A guided exercise proves it step by step. For Lebesgue measure, intervals form a generating π-system and have finite length.
Existence: from length to Lebesgue measure
The inverse problem is construction: we want a measure on with . Uniqueness is established. For existence, assign values consistently to every Borel set; Carathéodory’s recipe measures “from outside”: approximate each set by interval covers, then find sets for which that approximation behaves additively.
Outer measure
Outer measure is defined on all subsets of , without contradicting Vitali because is not additive on all of them. What it does satisfy is summarized in three properties.
Proof
(a) is immediate. (b) If any there is nothing to prove. Otherwise fix and cover each with open intervals of total length below . Together they form a countable cover of of total length below . Since is arbitrary, (b) follows. This “geometric tip” is the most-used trick in the theory.
(c) Bound is immediate by covering with . For the other, it suffices to show that if then , then apply monotonicity to . By compactness (compactness of ), a finite subcover suffices. Order it as follows: take an interval containing ; if , is covered by another with ; continue until some . Since , .
∎Proof (b) contains nearly everything needed to see a surprising property of measure with your own eyes: a dense set can have outer measure zero.
Each rational is one point and fits in an arbitrarily short interval. Enumeration (available because is countable, here by increasing denominator: ) lets us reserve for an interval of length . Intervals are dense in the sense that every rational lies in one, but total length is . Thus for every , i.e. . An often surprising corollary: the complement of that open dense union is a closed set containing no rationals and having measure at least . It is a closed set without intervals (topologists call it nowhere dense) with almost full measure: topology and measure measure different things.
This differs from the length underlying the Riemann integral (Jordan content), which permits only finite covers. If finitely many intervals cover , the union of their closures is closed and contains a dense subset of , hence all , and total length is at least . With finite covers rationals “measure” from outside and from inside: they have no Jordan content, so the rational indicator (Dirichlet function) is not Riemann integrable. Moving from finite to countable covers is exactly Lebesgue’s addition, making that function’s integral .
Carathéodory’s theorem
is not generally additive; Carathéodory’s solution keeps sets on which it is.
Subadditivity already gives . The requirement is .
Proof
This is the Carathéodory extension theorem in outer-measure form; the full proof follows. and complement closure of are clear because the definition is symmetric in and .
Algebra. If and is arbitrary, use and then :
Since , subadditivity gives . Thus and . Also, if are disjoint, applying the definition of to set gives , and induction gives the same for disjoint sets.
Countable unions. Let be disjoint and . With , and since ,
Let and use countable subadditivity: . Thus , and yields : countable additivity. Any countable union becomes disjoint using , and is a σ-algebra.
Null sets. If , then by monotonicity.
∎For length we must check that contains Borel sets. It suffices to show rays are -measurable. Let with and cover it by open intervals of total length below . Intervals cover , cover , and lengths of the two pieces of sum to that of . By outer-measure property (c) for an interval (even if not open) and subadditivity, . Since is arbitrary, the condition holds. Thus .
Uniqueness has free consequences. Measure also equals on , so agrees with : Lebesgue measure is translation invariant. Likewise, for , measure agrees with on intervals, hence . By Vitali the earlier set is not measurable: . On proceed likewise with boxes and volume .
The general mechanism uses nothing specific to except that length, measured on finite unions of intervals , is countably additive (exactly what the compactness argument in (c) guarantees). This is the usual statement.
Existence is built with and the proof above; uniqueness follows from the π-λ theorem (an algebra is a π-system). This constructs Lebesgue–Stieltjes measure associated with a distribution function and, in the product-measure lesson, measure on and the law of infinite sequences of random variables. Tao (2011, chapter 1, linked in sources) develops the construction fully.
Null sets and “almost surely”
A countable union of null sets is null by subadditivity. Every countable set is Lebesgue-null because each point fits in an interval of length , as just seen with rationals. Thus if you choose , almost surely is irrational. But null does not mean impossible: and can take value (a continuous variable takes some value, all having probability zero). Functions differing only on a null set are indistinguishable for integration, as the Lebesgue integral will show.
A final technical detail. Subsets of a null set need not be measurable in . A measure is complete if they are. Every measure space has a completion (add subsets of null sets to ), and the Lebesgue σ-algebra from Carathéodory’s theorem is the completion of . Probability usually works with uncompleted and writes “a.s.” to avoid dependence on that.
The Cantor set: null and uncountable
Some null sets are far larger than countable ones. The most famous is built by removing thirds.
Let and be what remains of after removing the open middle third of each interval. is a union of intervals of length , and the Cantor set is .
It is null. , and since with , continuity from above gives .
It is uncountable. Each has a ternary expansion with . A point belongs to if and only if it admits an expansion whose first digits are not (the first step removes exactly whose first digit must be ; the next acts likewise within each remaining third). Thus is the set of admitting an expansion using only digits and . Map , is injective: if two sequences first differ at , with and , the difference of their images is at least . Map from to is surjective, because every number in has a binary expansion. Therefore has at least as many points as (in cardinality terms: injects into and maps onto ), is uncountable (Cantor diagonal) and .
Four consequences:
- Null does not mean countable or empty. has the cardinality of and measure . “Negligible for measure” and “small as a set” are different ideas.
- Some Lebesgue sets are not Borel. By completeness, all subsets of are -measurable (null). Since has only elements, the Lebesgue σ-algebra is strictly larger than Borel’s.
- Null is not the same as topologically small. In the figure’s “fat Cantor” set, step removes a gap of length from each of intervals; removed length is , leaving a closed, interval-free, uncountable set of measure .
- Digits matter. Numbers in whose first decimal digits contain no 7 have measure ; those with no 7 in any position have measure but are uncountable by the same argument as . Almost every real contains every digit, in a sense the strong law will make precise.
Implementation from scratch
The whole lesson can be explored on finite sets with exact arithmetic. First, finite σ-algebras: compute the generated one by closure under complements and unions (iterating until unchanged), extract atoms with the rule “two points are indistinguishable if they belong to the same family sets”, and verify , the finite-σ-algebra theorem. Examples are from the information figure.
from itertools import combinations, product
def cierre_sigma(omega, familia):
"""σ-álgebra generada por `familia` sobre un Ω finito: cierre por complemento y unión."""
omega = frozenset(omega)
S = {frozenset(), omega} | {frozenset(A) for A in familia}
cambio = True
while cambio:
cambio = False
for A in list(S):
if omega - A not in S:
S.add(omega - A)
cambio = True
for A, B in combinations(list(S), 2):
if A | B not in S:
S.add(A | B)
cambio = True
return S
def atomos(omega, familia):
"""Clases de puntos con la misma pertenencia a todos los conjuntos de la familia."""
grupos = {}
for w in omega:
grupos.setdefault(tuple(w in A for A in familia), set()).add(w)
return [frozenset(g) for g in grupos.values()]
omega = ["".join(t) for t in product("CX", repeat=3)] # CCC, CCX, ..., XXX
caras = lambda w: w.count("C")
observaciones = {
"nada": [],
"1.er lanzamiento": [{w for w in omega if w[0] == "C"}],
"2 primeros": [{w for w in omega if w[0] == "C"}, {w for w in omega if w[1] == "C"}],
"los 3": [{w for w in omega if w[i] == "C"} for i in range(3)],
"nº de caras": [{w for w in omega if caras(w) == k} for k in range(4)],
}
sigmas = {}
for nombre, fam in observaciones.items():
S = cierre_sigma(omega, fam)
at = atomos(omega, fam)
sigmas[nombre] = S
print(f"{nombre:17s} átomos = {len(at)} |σ| = {len(S):3d} 2^átomos = {2 ** len(at):3d}")
assert len(S) == 2 ** len(at)
# Cada elemento de σ es una unión de átomos, y la filtración crece
F = sigmas
print("\nF0 ⊂ F1 ⊂ F2 ⊂ F3:", F["nada"] <= F["1.er lanzamiento"] <= F["2 primeros"] <= F["los 3"])
print("σ(nº de caras) ⊂ σ(2 primeros)?", F["nº de caras"] <= F["2 primeros"],
" σ(2 primeros) ⊂ σ(nº de caras)?", F["2 primeros"] <= F["nº de caras"])The last two print answer the figure’s question: observing head count is neither more nor less informative than the first two tosses, and σ-algebras are incomparable.
Second, π-λ in the finite world. “Determine a measure” is a linear-algebra problem: probabilities of agreeing with on the family are affine solutions of a system, determined when its rank is . Code computes degrees of freedom and constructs two different measures agreeing on the family.
import numpy as np
omega = [1, 2, 3, 4]
p = np.array([0.4, 0.1, 0.3, 0.2])
indicadora = lambda A: np.array([1.0 if w in A else 0.0 for w in omega])
def sistema(familia):
"""Filas: Ω (suma 1) y un suceso por conjunto de la familia."""
return np.array([np.ones(4)] + [indicadora(B) for B in familia])
def es_pi_sistema(familia):
fam = [frozenset(B) for B in familia]
return all((A & B) == frozenset() or (A & B) in fam for A in fam for B in fam)
familias = {
"{1,2}, {2,3}": [{1, 2}, {2, 3}],
"{1,2}, {2,3}, {2}": [{1, 2}, {2, 3}, {2}],
"{1,2}, {2,3}, {1,3}": [{1, 2}, {2, 3}, {1, 3}],
"{1,2}": [{1, 2}],
"{1}, {2}, {3}": [{1}, {2}, {3}],
}
for nombre, fam in familias.items():
M = sistema(fam)
libres = 4 - np.linalg.matrix_rank(M)
print(f"{nombre:22s} π-sistema: {str(es_pi_sistema(fam)):5s} grados de libertad: {libres}")
# Dos medidas distintas que coinciden en {1,2} y {2,3}
M = sistema(familias["{1,2}, {2,3}"])
v = np.linalg.svd(M)[2][-1] # dirección del núcleo de M
v = v / np.abs(v).max()
q = p + 0.1 * v
print("\ndirección:", np.round(v, 3))
print("p =", p, " q =", np.round(q, 3))
print("coinciden en {1,2}:", np.isclose(p[[0, 1]].sum(), q[[0, 1]].sum()), " en {2,3}:", np.isclose(p[[1, 2]].sum(), q[[1, 2]].sum()))
print("pero p({1}) =", p[0], " y q({1}) =", round(q[0], 3))Notice row three: family is not a π-system, yet determines the measure. The theorem says a generating π-system suffices, not that it is necessary. Without that assumption there is no guarantee, as row one shows.
Third, remaining length of Cantor-type sets using exact fractions, and checking that belongs to (its ternary digits alternate and ) while does not. Then how many steps make classical length fall below (). Finally a digit-exercise simulation: the fraction of uniform numbers whose first ten decimal digits contain no 7 should be near .
from fractions import Fraction as Fr
import numpy as np
def paso(intervalos, k, tipo):
"""Un paso: se elimina un hueco abierto centrado de cada intervalo."""
nuevos = []
for a, b in intervalos:
hueco = (b - a) / 3 if tipo == "clásico" else Fr(1, 4 ** k)
m = (a + b) / 2
nuevos += [(a, m - hueco / 2), (m + hueco / 2, b)]
return nuevos
for tipo in ("clásico", "gordo"):
I = [(Fr(0), Fr(1))]
for k in range(1, 11):
I = paso(I, k, tipo)
if k in (1, 2, 5, 10):
L = sum(b - a for a, b in I)
esperado = Fr(2, 3) ** k if tipo == "clásico" else Fr(1, 2) + Fr(1, 2 ** (k + 1))
print(f"{tipo:8s} paso {k:2d}: {len(I):4d} intervalos, longitud = {float(L):.6f} fórmula: {float(esperado):.6f} iguales: {L == esperado}")
print()
def ternario(x, n=12):
"""Dígitos ternarios con la regla de Cantor (0 o 2 si se puede) y posición del primer 1."""
digitos, vivo, primero = [], True, None
for k in range(n):
t = 3 * x
if vivo and t <= 1:
d, x = 0, t
elif vivo and t >= 2:
d, x = 2, t - 2
elif vivo:
d, x, vivo, primero = 1, t - 1, False, k + 1
else:
d = min(2, int(t)); x = t - d
digitos.append(d)
return digitos, primero
for x in (Fr(1, 4), Fr(1, 3), Fr(1, 10), Fr(1, 2), Fr(1, 20)):
d, primero = ternario(x)
print(f"{str(x):5s} dígitos {''.join(map(str, d))} primer 1 en la posición {primero} {'está en C' if primero is None else 'no está en C'}")
n = 18
print(f"\n(2/3)^{n} = {(2 / 3) ** n:.6f} < 0.001; con n = {n - 1}: {(2 / 3) ** (n - 1):.6f} > 0.001")
rng = np.random.default_rng(0)
x = rng.random(200_000)
decimales = (np.floor(x[:, None] * 10.0 ** np.arange(1, 11)) % 10).astype(int)
sin_siete = ~(decimales == 7).any(axis=1)
print(f"fracción sin ningún 7 en los 10 primeros decimales: {sin_siete.mean():.4f} 0.9^10 = {0.9 ** 10:.4f}")Fourth, covering rationals. Enumerate them by denominator, give each an interval of length and calculate the union measure exactly (merging intervals). Total length never exceeds and uncovered fraction is at least , though each rational is covered.
from math import gcd
def racionales(Q):
r = [(0, 1), (1, 1)]
for q in range(2, Q + 1):
r += [(p, q) for p in range(1, q) if gcd(p, q) == 1]
return r
def union_y_huecos(intervalos):
"""Fusiona intervalos [a, b] recortados a [0, 1]; devuelve la medida de la unión y la lista de huecos."""
iv = sorted((max(0.0, a), min(1.0, b)) for a, b in intervalos)
fusion = [list(iv[0])]
for a, b in iv[1:]:
if a <= fusion[-1][1]:
fusion[-1][1] = max(fusion[-1][1], b)
else:
fusion.append([a, b])
huecos = [(fusion[i][1], fusion[i + 1][0]) for i in range(len(fusion) - 1)]
if fusion[0][0] > 0: huecos.insert(0, (0.0, fusion[0][0]))
if fusion[-1][1] < 1: huecos.append((fusion[-1][1], 1.0))
return sum(b - a for a, b in fusion), huecos
for eps in (0.5, 0.1, 0.01):
for Q in (5, 12, 30):
R = racionales(Q)
L = [eps / 2 ** n for n in range(1, len(R) + 1)]
medida, huecos = union_y_huecos([(p / q - l / 2, p / q + l / 2) for (p, q), l in zip(R, L)])
mayor = max(b - a for a, b in huecos)
print(f"eps = {eps:<5} q <= {Q:2d}: {len(R):3d} racionales, suma de longitudes = {sum(L):.5f}, "
f"unión = {medida:.5f}, sin cubrir = {1 - medida:.5f} (>= {1 - eps:.2f}), huecos = {len(huecos)}, mayor = {mayor:.4f}")The library version
NumPy simulates Bertrand’s paradox vectorially: three recipes, half a million chords per recipe. SymPy calculates Lebesgue measure of sets built from interval set operations (Interval, Union) without manually writing any length formula: real Lebesgue measure restricted to the algebra of finite interval unions (the following note explains why it cannot go further).
import numpy as np
from sympy import Interval, Union, Rational, S
rng = np.random.default_rng(1)
N = 500_000
lado = np.sqrt(3)
# 1) dos extremos uniformes en la circunferencia
a, b = rng.uniform(0, 2 * np.pi, (2, N))
largo1 = 2 * np.abs(np.sin((a - b) / 2)) > lado
# 2) distancia uniforme sobre un radio: la cuerda mide 2*sqrt(1 - d^2)
d = rng.uniform(0, 1, N)
largo2 = 2 * np.sqrt(1 - d ** 2) > lado
# 3) punto medio uniforme en el disco: la distancia al centro es sqrt(U)
r = np.sqrt(rng.uniform(0, 1, N))
largo3 = 2 * np.sqrt(1 - r ** 2) > lado
print("frecuencias:", largo1.mean().round(4), largo2.mean().round(4), largo3.mean().round(4), " exactas: 1/3, 1/2, 1/4")
# Medida de Lebesgue de borelianos construidos con operaciones de conjuntos
cantor = [Interval(0, 1)]
for n in range(1, 5):
nuevos = []
for I in cantor:
a_, b_ = I.start, I.end
h = (b_ - a_) / 3
nuevos += [Interval(a_, a_ + h), Interval(b_ - h, b_)]
cantor = nuevos
if n in (1, 2, 4):
C_n = Union(*cantor)
print(f"C_{n}: {len(cantor)} intervalos, medida = {C_n.measure} = {float(C_n.measure):.6f}")
U = Union(Interval(0, Rational(1, 2)), Interval(Rational(1, 4), 1))
print("medida de [0,1/2] U [1/4,1] =", U.measure, " (solapan: no se suman)")
print("medida del complemento de [0,1] en [-1,2]:", Interval(-1, 2).measure - Interval(0, 1).measure)
print("un punto:", Interval(Rational(1, 3), Rational(1, 3)).measure, " (Q ∩ [0,1] no es una unión finita de intervalos: SymPy no lo mide; su medida 0 sale del argumento ε/2^n)")Common errors
Exercises
Step 1 of 4. How do you check ?
Step 1 of 3. Which π-system do you choose?
More than one answer may be correct.
atoms(sets, omega), taking a list sets of subsets of omega (a finite iterable) and returning the list of atoms of the σ-algebra they generate: the partition of omega into classes of points belonging to exactly the same sets in sets. Each atom must be a frozenset. List order does not matter. With empty sets the only atom is all of omega. Tests check it is a partition and generated σ-algebra cardinality is with the atom count.def atoms(sets, omega):
"""Devuelve la lista de átomos (frozensets) de la σ-álgebra generada por sets sobre omega."""
omega = list(omega)
# tu código: agrupa los puntos por su "firma" de pertenencia a cada conjunto de sets
return [frozenset(omega)]Summary
- “Choose at random” requires a measure. Bertrand’s paradox has three answers, , and , because there are three measures on chords.
- No countably additive, translation-invariant normalized measure exists on every subset of (Vitali). The domain is restricted to a σ-algebra .
- A σ-algebra contains and is closed under complements and countable unions. That generated by a family is the intersection of all containing it. On finite it corresponds to a partition into atoms and has elements. Observing more refines the partition, and a filtration is an increasing σ-algebra sequence.
- is generated by open sets and also by rays , because rationals are countable and dense. It is too large to enumerate.
- A measure is countably additive, yielding monotonicity, subadditivity and continuity from below (always) and above (when some set has finite measure).
- π-λ. If two measures agree on a generating π-system and finite-measure sets increase to , they agree everywhere. In particular, a probability on is determined by its distribution function.
- Carathéodory. Outer measure restricted to sets that split every set additively is a measure and contains the Borel sets: Lebesgue measure, unique with and translation invariant.
- Null sets have measure zero, and “almost surely” means outside a null set. Countable sets are null, and the Cantor set is null and uncountable. Fat versions have positive measure.