Skip to content
The Lumenary
Advanced undergraduateUndergraduate (second or third year) 120 min

Markov chains

Random processes whose future depends on the past only through the present — transition matrices, recurrence and transience, stationary distributions, and why a well-mixed chain forgets where it began.

Formally verified · 19 LeanComputationally tested · 3 PythonAI-drafted · awaiting human reviewMathematically reviewed: Awaiting human review
MotivationH

Memory of one step

In 1913 Andrei Markov took the first 20 00020\,000 letters of Pushkin's Eugene Onegin and counted how often a vowel follows a vowel and a consonant follows a consonant. He was making a mathematical point: the law of large numbers does not need independence. Letters are far from independent, but if each letter depends on the past only through the letter before it, averages still settle down. Processes of this kind — Markov chains — are now everywhere:

  • Board games. In snakes and ladders (which originated in India as Moksha Patam), your next square depends only on your current square and the die. How long does a game last?
  • The web. Google's PageRank ranks pages by the long-run fraction of time a random surfer spends on each — the stationary distribution of a chain on billions of states.
  • Genetics. In the Wright–Fisher model of a population, the number of copies of a gene in the next generation depends only on the number in this one. Will a new variant spread or vanish?
  • Computation. Markov chain Monte Carlo methods sample from distributions too complicated to write down, by running a chain that has them as equilibrium.

The questions are always the same: Where will the chain be after nn steps? Will it reach a given set of states, and how long will it take? Does it return to where it started? Does it settle into an equilibrium, and how fast? This lesson answers them for chains with countably many states, with complete proofs for finite chains. It uses probability theory (conditional probability, expectation) and linear algebra (matrices, eigenvalues, rank).

IntuitionH

A two-state chain

Each day in a highland town is dry or rainy. If today is dry, tomorrow is rainy with probability aa; if today is rainy, tomorrow is dry with probability bb. Let xnx_n be the probability that day nn is rainy. Conditioning on day nn,

xn+1=a(1−xn)+(1−b)xn=a+(1−a−b) xn.x_{n+1} = a(1 - x_n) + (1 - b)x_n = a + (1 - a - b)\,x_n .

This is a straight-line map with slope 1−a−b1 - a - b and fixed point x∗=aa+bx^* = \frac{a}{a + b}; when ∣1−a−b∣<1|1 - a - b| < 1 it is a contraction, and xn→x∗x_n \to x^* from any start, at the geometric rate ∣1−a−b∣n|1 - a - b|^n.

The probability of rain, day by day

Start from a dry day (x₀ = 0). Every orbit is drawn to a/(a + b). Try a = b = 1: the slope is −1 and the orbit oscillates forever.

f(x) =
x₀

Iterates xₖ against k

  • y = f(x)
  • y = x
  • cobweb path

Last iterates: x18 = 0.375, x19 = 0.375, x20 = 0.375

The orbit appears to settle at a fixed point x* ≈ 0.375.

Fixed points in view (numerical): x* = 0.375 (attracting: |f′(x*)| < 1)

Based on 3,000 iterations in floating-point arithmetic: numerical evidence, not proof.

Three phenomena are already visible. The chain has an equilibrium, the stationary probability aa+b\frac{a}{a+b} of rain. It forgets its starting point geometrically fast. And when a=b=1a = b = 1 the weather alternates deterministically — a periodic chain, which never settles down. The rest of the lesson is about these three phenomena on general state spaces.

DefinitionsH

Definitions

Let II be a countable set, the state space. A distribution on II is a row vector λ=(λi)i∈I\lambda = (\lambda_i)_{i \in I} with λi≥0\lambda_i \ge 0 and ∑iλi=1\sum_i \lambda_i = 1.

Definition— transition matrix and Markov chain

A transition matrix (or stochastic matrix) is P=(pij)i,j∈IP = (p_{ij})_{i, j \in I} with pij≥0p_{ij} \ge 0 and ∑jpij=1\sum_j p_{ij} = 1 for every ii: each row is a distribution. A sequence of random variables X0,X1,…X_0, X_1, \dots with values in II is a Markov chain with initial distribution λ\lambda and transition matrix PP if P(X0=i)=λiP(X_0 = i) = \lambda_i and, for all nn and all states,

P(Xn+1=j∣X0=i0,…,Xn−1=in−1,Xn=i)=pijP(X_{n+1} = j \mid X_0 = i_0, \dots, X_{n-1} = i_{n-1}, X_n = i) = p_{ij}

whenever the conditioning event has positive probability. Equivalently, P(X0=i0,X1=i1,…,Xn=in)=λi0pi0i1⋯pin−1inP(X_0 = i_0, X_1 = i_1, \dots, X_n = i_n) = \lambda_{i_0}p_{i_0i_1}\cdots p_{i_{n-1}i_n}.

The Markov property says that, given the present state Xn=iX_n = i, the future (Xn,Xn+1,… )(X_n, X_{n+1}, \dots) is independent of the past (X0,…,Xn−1)(X_0, \dots, X_{n-1}) and is itself a Markov chain started at ii. The strong Markov property says the same at a random time TT that is a stopping time (whether T=nT = n is decided by X0,…,XnX_0, \dots, X_n), such as the first time the chain hits a given state. We write PiP_i and EiE_i for probabilities and expectations when X0=iX_0 = i.

Definition— hitting times, recurrence and transience

The hitting time of a set AA is HA=inf⁡{n≥0:Xn∈A}H^A = \inf\{n \ge 0 : X_n \in A\} and the first return time to ii is Ti=inf⁡{n≥1:Xn=i}T_i = \inf\{n \ge 1 : X_n = i\} (with inf⁡∅=∞\inf \emptyset = \infty). A state ii is recurrent if Pi(Ti<∞)=1P_i(T_i < \infty) = 1 and transient otherwise. A recurrent state is positive recurrent if moreover mi=Ei[Ti]<∞m_i = E_i[T_i] < \infty, its mean return time.

Definition— communicating classes, irreducibility, period

State jj is accessible from ii, written i→ji \to j, if pij(n)>0p_{ij}^{(n)} > 0 for some n≥0n \ge 0, where pij(n)=(Pn)ijp_{ij}^{(n)} = (P^n)_{ij}. States communicate, i↔ji \leftrightarrow j, if i→ji \to j and j→ij \to i; this is an equivalence relation, whose classes are the communicating classes. A class CC is closed if i∈Ci \in C and i→ji \to j imply j∈Cj \in C. The chain is irreducible if there is a single class. The period of ii is d(i)=gcd⁡{n≥1:pii(n)>0}d(i) = \gcd\{n \ge 1 : p_{ii}^{(n)} > 0\}, and ii is aperiodic if d(i)=1d(i) = 1.

Definition— stationary distribution and detailed balance

A distribution π\pi is stationary (or invariant) if πP=π\pi P = \pi, that is, πj=∑iπipij\pi_j = \sum_i \pi_i p_{ij} for all jj: a chain started from π\pi has distribution π\pi at every time. A distribution π\pi satisfies detailed balance with PP if πipij=πjpji\pi_i p_{ij} = \pi_j p_{ji} for all i,ji, j; the chain is then reversible: started from π\pi, it looks the same run forwards or backwards in time.

The total-variation distance between distributions is ∥μ−ν∥TV=12∑i∣μi−νi∣=max⁡A⊆I∣μ(A)−ν(A)∣\|\mu - \nu\|_{TV} = \frac12\sum_i |\mu_i - \nu_i| = \max_{A \subseteq I}|\mu(A) - \nu(A)|.

Worked examplesH

Examples

Example— The two-state chain in matrix form

With states 0=0 = dry and 1=1 = rainy, P=(1−aab1−b)P = \begin{pmatrix} 1 - a & a \\ b & 1 - b \end{pmatrix}. Its eigenvalues are 11 and λ=1−a−b\lambda = 1 - a - b, the stationary distribution is π=(ba+b,aa+b)\pi = \big(\frac{b}{a + b}, \frac{a}{a + b}\big), and (proved by induction in the Lean section)

Pn=1a+b(b+aλna−aλnb−bλna+bλn).P^n = \frac{1}{a + b}\begin{pmatrix} b + a\lambda^n & a - a\lambda^n \\ b - b\lambda^n & a + b\lambda^n \end{pmatrix}.

Each row is π\pi plus a correction of size O(∣λ∣n)O(|\lambda|^n). If 0<a+b<20 < a + b < 2, then Pn→(ππ)P^n \to \begin{pmatrix} \pi \\ \pi \end{pmatrix}; if a=b=1a = b = 1, then λ=−1\lambda = -1 and PnP^n alternates.

A transposed transition matrix acting on distributions

This is Pᵀ for a = 0.3, b = 0.1, so that column vectors (dry, rain) map to their next-day distributions. The invariant line for eigenvalue 1 is spanned by (b, a) = (0.1, 0.3) — the stationary distribution — and the other invariant line, with eigenvalue 1 − a − b = 0.6, is the direction (1, −1) that dies away.

Your own matrix
λ₁ = 1λ₂ = 0.6Ae₁Ae₂
  • image of the grid
  • image of the unit square
  • image of the flag
  • before the transformation
  • invariant line
Entries of the matrix A
A =

The columns of A are the images of e₁ = (1, 0) and e₂ = (0, 1): Ae₁ = (0.7, 0.3), Ae₂ = (0.1, 0.9)

det A = ad − bc = 0.6

The unit square (area 1) becomes a parallelogram of area |det A| = 0.6. Since det A > 0, orientation is preserved.

Invariant lines (real eigenvectors)

  • λ₁ = 1, v₁ = (0.333, 1)
  • λ₂ = 0.6, v₂ = (1, −1)

Vectors on the two dashed lines are only stretched, by the factors λ₁ = 1 and λ₂ = 0.6; every other direction is turned.

Example— Random walk on a graph

On a finite connected graph, let the walker move from a vertex to a uniformly random neighbour: puv=1/deg⁡up_{uv} = 1/\deg u for each edge uvuv. Then πv=deg⁡v2∣E∣\pi_v = \frac{\deg v}{2|E|} satisfies detailed balance, since πupuv=12∣E∣=πvpvu\pi_u p_{uv} = \frac{1}{2|E|} = \pi_v p_{vu} for every edge; so it is stationary. The walk is irreducible (the graph is connected) and aperiodic exactly when the graph is not bipartite. On the wheel below, the hub has degree 55 and the rim vertices degree 33, so in the long run the walker is at the hub a quarter of the time.

Random walk on a wheel

Stationary probability is proportional to degree: 5/20 at the hub, 3/20 at each rim vertex. In the matrix tab, entries of A^k count walks of length k.

A3B3C3D3E3H5
|V| = 6|E| = 10Select a vertex to see the edges that meet there.
deg(A) = 3deg(B) = 3deg(C) = 3deg(D) = 3deg(E) = 3deg(H) = 5

3 + 3 + 3 + 3 + 3 + 5 = 20 = 2 × 10

Every edge has two ends, so it adds exactly 2 to the total: the degrees add up to 20 = 2 × 10. This is the handshake lemma, Σ deg(v) = 2|E|.

Vertices of odd degree: 6. This number is always even, because the total is even.

Example— Gambler's ruin

A gambler with ii coins bets one coin at a time, winning with probability pp and losing with probability q=1−pq = 1 - p, and stops at 00 or NN. This is a chain on {0,1,…,N}\{0, 1, \dots, N\} with pi,i+1=pp_{i,i+1} = p, pi,i−1=qp_{i,i-1} = q for 0<i<N0 < i < N and absorbing states 00 and NN (p00=pNN=1p_{00} = p_{NN} = 1). The classes are {0}\{0\}, {N}\{N\} (closed, recurrent) and {1,…,N−1}\{1, \dots, N-1\} (not closed, transient). Its hitting probabilities are computed below.

Example— The Ehrenfest urn: periodic and reversible

Paul and Tatjana Ehrenfest (1907) modelled the diffusion of gas between two containers: NN balls are split between two urns, and at each step a uniformly random ball changes urn. With XnX_n the number of balls in the first urn, pk,k−1=k/Np_{k,k-1} = k/N and pk,k+1=1−k/Np_{k,k+1} = 1 - k/N. The binomial distribution πk=(Nk)2−N\pi_k = \binom Nk 2^{-N} satisfies detailed balance: (Nk)N−kN=(Nk+1)k+1N\binom Nk \frac{N - k}{N} = \binom N{k+1}\frac{k+1}{N}. The chain is irreducible but has period 22 (XnX_n changes parity at each step), so P(Xn=k)P(X_n = k) does not converge, although the long-run fraction of time spent at kk does tend to πk\pi_k.

ProofH

n-step transitions and first-step analysis

Theorem— Theorem (Chapman–Kolmogorov)

For a Markov chain with initial distribution λ\lambda and transition matrix PP: P(Xn=j)=(λPn)jP(X_n = j) = (\lambda P^n)_j and Pi(Xn=j)=pij(n)P_i(X_n = j) = p_{ij}^{(n)}. In particular pij(m+n)=∑kpik(m)pkj(n)p_{ij}^{(m+n)} = \sum_k p_{ik}^{(m)}p_{kj}^{(n)}.

Proof

By the law of total probability and the Markov property, P(Xn+1=j)=∑iP(Xn=i) pijP(X_{n+1} = j) = \sum_i P(X_n = i)\,p_{ij}, i.e. the row vector of probabilities at time n+1n + 1 is that at time nn times PP; induct on nn. The last identity is Pm+n=PmPnP^{m+n} = P^mP^n.

∎

Products and powers of stochastic matrices are stochastic, so each PnP^n is again a transition matrix — the matrix of the chain observed every nn steps.

Theorem— Theorem (hitting probabilities)

Let A⊆IA \subseteq I and hi=Pi(HA<∞)h_i = P_i(H^A < \infty). Then hh is the minimal non-negative solution of the system

hi=1(i∈A),hi=∑j∈Ipijhj(i∉A),h_i = 1 \quad (i \in A), \qquad h_i = \sum_{j \in I} p_{ij}h_j \quad (i \notin A),

meaning that hh solves it, and any solution xx with xi≥0x_i \ge 0 for all ii satisfies xi≥hix_i \ge h_i for all ii.

Proof

hh is a solution ("first-step analysis"): if i∈Ai \in A then HA=0H^A = 0; if i∉Ai \notin A, condition on X1X_1 and use the Markov property: Pi(HA<∞)=∑jpijPj(HA<∞)P_i(H^A < \infty) = \sum_j p_{ij}P_j(H^A < \infty).

Minimality. Let x≥0x \ge 0 be a solution and i∉Ai \notin A. Substituting the equation into itself,

xi=∑j∈Apij+∑j∉Apijxj=∑j∈Apij+∑j∉Apij∑k∈Apjk+∑j,k∉Apijpjkxk=Pi(HA≤2)+∑j,k∉Apijpjkxk.x_i = \sum_{j \in A} p_{ij} + \sum_{j \notin A} p_{ij}x_j = \sum_{j \in A}p_{ij} + \sum_{j \notin A}p_{ij}\sum_{k \in A}p_{jk} + \sum_{j, k \notin A}p_{ij}p_{jk}x_k = P_i(H^A \le 2) + \sum_{j,k \notin A}p_{ij}p_{jk}x_k .

After nn substitutions, xi=Pi(HA≤n)+(a sum of non-negative terms)≥Pi(HA≤n)x_i = P_i(H^A \le n) + (\text{a sum of non-negative terms}) \ge P_i(H^A \le n). Letting n→∞n \to \infty, xi≥Pi(HA<∞)=hix_i \ge P_i(H^A < \infty) = h_i.

∎

Expected hitting times ki=Ei[HA]k_i = E_i[H^A] are, in the same way, the minimal non-negative solution of ki=0k_i = 0 for i∈Ai \in A and ki=1+∑j∉Apijkjk_i = 1 + \sum_{j \notin A}p_{ij}k_j for i∉Ai \notin A.

Example— Solving gambler's ruin

With A={N}A = \{N\}, the probability h(i)h(i) of reaching NN satisfies h(i)=p h(i+1)+q h(i−1)h(i) = p\,h(i + 1) + q\,h(i - 1) for 0<i<N0 < i < N, with h(0)=0h(0) = 0 and h(N)=1h(N) = 1 (on a finite set the solution is unique, so minimality is automatic). The characteristic equation pρ2−ρ+q=0p\rho^2 - \rho + q = 0 has roots 11 and r=q/pr = q/p. Hence:

  • Fair game (p=12p = \frac12, double root 11): h(i)=A+Bih(i) = A + Bi, so h(i)=iNh(i) = \frac iN.
  • Unfair game (p≠12p \ne \frac12): h(i)=A+Brih(i) = A + Br^i, so h(i)=1−ri1−rNh(i) = \dfrac{1 - r^i}{1 - r^N}.

The expected duration of the fair game solves m(i)=1+12m(i−1)+12m(i+1)m(i) = 1 + \frac12 m(i-1) + \frac12 m(i+1), m(0)=m(N)=0m(0) = m(N) = 0, so m(i)=i(N−i)m(i) = i(N - i): starting with 1010 coins and playing to 00 or 2020 takes 100100 bets on average. Betting on red at roulette (p=1838p = \frac{18}{38}, r=109r = \frac{10}{9}), the chance of turning 1010 coins into 2020 is 11+(10/9)10≈0.26\frac{1}{1 + (10/9)^{10}} \approx 0.26. Against an infinitely rich opponent (N→∞N \to \infty) the fair gambler is ruined with probability lim⁡N(1−i/N)=1\lim_N (1 - i/N) = 1, while a gambler with p>12p > \frac12 survives forever with probability 1−(q/p)i1 - (q/p)^i — here the minimality in the theorem is essential, since on an infinite state space the equations have many solutions.

ProofH

Recurrence and transience

Theorem— Theorem (recurrence criterion)

Let fi=Pi(Ti<∞)f_i = P_i(T_i < \infty) and let Vi=∑n≥11{Xn=i}V_i = \sum_{n \ge 1}\mathbf 1_{\{X_n = i\}} be the number of returns to ii. Then Pi(Vi≥k)=fikP_i(V_i \ge k) = f_i^k for k≥0k \ge 0, and

Ei[Vi]=∑n≥1pii(n)={fi1−fi<∞if i is transient,∞if i is recurrent.E_i[V_i] = \sum_{n \ge 1} p_{ii}^{(n)} = \begin{cases} \dfrac{f_i}{1 - f_i} < \infty & \text{if } i \text{ is transient}, \\[2mm] \infty & \text{if } i \text{ is recurrent.}\end{cases}

So ii is recurrent if and only if ∑npii(n)=∞\sum_n p_{ii}^{(n)} = \infty, and then the chain started at ii returns infinitely often with probability 11.

Proof

Let T(k)T^{(k)} be the time of the kk-th return (a stopping time). On {T(k)<∞}\{T^{(k)} < \infty\} the chain is at ii at time T(k)T^{(k)}, so by the strong Markov property the future is a fresh chain started at ii, and the probability of a further return is fif_i, independently of the past. By induction Pi(Vi≥k)=Pi(T(k)<∞)=fikP_i(V_i \ge k) = P_i(T^{(k)} < \infty) = f_i^k. Then Ei[Vi]=∑k≥1Pi(Vi≥k)=∑k≥1fikE_i[V_i] = \sum_{k \ge 1}P_i(V_i \ge k) = \sum_{k \ge 1}f_i^k, which is fi/(1−fi)f_i/(1 - f_i) if fi<1f_i < 1 and infinite if fi=1f_i = 1. On the other hand, by linearity, Ei[Vi]=∑n≥1Pi(Xn=i)=∑n≥1pii(n)E_i[V_i] = \sum_{n \ge 1}P_i(X_n = i) = \sum_{n \ge 1}p_{ii}^{(n)}. If fi=1f_i = 1, Pi(Vi≥k)=1P_i(V_i \ge k) = 1 for every kk, so Vi=∞V_i = \infty almost surely.

∎

Theorem— Corollary (recurrence is a class property; finite closed classes are recurrent)

If i↔ji \leftrightarrow j, then ii and jj are both recurrent or both transient. Every closed class with finitely many states is recurrent; in particular every state of an irreducible finite chain is recurrent.

Proof

Choose m,rm, r with pji(m)>0p_{ji}^{(m)} > 0 and pij(r)>0p_{ij}^{(r)} > 0. Then pjj(m+n+r)≥pji(m)pii(n)pij(r)p_{jj}^{(m+n+r)} \ge p_{ji}^{(m)}p_{ii}^{(n)}p_{ij}^{(r)} (one way of returning to jj), so ∑npii(n)=∞\sum_n p_{ii}^{(n)} = \infty implies ∑npjj(n)=∞\sum_n p_{jj}^{(n)} = \infty; by symmetry the converse holds too. For a finite closed class CC and i∈Ci \in C, the chain stays in CC, so ∑j∈C∑n≥1pij(n)=∑n≥11=∞\sum_{j \in C}\sum_{n \ge 1}p_{ij}^{(n)} = \sum_{n \ge 1}1 = \infty, and some j∈Cj \in C has ∑npij(n)=∞\sum_n p_{ij}^{(n)} = \infty. With pji(m)>0p_{ji}^{(m)} > 0, ∑npjj(n+m)≥pji(m)∑npij(n)=∞\sum_n p_{jj}^{(n+m)} \ge p_{ji}^{(m)}\sum_n p_{ij}^{(n)} = \infty, so jj is recurrent, and hence so is the whole class.

∎

On infinite state spaces recurrence becomes a deep question. Simple random walk on Zd\Z^d moves at each step to one of the 2d2d neighbours, each with probability 12d\frac{1}{2d}.

Theorem— Theorem (Pólya, 1921)

Simple random walk on Zd\Z^d is recurrent for d=1,2d = 1, 2 and transient for d≥3d \ge 3.

Proof

A return to 00 is only possible at even times. Write an=(2nn)4−na_n = \binom{2n}{n}4^{-n}.

d=1d = 1. P0(S2n=0)=anP_0(S_{2n} = 0) = a_n, the probability of exactly nn steps to the right among 2n2n. The 2n+12n + 1 binomial coefficients (2nk)\binom{2n}k add up to 4n4^n and the middle one is the largest, so an≥12n+1a_n \ge \frac{1}{2n + 1}, and ∑nan=∞\sum_n a_n = \infty by comparison with the harmonic series.

d=2d = 2. Rotate by 45°45°: if (x,y)(x, y) is the walker's position, u=x+yu = x + y and v=x−yv = x - y change by (±1,±1)(\pm1, \pm1) at each step, with all four sign patterns equally likely. So uu and vv are independent simple random walks on Z\Z, and P0(S2n=0)=P(u2n=0)P(v2n=0)=an2P_0(S_{2n} = 0) = P(u_{2n} = 0)P(v_{2n} = 0) = a_n^2. From an+1=an2n+12n+2a_{n+1} = a_n\frac{2n+1}{2n+2} and (2n+1)2≥4n(n+1)(2n + 1)^2 \ge 4n(n + 1), induction gives an2≥14na_n^2 \ge \frac{1}{4n} for n≥1n \ge 1, so again ∑nan2=∞\sum_n a_n^2 = \infty.

d=3d = 3 (sketch). Counting paths with i,j,ki, j, k steps out and back along the three axes,

P0(S2n=0)=162n∑i+j+k=n(2n)!(i! j! k!)2=an∑i+j+k=n(n!3n i! j! k!)2≤anmax⁡i+j+k=nn!3n i! j! k!,P_0(S_{2n} = 0) = \frac{1}{6^{2n}}\sum_{i+j+k=n}\frac{(2n)!}{(i!\,j!\,k!)^2} = a_n\sum_{i+j+k=n}\Big(\frac{n!}{3^n\,i!\,j!\,k!}\Big)^2 \le a_n \max_{i+j+k=n}\frac{n!}{3^n\,i!\,j!\,k!},

because the trinomial probabilities n!3ni!j!k!\frac{n!}{3^n i!j!k!} sum to 11. Stirling's formula shows that an≤n−1/2a_n \le n^{-1/2} and that the maximum (attained near i=j=k=n/3i = j = k = n/3) is O(1/n)O(1/n), so P0(S2n=0)=O(n−3/2)P_0(S_{2n} = 0) = O(n^{-3/2}), which is summable. In d≥4d \ge 4 the walk restricted to its first three coordinates, watched only when they move, is a three-dimensional walk, so it too is transient.

∎

The cases d=1d = 1 and d=2d = 2 — the divergence of ∑an\sum a_n and ∑an2\sum a_n^2 — are formalised in Lean below. The precise asymptotics are P0(S2n=0)∼2(d4πn)d/2P_0(S_{2n} = 0) \sim 2\big(\frac{d}{4\pi n}\big)^{d/2}, and in d=3d = 3 the walk returns with probability about 0.340.34 (Watson, 1939). "A drunk man will find his way home, but a drunk bird may get lost forever" (attributed to Shizuo Kakutani). Simple random walk on Z\Z is recurrent but null recurrent: E0[T0]=∞E_0[T_0] = \infty, and it has no stationary distribution.

Random walks on the integers

Each walk returns to 0 again and again, but the typical distance grows like √n — so the returns get rarer, which is why their expected number, though infinite, grows only like √n.

-500500100200300400stepsposition
  • 8 of the walks
  • root-mean-square distance (300 walks)
  • ±√n (exact)

Root-mean-square distance after 400 steps

Simulated20.48

Exact√400 ≈ 20

Simulation of 300 walks of 400 steps: root-mean-square distance 20.48. The exact value is √n, about 20.

Evidence, not proofThis is a simulation of 300 walks (run 1) using a seeded random number generator. It is evidence, not proof: the exact values come from mathematics, and a new run gives slightly different numbers.

Exactly: the average of (position)² after n steps is n, so the root-mean-square distance is √n. Going twice as far takes four times as many steps.

ProofH

Stationary distributions

Theorem— Theorem (existence and uniqueness)

Every Markov chain on a finite state space has a stationary distribution. If the chain is irreducible, the stationary distribution π\pi is unique and πi>0\pi_i > 0 for every ii.

Proof

Existence. Fix a distribution λ\lambda and consider the averages νn=1n∑k=0n−1λPk\nu_n = \frac1n\sum_{k=0}^{n-1}\lambda P^k. They are distributions, which form a compact subset (a simplex) of RI\R^I, so a subsequence νnm\nu_{n_m} converges to a distribution π\pi. Now νnP−νn=1n(λPn−λ)\nu_nP - \nu_n = \frac1n(\lambda P^n - \lambda) has entries of absolute value at most 1n\frac1n, so letting n=nm→∞n = n_m \to \infty gives πP−π=0\pi P - \pi = 0.

Positivity. If π\pi is stationary, then π=πPn\pi = \pi P^n for all nn. Some πi>0\pi_i > 0; for any jj, irreducibility gives nn with pij(n)>0p_{ij}^{(n)} > 0, and πj=∑kπkpkj(n)≥πipij(n)>0\pi_j = \sum_k \pi_k p_{kj}^{(n)} \ge \pi_i p_{ij}^{(n)} > 0.

Uniqueness. First, every h∈RIh \in \R^I with Ph=hPh = h (a harmonic function) is constant. Let M=max⁡ihiM = \max_i h_i, attained at ii. Since hi=∑jpijhjh_i = \sum_j p_{ij}h_j is an average of values ≤M\le M that equals MM, every jj with pij>0p_{ij} > 0 has hj=Mh_j = M. So the set {j:hj=M}\{j : h_j = M\} contains every state reachable in one step from any of its members, hence (by irreducibility) every state. Thus ker⁡(P−I)\ker(P - I) is spanned by the all-ones vector, and rank⁡(P−I)=∣I∣−1\operatorname{rank}(P - I) = |I| - 1. A matrix and its transpose have the same rank, so the space of row vectors π\pi with π(P−I)=0\pi(P - I) = 0 is also one-dimensional. Two stationary distributions are therefore proportional, and since both sum to 11, they are equal.

∎

The unique stationary distribution has a probabilistic meaning: πi=1/mi\pi_i = 1/m_i, the reciprocal of the mean return time (Kac's formula), and the ergodic theorem for Markov chains says that, for an irreducible finite chain and any starting distribution, the fraction of time spent in ii up to time nn tends to πi\pi_i with probability 11 — and more generally 1n∑k<nf(Xk)→∑iπif(i)\frac1n\sum_{k<n}f(X_k) \to \sum_i \pi_i f(i). (We state these without proof; see Norris, §1.7–1.10.) On infinite state spaces, an irreducible chain has a stationary distribution if and only if it is positive recurrent.

Solving πP=π\pi P = \pi is a linear system, but detailed balance is often easier: if πipij=πjpji\pi_ip_{ij} = \pi_jp_{ji} for all i,ji, j, then (πP)j=∑iπjpji=πj(\pi P)_j = \sum_i \pi_jp_{ji} = \pi_j, so π\pi is stationary (proved in Lean below). The random walk on a graph and the Ehrenfest urn were solved this way. Not every stationary distribution satisfies detailed balance: a chain that cycles 1→2→3→11 \to 2 \to 3 \to 1 with probability 0.90.9 and goes backwards with probability 0.10.1 has uniform π\pi but a net probability flow around the cycle.

ProofH

Convergence to equilibrium

Theorem— Theorem (convergence theorem)

Let PP be irreducible and aperiodic on a finite state space II with kk states, and let π\pi be its stationary distribution. Then there are N≥1N \ge 1 and δ>0\delta > 0 such that, for every initial distribution λ\lambda and every nn,

∥λPn−π∥TV≤(1−kδ)⌊n/N⌋.\|\lambda P^n - \pi\|_{TV} \le (1 - k\delta)^{\lfloor n/N \rfloor}.

In particular Pλ(Xn=j)→πjP_\lambda(X_n = j) \to \pi_j for all jj, exponentially fast.

The proof has three steps: a lemma from number theory, a positivity lemma, and Doeblin's contraction.

Theorem— Lemma 1 (numerical semigroups)

If S⊆{1,2,… }S \subseteq \{1, 2, \dots\} is closed under addition and gcd⁡S=1\gcd S = 1, then SS contains every sufficiently large integer.

Proof

The gcd of SS is the gcd of finitely many of its elements, so by Bézout there are s1,…,sr∈Ss_1, \dots, s_r \in S and integers c1,…,crc_1, \dots, c_r with ∑clsl=1\sum c_ls_l = 1. Let aa be the sum of the terms with cl>0c_l > 0 and bb minus the sum of those with cl<0c_l < 0; both are sums of elements of SS, hence in SS (if b=0b = 0 then 1=a∈S1 = a \in S and we are done), and a=b+1a = b + 1. For n≥b2n \ge b^2, write n=qb+tn = qb + t with 0≤t<b≤q0 \le t < b \le q; then n=(q−t)b+t(b+1)=(q−t)b+tan = (q - t)b + t(b + 1) = (q - t)b + ta with q−t≥0q - t \ge 0, so n∈Sn \in S.

∎

Theorem— Lemma 2 (some power is positive)

If PP is irreducible and aperiodic on a finite set, there is NN with pij(n)>0p_{ij}^{(n)} > 0 for all i,ji, j and all n≥Nn \ge N.

Proof

For each ii, Si={n≥1:pii(n)>0}S_i = \{n \ge 1 : p_{ii}^{(n)} > 0\} is closed under addition (Chapman–Kolmogorov: pii(m+n)≥pii(m)pii(n)p_{ii}^{(m+n)} \ge p_{ii}^{(m)}p_{ii}^{(n)}) and has gcd 11, so by Lemma 1 it contains all n≥Nin \ge N_i. Given i,ji, j, choose mijm_{ij} with pij(mij)>0p_{ij}^{(m_{ij})} > 0; then pij(n)≥pii(n−mij)pij(mij)>0p_{ij}^{(n)} \ge p_{ii}^{(n - m_{ij})}p_{ij}^{(m_{ij})} > 0 for n≥Ni+mijn \ge N_i + m_{ij}. Take N=max⁡i,j(Ni+mij)N = \max_{i,j}(N_i + m_{ij}).

∎

Theorem— Lemma 3 (Doeblin's contraction)

Let QQ be a stochastic matrix on kk states whose entries are all at least δ\delta. Then for every row vector xx with ∑ixi=0\sum_i x_i = 0,   ∑j∣(xQ)j∣≤(1−kδ)∑i∣xi∣\;\sum_j |(xQ)_j| \le (1 - k\delta)\sum_i |x_i|.

Proof

Since ∑ixi=0\sum_i x_i = 0, (xQ)j=∑ixiqij=∑ixi(qij−δ)(xQ)_j = \sum_i x_iq_{ij} = \sum_i x_i(q_{ij} - \delta), with qij−δ≥0q_{ij} - \delta \ge 0. Hence ∑j∣(xQ)j∣≤∑j∑i∣xi∣(qij−δ)=∑i∣xi∣∑j(qij−δ)=(1−kδ)∑i∣xi∣\sum_j|(xQ)_j| \le \sum_j\sum_i |x_i|(q_{ij} - \delta) = \sum_i|x_i|\sum_j(q_{ij} - \delta) = (1 - k\delta)\sum_i|x_i|.

∎

Proof of the theorem. Let Q=PNQ = P^N with NN from Lemma 2 and δ=min⁡i,jqij>0\delta = \min_{i,j}q_{ij} > 0 (then kδ≤1k\delta \le 1, as rows sum to 11). The vector x=λ−πx = \lambda - \pi sums to 00, and multiplying by a stochastic matrix keeps the sum at 00 and never increases ∑i∣xi∣\sum_i|x_i| (the same computation with δ=0\delta = 0). Writing n=qN+sn = qN + s and using πPn=π\pi P^n = \pi,

∥λPn−π∥TV=12∑j∣(xQqPs)j∣≤12(1−kδ)q∑i∣xi∣≤(1−kδ)q,\|\lambda P^n - \pi\|_{TV} = \tfrac12\textstyle\sum_j |(xQ^qP^s)_j| \le \tfrac12(1 - k\delta)^q\sum_i|x_i| \le (1 - k\delta)^q,

since ∑i∣λi−πi∣≤2\sum_i |\lambda_i - \pi_i| \le 2. ■\blacksquare

Aperiodicity is necessary: for P=(0110)P = \begin{pmatrix}0 & 1 \\ 1 & 0\end{pmatrix}, λPn\lambda P^n alternates between (1,0)(1, 0) and (0,1)(0, 1), although π=(12,12)\pi = (\frac12, \frac12) is stationary. For a periodic irreducible chain, the averages 1n∑k<nλPk\frac1n\sum_{k<n}\lambda P^k still converge to π\pi, and the "lazy" chain 12(I+P)\frac12(I + P) is aperiodic with the same π\pi.

The rate. Doeblin's bound is crude but universal. The true rate is governed by the eigenvalues of PP: 11 is an eigenvalue (with right eigenvector 1\mathbf 1), all eigenvalues satisfy ∣μ∣≤1|\mu| \le 1, and for an irreducible aperiodic chain all others satisfy ∣μ∣<1|\mu| < 1; ∥λPn−π∥TV\|\lambda P^n - \pi\|_{TV} decays like ∣μ2∣n|\mu_2|^n, where μ2\mu_2 is the second-largest eigenvalue in modulus. For the two-state chain μ2=1−a−b\mu_2 = 1 - a - b. The first experiment below compares the actual distance, ∣μ2∣n|\mu_2|^n and Doeblin's bound for a three-state weather chain.

Doeblin (1938) also invented the other classical proof, by coupling: run two copies of the chain, one from λ\lambda and one from π\pi, independently until they meet, and together afterwards; then ∥λPn−π∥TV≤P(they have not met by time n)\|\lambda P^n - \pi\|_{TV} \le P(\text{they have not met by time } n). Coupling extends to countable state spaces, where the theorem holds for irreducible, aperiodic, positive recurrent chains.

ExplanationH

Three applications

PageRank. Let PP be the random-surfer matrix of the web (follow a uniformly random link from the current page), and JJ the matrix with every entry 1/k1/k. Google's matrix G=αP+(1−α)JG = \alpha P + (1 - \alpha)J, with damping α=0.85\alpha = 0.85 in the original paper (Brin and Page, 1998), has every entry at least (1−α)/k(1 - \alpha)/k. So Doeblin's lemma applies with 1−kδ=α1 - k\delta = \alpha: repeated multiplication converges to the unique stationary distribution — the PageRank vector — with error shrinking by a factor 0.850.85 per iteration, however large kk is.

Markov chain Monte Carlo. To sample from a distribution π\pi on a huge finite set known only up to a constant (a posterior distribution in statistics, a Gibbs distribution in physics), the Metropolis algorithm (Metropolis, Rosenbluth, Rosenbluth, Teller and Teller, 1953) proposes a move i→ji \to j from a symmetric proposal qij=qjiq_{ij} = q_{ji} and accepts it with probability min⁡(1,πj/πi)\min(1, \pi_j/\pi_i). The resulting chain satisfies detailed balance with π\pi — only ratios πj/πi\pi_j/\pi_i are needed — so if it is irreducible and aperiodic, its distribution converges to π\pi, and ergodic averages estimate expectations under π\pi. How fast it mixes is the hard part.

Genetic drift. In the Wright–Fisher model, a population carries NN copies of a gene, XnX_n of them of type A. Each copy in the next generation picks its parent uniformly at random, so Xn+1X_{n+1} given Xn=iX_n = i is Binomial(N,i/N)(N, i/N). The states 00 and NN are absorbing, all others transient, so one type is eventually lost. Since E[Xn+1∣Xn]=XnE[X_{n+1} \mid X_n] = X_n (the chain is a martingale), the probability that type A takes over is X0/NX_0/N — a neutral mutation present in one copy fixes with probability 1/N1/N. Selection and mutation modify the transition probabilities; see mathematical biology.

Formal mathematicsF

Markov chains in Lean and Mathlib

A finite chain is a matrix P : Matrix S S ℝ over a finite type S; a distribution is a row vector μ : S → ℝ, and one step is μ ᵥ* P. Mathlib provides the submonoid Matrix.rowStochastic ℝ S of stochastic matrices with its basic lemmas, and the general theory of Markov kernels on measurable spaces (ProbabilityTheory.Kernel, with irreducibility in Kernel.IsIrreducible). Classification of states, the strong Markov property and the ergodic theorem for chains are not yet in Mathlib.

Transition matrices. Products and powers of stochastic matrices are stochastic, and one step maps distributions to distributions:

stochastic_mulLean 4Proved here from basic factsFormally verified
/-- **The product of two transition matrices is a transition matrix.** If `P` and `Q` have
non-negative entries and rows summing to `1`, so does `PQ`: its entries `∑ₖ Pᵢₖ Qₖⱼ` are sums
of non-negative terms, and its row sums are
`∑ⱼ ∑ₖ Pᵢₖ Qₖⱼ = ∑ₖ Pᵢₖ ∑ⱼ Qₖⱼ = ∑ₖ Pᵢₖ = 1`. By Chapman–Kolmogorov, `PQ` is "first a step of
`P`, then a step of `Q`". -/
theorem stochastic_mul {P Q : Matrix S S ℝ}
    (hP : (∀ i j, 0 ≤ P i j) ∧ ∀ i, ∑ j, P i j = 1)
    (hQ : (∀ i j, 0 ≤ Q i j) ∧ ∀ i, ∑ j, Q i j = 1) :
    (∀ i j, 0 ≤ (P * Q) i j) ∧ ∀ i, ∑ j, (P * Q) i j = 1 := by
  refine ⟨fun i j => ?_, fun i => ?_⟩
  · rw [mul_apply]
    exact sum_nonneg fun k _ => mul_nonneg (hP.1 i k) (hQ.1 k j)
  · simp only [mul_apply]
    rw [sum_comm]
    simp only [← mul_sum, hQ.2, mul_one]
    exact hP.2 i
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
stochastic_powLean 4Applies a library theoremFormally verified
/-- **n-step transition matrices are stochastic.** Mathlib's `Matrix.rowStochastic ℝ S` is a
submonoid of the matrix monoid, so it contains every power `Pⁿ` of its elements
(`Submonoid.pow_mem`). The entry `(Pⁿ)ᵢⱼ` is the probability of being at `j` after `n` steps
from `i`. -/
theorem stochastic_pow [DecidableEq S] {P : Matrix S S ℝ} (hP : P ∈ rowStochastic ℝ S) (n : ℕ) :
    P ^ n ∈ rowStochastic ℝ S :=
  Submonoid.pow_mem _ hP n
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
distribution_stepLean 4Applies a library theoremFormally verified
/-- **One step of the chain maps distributions to distributions.** If `μ ≥ 0` sums to `1`, so
does `μ P`. These are Mathlib's `nonneg_vecMul_of_mem_rowStochastic` and
`vecMul_dotProduct_one_eq_one_rowStochastic` (`x ⬝ᵥ 1` is the sum of the entries of `x`). -/
theorem distribution_step [DecidableEq S] {P : Matrix S S ℝ} (hP : P ∈ rowStochastic ℝ S) {μ : S → ℝ}
    (hμ0 : ∀ i, 0 ≤ μ i) (hμ1 : μ ⬝ᵥ 1 = 1) :
    (∀ j, 0 ≤ (μ ᵥ* P) j) ∧ (μ ᵥ* P) ⬝ᵥ 1 = 1 :=
  ⟨nonneg_vecMul_of_mem_rowStochastic hP hμ0, vecMul_dotProduct_one_eq_one_rowStochastic hP hμ1⟩
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor

Stationarity. Detailed balance implies stationarity, on any finite state space:

detailed_balance_stationaryLean 4Proved here from basic factsFormally verified
/-- **Detailed balance implies stationarity.** If `πᵢ Pᵢⱼ = πⱼ Pⱼᵢ` for all states (the flow
of probability from `i` to `j` equals the flow back), and the rows of `P` sum to `1`, then
`π P = π`. Proof: `(πP)ⱼ = ∑ᵢ πᵢ Pᵢⱼ = ∑ᵢ πⱼ Pⱼᵢ = πⱼ ∑ᵢ Pⱼᵢ = πⱼ`. -/
theorem detailed_balance_stationary {P : Matrix S S ℝ} (hrow : ∀ i, ∑ j, P i j = 1)
    {π : S → ℝ} (hdb : ∀ i j, π i * P i j = π j * P j i) : π ᵥ* P = π := by
  funext j
  simp only [vecMul, dotProduct]
  simp_rw [hdb _ j]
  rw [← mul_sum, hrow j, mul_one]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor

The two-state chain, its stationary distribution, the closed form of PnP^n by induction, and convergence of (Pn)00(P^n)_{00} to π0\pi_0:

twoStateLean 4Formally verified
/-- The general **two-state chain**: from state `0` jump with probability `a`, from state `1`
jump back with probability `b`. -/
def twoState (a b : ℝ) : Matrix (Fin 2) (Fin 2) ℝ :=
  !![1 - a, a; b, 1 - b]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
two_state_stationaryLean 4Proved here from basic factsFormally verified
/-- The two-state chain (with `a + b ≠ 0`) has stationary distribution
`π = (b/(a + b), a/(a + b))`: a direct computation of `π P`. -/
theorem two_state_stationary {a b : ℝ} (hab : a + b ≠ 0) :
    ![b / (a + b), a / (a + b)] ᵥ* twoState a b = ![b / (a + b), a / (a + b)] := by
  funext j
  fin_cases j <;>
  · simp [twoState, vecMul, dotProduct, Fin.sum_univ_two]
    field_simp
    ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
two_state_powLean 4Proved here from basic factsFormally verified
/-- **The n-step matrix of the two-state chain.** With `λ = 1 − a − b` (the second eigenvalue),
`(a + b) Pⁿ = [[b + a λⁿ, a − a λⁿ], [b − b λⁿ, a + b λⁿ]]`. Each row is the stationary
distribution plus a correction that decays like `λⁿ`. Proof: induction on `n`, using
`Pⁿ⁺¹ = Pⁿ P`. -/
theorem two_state_pow (a b : ℝ) (n : ℕ) :
    (a + b) • twoState a b ^ n =
      !![b + a * (1 - a - b) ^ n, a - a * (1 - a - b) ^ n;
         b - b * (1 - a - b) ^ n, a + b * (1 - a - b) ^ n] := by
  induction n with
  | zero =>
    ext i j
    fin_cases i <;> fin_cases j <;> simp [add_comm]
  | succ n ih =>
    rw [pow_succ, ← smul_mul_assoc, ih]
    ext i j
    fin_cases i <;> fin_cases j <;>
    · simp [twoState, mul_apply, Fin.sum_univ_two]
      ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
two_state_convergesLean 4Proved here from basic factsFormally verified
/-- **Convergence to equilibrium for two states.** If `|1 − a − b| < 1` (true whenever
`0 < a, b` and `a + b < 2`, i.e. the chain is irreducible and aperiodic), then the probability
of being in state `0` after `n` steps from state `0` tends to `π₀ = b/(a + b)`. Proof: by
`two_state_pow`, `(Pⁿ)₀₀ = (b + a λⁿ)/(a + b)` and `λⁿ → 0`. -/
theorem two_state_converges {a b : ℝ} (hab : a + b ≠ 0) (hlam : |1 - a - b| < 1) :
    Tendsto (fun n : ℕ => (twoState a b ^ n) 0 0) atTop (𝓝 (b / (a + b))) := by
  have hentry : ∀ n : ℕ, (twoState a b ^ n) 0 0 = (b + a * (1 - a - b) ^ n) / (a + b) := by
    intro n
    have h := congrFun (congrFun (two_state_pow a b n) 0) 0
    have h' : (a + b) * (twoState a b ^ n) 0 0 = b + a * (1 - a - b) ^ n := by
      simpa [Matrix.smul_apply] using h
    rw [eq_div_iff hab, mul_comm]
    exact h'
  simp_rw [hentry]
  have hpow : Tendsto (fun n : ℕ => (1 - a - b) ^ n) atTop (𝓝 0) :=
    tendsto_pow_atTop_nhds_zero_of_abs_lt_one hlam
  have := ((hpow.const_mul a).const_add b).div_const (a + b)
  simpa using this
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor

Gambler's ruin. The fair solution and its uniqueness, the biased solution, and the expected duration:

gambler_fair_solvesLean 4Proved here from basic factsFormally verified
/-- **Fair gambler's ruin.** Starting with `i` coins and betting one coin on fair coin flips
until reaching `0` or `N`, the probability `h(i)` of reaching `N` satisfies the first-step
equations `h(i) = ½ h(i − 1) + ½ h(i + 1)` with `h(0) = 0`, `h(N) = 1`. The function
`h(i) = i/N` is a solution. -/
theorem gambler_fair_solves {N : ℕ} (hN : 0 < N) (i : ℕ) :
    ((i + 1 : ℕ) : ℝ) / N = 1 / 2 * ((i : ℝ) / N) + 1 / 2 * (((i + 2 : ℕ) : ℝ) / N) := by
  have : (N : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hN.ne'
  push_cast
  field_simp
  ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
gambler_fair_uniqueLean 4Proved here from basic factsFormally verified
/-- **…and it is the only solution.** If `h(0) = 0`, `h(N) = 1` and
`h(i + 1) = 2h(i) − h(i − 1)` for `0 < i < N` (the first-step equation rearranged), then
`h(i) = i/N` for all `i ≤ N`. Proof: the increments `h(i + 1) − h(i)` are all equal, so
`h(i) = i·h(1)` by induction, and `h(N) = 1` forces `h(1) = 1/N`. -/
theorem gambler_fair_unique {N : ℕ} (hN : 0 < N) (h : ℕ → ℝ) (h0 : h 0 = 0) (hNv : h N = 1)
    (hrec : ∀ i, 0 < i → i < N → h (i + 1) = 2 * h i - h (i - 1)) :
    ∀ i ≤ N, h i = i / N := by
  -- First, `h i = i * h 1` for `i ≤ N`, proved together with the next value.
  have key : ∀ i, i + 1 ≤ N → h i = i * h 1 ∧ h (i + 1) = (i + 1) * h 1 := by
    intro i
    induction i with
    | zero => intro _; simp [h0]
    | succ k ih =>
      intro hk
      obtain ⟨h1, h2⟩ := ih (by omega)
      refine ⟨by push_cast; exact h2, ?_⟩
      have := hrec (k + 1) (by omega) (by omega)
      rw [this, show k + 1 - 1 = k by omega, h1, h2]
      push_cast
      ring
  have hNR : (N : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hN.ne'
  have hN1 : h 1 = 1 / N := by
    obtain ⟨_, hlast⟩ := key (N - 1) (by omega)
    rw [show N - 1 + 1 = N by omega, hNv] at hlast
    have : ((N - 1 : ℕ) : ℝ) + 1 = N := by
      rw [Nat.cast_sub (by omega)]
      push_cast
      ring
    rw [this] at hlast
    field_simp
    linarith
  intro i hi
  rcases Nat.lt_or_ge i N with hlt | hge
  · rw [(key i (by omega)).1, hN1]
    ring
  · rw [show i = N by omega, hNv]
    field_simp
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
gambler_biased_solvesLean 4Proved here from basic factsFormally verified
/-- **Biased gambler's ruin.** If each bet is won with probability `p` and lost with
probability `q = 1 − p`, with `r = q/p ≠ 1`, the probability of reaching `N` from `i` is
`h(i) = (1 − rⁱ)/(1 − rᴺ)`: it satisfies `h(i + 1) = p h(i + 2) + q h(i)` (first-step
analysis from `i + 1`), together with `h(0) = 0` and `h(N) = 1`. -/
theorem gambler_biased_solves {p : ℝ} (hp0 : 0 < p) (hp1 : p < 1) (hr : (1 - p) / p ≠ 1) {N : ℕ}
    (hN : 0 < N) (i : ℕ) :
    let r := (1 - p) / p
    let h : ℕ → ℝ := fun k => (1 - r ^ k) / (1 - r ^ N)
    h 0 = 0 ∧ h N = 1 ∧ h (i + 1) = p * h (i + 2) + (1 - p) * h i := by
  intro r h
  have hrpos : 0 ≤ r := div_nonneg (by linarith) hp0.le
  have hrN : 1 - r ^ N ≠ 0 := by
    intro h0
    have hr1 : r ^ N = 1 := by linarith
    exact hr ((pow_eq_one_iff_of_nonneg hrpos hN.ne').mp hr1)
  refine ⟨by simp [h], by simp [h, div_self hrN], ?_⟩
  have hq : 1 - p = r * p := by
    simp only [r]
    field_simp
  have key : p * (1 - r ^ (i + 2)) + (1 - p) * (1 - r ^ i) = 1 - r ^ (i + 1) := by
    linear_combination (r ^ i * (r - 1)) * hq
  simp only [h]
  rw [show p * ((1 - r ^ (i + 2)) / (1 - r ^ N)) + (1 - p) * ((1 - r ^ i) / (1 - r ^ N)) =
      (p * (1 - r ^ (i + 2)) + (1 - p) * (1 - r ^ i)) / (1 - r ^ N) by ring, key]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
duration_fair_solvesLean 4Proved here from basic factsFormally verified
/-- **Expected duration of the fair game.** The expected number of bets `m(i)` until the
fair game ends satisfies `m(i) = 1 + ½ m(i − 1) + ½ m(i + 1)` with `m(0) = m(N) = 0`, and
`m(i) = i (N − i)` is a solution (shown here at `i + 1` for all `i`). Starting with `10`
coins and stopping at `0` or `20` takes `100` bets on average. -/
theorem duration_fair_solves (N i : ℝ) :
    (i + 1) * (N - (i + 1)) = 1 + 1 / 2 * (i * (N - i)) + 1 / 2 * ((i + 2) * (N - (i + 2))) := by
  ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor

Doeblin's contraction — Lemma 3 of the convergence theorem — and its iteration, which gives the geometric rate once some power of PP is positive:

zero_sum_vecMulLean 4Proved here from basic factsFormally verified
/-- A step of a stochastic matrix preserves zero-sum vectors (such as the difference `μ − ν`
of two distributions): `∑ⱼ (xP)ⱼ = ∑ᵢ xᵢ ∑ⱼ Pᵢⱼ = ∑ᵢ xᵢ`. -/
theorem zero_sum_vecMul {P : Matrix S S ℝ} (hrow : ∀ i, ∑ j, P i j = 1) {x : S → ℝ}
    (hx : ∑ i, x i = 0) : ∑ j, (x ᵥ* P) j = 0 := by
  simp only [vecMul, dotProduct]
  rw [sum_comm]
  simp only [← mul_sum, hrow, mul_one]
  exact hx
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
doeblin_contractionLean 4Proved here from basic factsFormally verified
/-- **Doeblin's contraction.** Let `P` be stochastic with every entry at least `δ`, on a state
space with `k` states. Then for every zero-sum vector `x`, `‖xP‖₁ ≤ (1 − kδ)‖x‖₁`.
Proof: since `∑ᵢ xᵢ = 0`, `(xP)ⱼ = ∑ᵢ xᵢ (Pᵢⱼ − δ)` with `Pᵢⱼ − δ ≥ 0`, so
`∑ⱼ |(xP)ⱼ| ≤ ∑ᵢ |xᵢ| ∑ⱼ (Pᵢⱼ − δ) = (1 − kδ) ∑ᵢ |xᵢ|`. Applied to `x = μ − ν`, two
distributions are pulled together by a factor `1 − kδ < 1` at every step. -/
theorem doeblin_contraction {P : Matrix S S ℝ} (hrow : ∀ i, ∑ j, P i j = 1) {δ : ℝ}
    (hδ : ∀ i j, δ ≤ P i j) {x : S → ℝ} (hx : ∑ i, x i = 0) :
    ∑ j, |(x ᵥ* P) j| ≤ (1 - Fintype.card S * δ) * ∑ i, |x i| := by
  have hshift : ∀ j, (x ᵥ* P) j = ∑ i, x i * (P i j - δ) := by
    intro j
    simp only [vecMul, dotProduct, mul_sub, sum_sub_distrib, ← sum_mul, hx, zero_mul, sub_zero]
  calc ∑ j, |(x ᵥ* P) j| = ∑ j, |∑ i, x i * (P i j - δ)| := by simp_rw [hshift]
    _ ≤ ∑ j, ∑ i, |x i| * (P i j - δ) := by
        apply sum_le_sum
        intro j _
        refine (abs_sum_le_sum_abs _ _).trans (le_of_eq ?_)
        refine sum_congr rfl fun i _ => ?_
        rw [abs_mul, abs_of_nonneg (sub_nonneg.mpr (hδ i j))]
    _ = ∑ i, |x i| * ∑ j, (P i j - δ) := by
        rw [sum_comm]
        simp only [mul_sum]
    _ = (1 - Fintype.card S * δ) * ∑ i, |x i| := by
        simp only [sum_sub_distrib, hrow, sum_const, card_univ, nsmul_eq_mul]
        rw [mul_sum]
        exact sum_congr rfl fun i _ => by ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
doeblin_iterateLean 4Proved here from basic factsFormally verified
/-- **Geometric convergence.** Iterating Doeblin's contraction (zero-sum vectors stay
zero-sum): `‖x Pⁿ‖₁ ≤ (1 − kδ)ⁿ ‖x‖₁`. With `x = μ − π` for a stationary `π`, the distribution
at time `n` approaches `π` exponentially fast. For a general irreducible aperiodic chain, apply
this to a power `Pᴺ` whose entries are all positive. -/
theorem doeblin_iterate [DecidableEq S] {P : Matrix S S ℝ} (hrow : ∀ i, ∑ j, P i j = 1) {δ : ℝ}
    (hδ : ∀ i j, δ ≤ P i j) (hkδ : Fintype.card S * δ ≤ 1) {x : S → ℝ} (hx : ∑ i, x i = 0)
    (n : ℕ) : ∑ j, |(x ᵥ* P ^ n) j| ≤ (1 - Fintype.card S * δ) ^ n * ∑ i, |x i| := by
  have hz : ∀ m : ℕ, ∑ i, (x ᵥ* P ^ m) i = 0 := by
    intro m
    induction m with
    | zero => simpa using hx
    | succ m ihm =>
      rw [pow_succ, ← vecMul_vecMul]
      exact zero_sum_vecMul hrow ihm
  induction n with
  | zero => simp
  | succ n ih =>
    have hzero := hz n
    rw [pow_succ, ← vecMul_vecMul]
    calc ∑ j, |((x ᵥ* P ^ n) ᵥ* P) j| ≤ (1 - Fintype.card S * δ) * ∑ i, |(x ᵥ* P ^ n) i| :=
          doeblin_contraction hrow hδ hzero
      _ ≤ (1 - Fintype.card S * δ) * ((1 - Fintype.card S * δ) ^ n * ∑ i, |x i|) :=
          mul_le_mul_of_nonneg_left ih (by linarith)
      _ = (1 - Fintype.card S * δ) ^ (n + 1) * ∑ i, |x i| := by ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor

Pólya in dimensions one and two. The bound 4n≤(2n+1)(2nn)4^n \le (2n + 1)\binom{2n}{n} from Mathlib, the divergence of ∑nan\sum_n a_n, the sharper bound an2≥14na_n^2 \ge \frac1{4n}, and the divergence of ∑nan2\sum_n a_n^2:

central_binom_lowerLean 4Applies a library theoremFormally verified
/-- `4ⁿ ≤ (2n + 1) C(2n, n)`: the middle binomial coefficient is the largest of the `2n + 1`
coefficients `C(2n, k)`, which add up to `4ⁿ`. This is Mathlib's
`Nat.four_pow_le_two_mul_add_one_mul_centralBinom`. Since simple random walk on `ℤ` is back at
`0` at time `2n` with probability `C(2n, n)/4ⁿ`, that probability is at least `1/(2n + 1)`. -/
theorem central_binom_lower (n : ℕ) : 4 ^ n ≤ (2 * n + 1) * n.centralBinom :=
  Nat.four_pow_le_two_mul_add_one_mul_centralBinom n
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
walk_1d_returns_divergeLean 4Proved here from basic factsFormally verified
/-- **Simple random walk on `ℤ` is recurrent.** The expected number of returns to `0` is
`∑ₙ P(S₂ₙ = 0) = ∑ₙ C(2n, n)/4ⁿ`, and this series diverges: each term is at least
`1/(2n + 1) ≥ 1/(2(n + 1))`, and the harmonic series diverges. By the recurrence criterion
(infinitely many expected returns ⇔ recurrent), the walk returns with probability `1`. -/
theorem walk_1d_returns_diverge :
    ¬ Summable (fun n : ℕ => (n.centralBinom : ℝ) / 4 ^ n) := by
  intro hsum
  -- Compare with `1/(2(n + 1))`.
  have hle : ∀ n : ℕ, 1 / (2 * ((n : ℝ) + 1)) ≤ (n.centralBinom : ℝ) / 4 ^ n := by
    intro n
    have h := central_binom_lower n
    have h' : (4 : ℝ) ^ n ≤ (2 * n + 1) * n.centralBinom := by exact_mod_cast h
    rw [div_le_div_iff₀ (by positivity) (by positivity)]
    nlinarith [pow_pos (show (0 : ℝ) < 4 by norm_num) n,
      (Nat.cast_nonneg n.centralBinom : (0 : ℝ) ≤ _)]
  have h2 : Summable (fun n : ℕ => 1 / (2 * ((n : ℝ) + 1))) :=
    Summable.of_nonneg_of_le (fun n => by positivity) hle hsum
  have h3 : Summable (fun n : ℕ => 1 / ((n + 1 : ℕ) : ℝ)) := by
    have := h2.mul_left 2
    refine this.congr fun n => ?_
    push_cast
    field_simp
  exact Real.not_summable_one_div_natCast ((summable_nat_add_iff 1).mp h3)
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
central_binom_sq_lowerLean 4Proved here from basic factsFormally verified
/-- `(C(2n, n)/4ⁿ)² ≥ 1/(4n)` for `n ≥ 1`. Proof by induction: `aₙ = C(2n, n)/4ⁿ` satisfies
`aₙ₊₁ = aₙ (2n + 1)/(2n + 2)` (Mathlib's `Nat.succ_mul_centralBinom_succ`), and
`(2n + 1)² ≥ 4n(n + 1)`. This sharper bound is what dimension two needs. -/
theorem central_binom_sq_lower (n : ℕ) (hn : 1 ≤ n) :
    1 ≤ 4 * (n : ℝ) * ((n.centralBinom : ℝ) / 4 ^ n) ^ 2 := by
  induction n, hn using Nat.le_induction with
  | base => norm_num [Nat.centralBinom, Nat.choose]
  | succ k hk ih =>
    set a := (k.centralBinom : ℝ) / 4 ^ k
    have hrec : ((k + 1).centralBinom : ℝ) / 4 ^ (k + 1) = a * (2 * k + 1) / (2 * k + 2) := by
      have h := Nat.succ_mul_centralBinom_succ k
      have h' : ((k : ℝ) + 1) * (k + 1).centralBinom = 2 * (2 * k + 1) * k.centralBinom := by
        exact_mod_cast h
      have hk1 : (k : ℝ) + 1 ≠ 0 := by positivity
      simp only [a]
      rw [pow_succ]
      field_simp
      have : ((k + 1).centralBinom : ℝ) = 2 * (2 * k + 1) * k.centralBinom / (k + 1) := by
        field_simp
        linarith
      rw [this]
      field_simp
      ring
    rw [hrec]
    have hkR : (1 : ℝ) ≤ k := by exact_mod_cast hk
    have hsq : 4 * (k : ℝ) * (k + 1) ≤ (2 * k + 1) ^ 2 := by nlinarith
    have hpos : (0 : ℝ) < 2 * k + 2 := by positivity
    push_cast
    have hsimp : 4 * ((k : ℝ) + 1) * (a * (2 * k + 1) / (2 * k + 2)) ^ 2 =
        a ^ 2 * (2 * k + 1) ^ 2 / (k + 1) := by
      field_simp
      ring
    rw [hsimp, le_div_iff₀ (by positivity)]
    have hchain : (2 * (k : ℝ) + 1) ^ 2 ≤ (2 * k + 1) ^ 2 * (4 * k * a ^ 2) := by
      nlinarith [sq_nonneg (2 * (k : ℝ) + 1)]
    nlinarith [hchain, hsq, hkR]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor
walk_2d_returns_divergeLean 4Proved here from basic factsFormally verified
/-- **Simple random walk on `ℤ²` is recurrent.** Rotating the lattice by 45° turns the planar
walk into two independent walks on `ℤ` (the coordinates `x + y` and `x − y`), so
`P(S₂ₙ = 0) = (C(2n, n)/4ⁿ)²`. These probabilities are not summable: from `n = 1` on they are
at least `1/(4n)`. (The rotation argument itself is in the lesson, not formalised.) -/
theorem walk_2d_returns_diverge :
    ¬ Summable (fun n : ℕ => ((n.centralBinom : ℝ) / 4 ^ n) ^ 2) := by
  intro hsum
  have hshift := (summable_nat_add_iff 1).mpr hsum
  have hle : ∀ n : ℕ, 1 / 4 * (1 / ((n + 1 : ℕ) : ℝ)) ≤
      (((n + 1).centralBinom : ℝ) / 4 ^ (n + 1)) ^ 2 := by
    intro n
    have h := central_binom_sq_lower (n + 1) (by omega)
    have hn : (0 : ℝ) < ((n + 1 : ℕ) : ℝ) := by positivity
    rw [show 1 / 4 * (1 / ((n + 1 : ℕ) : ℝ)) = 1 / (4 * ((n + 1 : ℕ) : ℝ)) by field_simp]
    rw [div_le_iff₀ (by positivity)]
    linarith
  have h2 : Summable (fun n : ℕ => 1 / 4 * (1 / ((n + 1 : ℕ) : ℝ))) :=
    Summable.of_nonneg_of_le (fun n => by positivity) hle hshift
  have h3 : Summable (fun n : ℕ => 1 / ((n + 1 : ℕ) : ℝ)) :=
    (summable_mul_left_iff (by norm_num : (1 / 4 : ℝ) ≠ 0)).mp h2
  exact Real.not_summable_one_div_natCast ((summable_nat_add_iff 1).mp h3)
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/MarkovChains.leanTry it in the Lean web editor

What is and is not formalised. Proved here: stochasticity of products, detailed balance ⇒ stationarity, everything about the two-state chain, the gambler's-ruin formulas (and uniqueness in the fair case), Doeblin's contraction and its iteration, and the divergence of the expected number of returns in d=1,2d = 1, 2 (as statements about the series ∑an\sum a_n and ∑an2\sum a_n^2). Cited from Mathlib: powers of stochastic matrices, one-step preservation of distributions, and the central binomial bound. Not formalised: the identification of ana_n and an2a_n^2 as return probabilities (including the 45°45° rotation), the recurrence criterion, transience in d=3d = 3, existence and uniqueness of stationary distributions, Lemmas 1 and 2, and the ergodic theorem.

ComputationC

Equilibrium, ruin and returns, computed

First, convergence to equilibrium: the exact stationary distribution of a three-state weather chain, the total-variation distance to it day by day, the eigenvalue rate and Doeblin's bound — and a periodic chain that never settles.

Convergence to equilibrium, eigenvalues and Doeblin's boundPythonExact computationNumerical approximationComputationally tested
"""Convergence to equilibrium: a weather chain forgets where it started.

A three-state chain (dry, cloudy, rainy) has a strictly positive transition
matrix, so it is irreducible and aperiodic. We find its stationary
distribution exactly (rational arithmetic), then follow the distribution mu P^n
from a dry start and measure its total-variation distance to pi. The distance
falls geometrically, at the rate |lambda_2| of the second-largest eigenvalue,
and always below Doeblin's bound (1 - k delta)^n. A periodic chain, by
contrast, never settles down; making it "lazy" restores convergence.
"""

from fractions import Fraction

import numpy as np

STATES = ["dry", "cloudy", "rainy"]
WEATHER = [["3/5", "3/10", "1/10"],
           ["3/10", "2/5", "3/10"],
           ["1/5", "3/10", "1/2"]]

def as_fractions(matrix):
    """Convert a matrix of strings or numbers into Fractions."""
    return [[Fraction(x) for x in row] for row in matrix]

def is_stochastic(matrix):
    """True if all entries are non-negative and every row sums to 1."""
    return all(min(row) >= 0 and sum(row) == 1 for row in matrix)

def stationary_exact(matrix):
    """Solve pi P = pi, sum(pi) = 1 exactly by Gauss-Jordan elimination.

    The equations are pi (P - I) = 0 with one equation replaced by the
    normalisation; for an irreducible chain the solution is unique.
    """
    p = as_fractions(matrix)
    k = len(p)
    # Unknowns pi_0..pi_{k-1}; equation j: sum_i pi_i (P_ij - [i = j]) = 0.
    rows = [[p[i][j] - (1 if i == j else 0) for i in range(k)] + [Fraction(0)]
            for j in range(k)]
    rows[-1] = [Fraction(1)] * k + [Fraction(1)]
    for col in range(k):
        pivot = next(r for r in range(col, k) if rows[r][col] != 0)
        rows[col], rows[pivot] = rows[pivot], rows[col]
        rows[col] = [x / rows[col][col] for x in rows[col]]
        for r in range(k):
            if r != col and rows[r][col] != 0:
                factor = rows[r][col]
                rows[r] = [a - factor * b for a, b in zip(rows[r], rows[col])]
    return [rows[i][k] for i in range(k)]

def tv_distance(mu, nu):
    """Total-variation distance: half the l1 distance."""
    return 0.5 * float(np.abs(np.asarray(mu) - np.asarray(nu)).sum())

def distances(matrix, start, steps):
    """[TV(mu P^n, pi) for n = 0..steps] with mu = the point mass at start."""
    p = np.array([[float(x) for x in row] for row in as_fractions(matrix)])
    pi = np.array([float(x) for x in stationary_exact(matrix)])
    mu = np.zeros(len(p))
    mu[start] = 1.0
    out = []
    for _ in range(steps + 1):
        out.append(tv_distance(mu, pi))
        mu = mu @ p
    return out

def second_eigenvalue(matrix):
    """Largest modulus among the eigenvalues other than 1."""
    p = np.array([[float(x) for x in row] for row in as_fractions(matrix)])
    moduli = sorted(np.abs(np.linalg.eigvals(p)), reverse=True)
    return float(moduli[1])

def main():
    pi = stationary_exact(WEATHER)
    print("Weather chain: stationary distribution (exact)")
    print("  " + ", ".join(f"{s} {x}" for s, x in zip(STATES, pi)))
    lam2 = second_eigenvalue(WEATHER)
    delta = min(min(as_fractions(WEATHER)[i]) for i in range(3))
    factor = 1 - 3 * float(delta)
    print(f"  |lambda_2| = {lam2:.4f}; Doeblin factor 1 - k delta = {factor:.2f}")
    print()
    print("  n   TV(mu P^n, pi)   |lambda_2|^n   Doeblin bound")
    tv = distances(WEATHER, 0, 12)
    for n in [0, 1, 2, 4, 6, 8, 10, 12]:
        print(f"{n:>3} {tv[n]:>16.2e} {lam2 ** n:>14.2e} {factor ** n:>15.2e}")
    print()
    flip = [[0, 1], [1, 0]]
    lazy = [["1/2", "1/2"], ["1/2", "1/2"]]
    print("Periodic chain [[0, 1], [1, 0]] from state 0:",
          [round(d, 2) for d in distances(flip, 0, 5)])
    print("Lazy version (I + P)/2 from state 0:        ",
          [round(d, 2) for d in distances(lazy, 0, 5)])
    print()
    print("Epistemic status: pi is exact. The distances are floating-point")
    print("values for one chain and one starting state; they illustrate the")
    print("convergence theorem, the spectral rate and Doeblin's bound (proved")
    print("in Lean), and the failure of convergence for a periodic chain.")

if __name__ == "__main__":
    main()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Next, gambler's ruin: the first-step equations solved in exact arithmetic, checked against the closed forms and against simulated games, for a fair coin and for betting on red at roulette.

Gambler's ruin: exact first-step analysis versus simulationPythonExact computationStatistical evidenceComputationally tested
"""Gambler's ruin: first-step analysis solved exactly, then checked by simulation.

A gambler with i coins bets one coin at a time, winning with probability p,
until she has N coins or none. The probability h(i) of reaching N and the
expected duration m(i) satisfy linear "first-step" equations. We solve these
tridiagonal systems exactly with fractions, compare with the closed-form
answers from the lesson, and then simulate the game. A fair game (p = 1/2) and
a slightly unfavourable one (p = 18/38, betting on red in roulette) behave
very differently.
"""

import random
from fractions import Fraction

def solve_tridiagonal(lower, diag, upper, rhs):
    """Solve a tridiagonal system exactly (Thomas algorithm with Fractions)."""
    n = len(diag)
    c, d = [Fraction(0)] * n, [Fraction(0)] * n
    c[0] = Fraction(upper[0]) / diag[0] if n > 1 else Fraction(0)
    d[0] = Fraction(rhs[0]) / diag[0]
    for i in range(1, n):
        denom = diag[i] - lower[i] * c[i - 1]
        c[i] = Fraction(upper[i]) / denom if i < n - 1 else Fraction(0)
        d[i] = (rhs[i] - lower[i] * d[i - 1]) / denom
    x = [Fraction(0)] * n
    x[-1] = d[-1]
    for i in range(n - 2, -1, -1):
        x[i] = d[i] - c[i] * x[i + 1]
    return x

def first_step(p, n_target, durations=False):
    """Exact h(i) (or m(i)) for i = 0..N from the first-step equations.

    For 0 < i < N: h(i) = p h(i+1) + q h(i-1), with h(0) = 0, h(N) = 1;
    m(i) = 1 + p m(i+1) + q m(i-1), with m(0) = m(N) = 0.
    """
    p = Fraction(p)
    q = 1 - p
    k = n_target - 1  # unknowns at 1..N-1
    lower = [-q] * k
    diag = [Fraction(1)] * k
    upper = [-p] * k
    if durations:
        rhs = [Fraction(1)] * k
    else:
        rhs = [Fraction(0)] * k
        rhs[-1] = p  # the term p h(N) = p moved to the right-hand side
    inner = solve_tridiagonal(lower, diag, upper, rhs)
    boundary = Fraction(0) if durations else Fraction(1)
    return [Fraction(0)] + inner + [boundary]

def ruin_formula(p, i, n_target):
    """Closed form: i/N if p = 1/2, else (1 - r^i)/(1 - r^N) with r = q/p."""
    p = Fraction(p)
    if p == Fraction(1, 2):
        return Fraction(i, n_target)
    r = (1 - p) / p
    return (1 - r ** i) / (1 - r ** n_target)

def simulate(p, i, n_target, games, rng):
    """Fraction of games reaching N, and the mean number of bets."""
    wins = total = 0
    for _ in range(games):
        x, steps = i, 0
        while 0 < x < n_target:
            x += 1 if rng.random() < p else -1
            steps += 1
        wins += x == n_target
        total += steps
    return wins / games, total / games

def main():
    rng = random.Random(1654)
    n_target, start, games = 20, 10, 4000
    print(f"Start with {start} coins, stop at 0 or {n_target};"
          f" {games} simulated games each")
    for label, p in [("fair coin, p = 1/2", Fraction(1, 2)),
                     ("roulette red, p = 18/38", Fraction(18, 38))]:
        h = first_step(p, n_target)
        m = first_step(p, n_target, durations=True)
        assert h[start] == ruin_formula(p, start, n_target)
        sim_h, sim_m = simulate(float(p), start, n_target, games, rng)
        print(f"{label}:")
        print(f"  P(reach {n_target}): exact {float(h[start]):.4f}"
              f" (formula agrees), simulated {sim_h:.4f}")
        print(f"  expected bets:  exact {float(m[start]):.2f},"
              f" simulated {sim_m:.2f}")
    print()
    fair_m = first_step(Fraction(1, 2), n_target, durations=True)
    ok = all(fair_m[i] == i * (n_target - i) for i in range(n_target + 1))
    print(f"Fair game: m(i) = i (N - i) for every i = 0..{n_target}: {ok}")
    print("A house edge of 1/19 per bet cuts the chance of doubling 10 coins")
    print("from 1/2 to about 1/4.")
    print()
    print("Epistemic status: the first-step solutions are exact rational")
    print("numbers and agree with the closed forms for these parameters; the")
    print("simulated frequencies are statistical evidence (standard error")
    print("about 0.008 for the probabilities).")

if __name__ == "__main__":
    main()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Finally, Pólya's theorem in numbers: partial sums of return probabilities in one, two and three dimensions, and the fraction of simulated walks that come home.

Polya's theorem: return probabilities in one, two and three dimensionsPythonNumerical approximationStatistical evidenceComputationally tested
"""Polya's theorem in numbers: does a random walk come home?

Simple random walk on Z^d returns to the origin with probability 1 when
d = 1 or 2 and with probability less than 1 when d = 3. The criterion is
whether the expected number of returns, sum_n P(S_2n = 0), is infinite. We
compute these return probabilities: exactly from C(2n, n)/4^n in d = 1 and its
square in d = 2, and from the trinomial formula in d = 3. The partial sums
grow like sqrt(n) and log(n) in d = 1 and 2, but level off in d = 3. A numpy
simulation of 1,000 walks of 1,000 steps adds the fraction that came back.
"""

import math

import numpy as np

def return_probs_1d(n_max):
    """[P(S_2n = 0) for n = 0..n_max] in d = 1, via a_(n+1) = a_n (2n+1)/(2n+2)."""
    a = [1.0]
    for n in range(n_max):
        a.append(a[-1] * (2 * n + 1) / (2 * n + 2))
    return a

def return_prob_3d(n):
    """P(S_2n = 0) in d = 3: (1/6^(2n)) C(2n, n) sum_(i+j+k=n) (n!/(i! j! k!))^2.

    Computed with logarithms of factorials (math.lgamma).
    """
    lf = [math.lgamma(m + 1) for m in range(2 * n + 1)]
    log_c = lf[2 * n] - 2 * lf[n]
    total = 0.0
    for i in range(n + 1):
        for j in range(n - i + 1):
            k = n - i - j
            total += math.exp(2 * (lf[n] - lf[i] - lf[j] - lf[k])
                              + log_c - 2 * n * math.log(6))
    return total

def simulate_returns(d, walks=1000, steps=1000, seed=1921):
    """Fraction of walks in Z^d that revisit the origin within ``steps``."""
    rng = np.random.default_rng(seed + d)
    axis = rng.integers(0, d, size=(walks, steps))
    sign = rng.choice(np.array([-1, 1], dtype=np.int16), size=(walks, steps))
    at_origin = np.ones((walks, steps), dtype=bool)
    for c in range(d):
        position = np.cumsum(np.where(axis == c, sign, 0), axis=1)
        at_origin &= position == 0
    return float(at_origin.any(axis=1).mean())

def main():
    a = return_probs_1d(10000)
    print("Expected number of returns up to time 2n: sum of P(S_2k = 0), k = 1..n")
    print(f"{'n':>7} {'d = 1':>9} {'2 sqrt(n/pi)':>13} {'d = 2':>8}"
          f" {'ln(n)/pi':>9}")
    for n in [10, 100, 1000, 10000]:
        s1 = sum(a[1:n + 1])
        s2 = sum(x * x for x in a[1:n + 1])
        print(f"{n:>7} {s1:>9.2f} {2 * math.sqrt(n / math.pi):>13.2f}"
              f" {s2:>8.3f} {math.log(n) / math.pi:>9.3f}")
    u3 = [return_prob_3d(n) for n in range(1, 61)]
    print("d = 3: partial sums at n = 10, 20, 40, 60:",
          ", ".join(f"{sum(u3[:n]):.3f}" for n in [10, 20, 40, 60]))
    tail = sum(2 * (3 / (4 * math.pi * n)) ** 1.5 for n in range(61, 200001))
    print(f"       plus the asymptotic tail estimate {tail:.3f}"
          f" gives about {sum(u3) + tail:.3f}")
    print("       (exact value 0.516..., so the return probability is")
    print("       0.516/1.516 = 0.34 < 1: the walk is transient)")
    print()
    print("Simulation: fraction of 1000 walks back at the origin by step 1000")
    for d in [1, 2, 3]:
        print(f"  d = {d}: {simulate_returns(d):.3f}")
    print()
    print("Epistemic status: the return probabilities are computed exactly up")
    print("to floating-point rounding, but a partial sum can never show that a")
    print("series diverges; the divergence for d = 1, 2 is proved in Lean and")
    print("convergence for d = 3 follows from P(S_2n = 0) <= C n^(-3/2). The")
    print("simulation is statistical evidence about finite walks only.")

if __name__ == "__main__":
    main()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The stationary distributions and first-step solutions are exact; the distances and return probabilities are numerical (floating point); the simulations are statistical evidence. A partial sum can never prove that a series diverges — that is what the Lean proofs above are for.

Exercises

Exercises

1. Markov chains

Warm-upHuman

A Markov chain X0,X1,…X_0, X_1, \dots is often called memoryless. Which statement captures the Markov property?

Choose one

2. Markov chains

Warm-upHuman

A weather chain on (dry, cloudy, rainy) has transition matrix P=(0.60.30.10.30.40.30.20.30.5)P = \begin{pmatrix} 0.6 & 0.3 & 0.1 \\ 0.3 & 0.4 & 0.3 \\ 0.2 & 0.3 & 0.5 \end{pmatrix}. Today is dry. What is the probability, in percent, that the day after tomorrow is dry?

3. Markov chains

CoreHuman

Find the stationary distribution of P=(0.90.10.50.5)P = \begin{pmatrix} 0.9 & 0.1 \\ 0.5 & 0.5 \end{pmatrix}.

Choose one

4. Markov chains

CoreHuman

In the fair gambler's ruin game you start with 33 coins and play one-coin fair bets until you have 00 or 1010 coins. What is the expected number of bets?

5. Markov chains

CoreHuman

A chain on {1,2,3,4}\{1, 2, 3, 4\} has p12=1p_{12} = 1; p21=p23=12p_{21} = p_{23} = \tfrac12; p33=p34=12p_{33} = p_{34} = \tfrac12; p43=1p_{43} = 1. Which statements are true? (Choose all that apply.)

Choose all that apply

6. Markov chains

CoreHuman

The lesson proves uniqueness of the stationary distribution by showing that every harmonic function (Ph=hPh = h) is constant. Where exactly is irreducibility used?

Choose one

7. Markov chains

CoreHuman

A walker moves on the 66 vertices of a hexagon, stepping to each of the two neighbouring vertices with probability 12\tfrac12. What is the period of the chain?

8. Markov chains

StretchHuman

Which statement about simple random walk is correct?

Choose one

9. Markov chains

CoreFormal

Which Lean statement formalises "detailed balance implies stationarity"? (π ᵥ* P is the row vector πP\pi P.)

Choose one

10. Markov chains

StretchComputational

Write step(mu, P) returning the row vector μP\mu P (lists of Fractions), and power_iterate(mu, P, n) applying step nn times. Then write is_stationary(pi, P). The tests use the two-state chain with a=14a = \tfrac14, b=12b = \tfrac12 and check that μPn\mu P^n approaches π=(23,13)\pi = (\tfrac23, \tfrac13) at the rate ∣1−a−b∣n=4−n|1 - a - b|^n = 4^{-n}.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
Common misconceptionsH

Common misconceptions

Misconception

"Memoryless means the chain forgets everything." The Markov property says that the future depends on the past only through the present: given XnX_n, the earlier states carry no further information. The present state itself matters enormously — it is the whole of the chain's memory. And unconditionally, Xn+1X_{n+1} is usually strongly dependent on X0,…,Xn−1X_0, \dots, X_{n-1}.

Misconception

"Every chain converges to its stationary distribution." Convergence of λPn\lambda P^n needs irreducibility (otherwise the limit depends on the starting class) and aperiodicity (otherwise the chain can cycle, as in the Ehrenfest urn or the flip chain (0110)\begin{pmatrix}0&1\\1&0\end{pmatrix}). On infinite state spaces positive recurrence is needed too: simple random walk on Z\Z has no stationary distribution at all.

Misconception

"Recurrent means the chain comes back soon." A recurrent state is revisited with probability 11, but the expected return time can be infinite: for simple random walk on Z\Z and Z2\Z^2, E0[T0]=∞E_0[T_0] = \infty (null recurrence). Returns happen infinitely often, but ever more rarely.

Misconception

"A stationary distribution means the chain stops moving." At stationarity the distribution is constant in time; the chain itself keeps jumping. Stationarity is a balance of probability flows, ∑iπipij=πj\sum_i \pi_ip_{ij} = \pi_j, not a frozen state.

Misconception

"The fair gambler breaks even, so playing longer is harmless." In the fair game the expected fortune stays constant, yet against an opponent with unlimited resources ruin is certain, and the expected time to ruin is infinite. With any house edge, the probability of reaching a target falls exponentially with the target's distance.

ViewpointsH

Many ways of seeing

Algebra— Perron–Frobenius: the eigenvalue 1

A stochastic matrix has the eigenvalue 11 with right eigenvector 1\mathbf 1, and a stationary distribution is a left eigenvector for it with non-negative entries. The Perron–Frobenius theorem (Perron 1907, Frobenius 1912) describes non-negative matrices in general: an irreducible non-negative matrix has a positive eigenvalue ρ\rho equal to its spectral radius, with a one-dimensional eigenspace spanned by a positive vector; if it is moreover primitive (some power is positive — for stochastic matrices, irreducible and aperiodic), every other eigenvalue has modulus strictly less than ρ\rho. For stochastic PP, ρ=1\rho = 1, and the theorem contains the existence, uniqueness and positivity of π\pi and the convergence theorem, with rate given by the spectral gap 1−∣μ2∣1 - |\mu_2|. A periodic irreducible chain of period dd has exactly the dd-th roots of unity as eigenvalues of modulus 11 — the algebraic shadow of its cycling.

Topology— A fixed point in a simplex

The set Δ\Delta of distributions on kk states is a simplex of dimension k−1k - 1 — a closed ball, topologically — and μ↦μP\mu \mapsto \mu P maps it continuously into itself. Brouwer's fixed-point theorem therefore guarantees a fixed point: a stationary distribution, for every finite chain, with no algebra at all. (Our existence proof replaced Brouwer by the more elementary averaging argument, which works because the map is affine — the Markov–Kakutani idea.) Uniqueness is not topological: a reducible chain can have a whole segment of fixed points. Topology also organises the state space itself: the communicating classes are the strongly connected components of the directed graph with an edge i→ji \to j when pij>0p_{ij} > 0, and closed classes are its sink components. See point-set topology.

Analysis— Contractions and the speed of mixing

Doeblin's lemma says that μ↦μPN\mu \mapsto \mu P^N is a contraction of the simplex in the total-variation metric, so the convergence theorem is an instance of the Banach fixed-point theorem: a contraction of a complete metric space has a unique fixed point, and iterates converge to it geometrically. Quantitatively, the mixing time tmix(ε)=min⁡{n:max⁡λ∥λPn−π∥TV≤ε}t_{\text{mix}}(\varepsilon) = \min\{n : \max_\lambda\|\lambda P^n - \pi\|_{TV} \le \varepsilon\} is studied with analytic tools — spectral gaps, isoperimetric (Cheeger) inequalities, and the comparison of Dirichlet forms E(f)=12∑i,jπipij(fi−fj)2\mathcal E(f) = \frac12\sum_{i,j}\pi_ip_{ij}(f_i - f_j)^2. Some chains exhibit a sharp cutoff: riffle-shuffling a deck of 5252 cards stays far from random for a while and then becomes close to random within a few shuffles (Bayer and Diaconis, 1992, the source of the familiar "seven shuffles").

Physics— Detailed balance, entropy and the arrow of time

Detailed balance is the probabilistic form of microscopic reversibility in statistical mechanics: at thermal equilibrium every transition is balanced by its reverse. The Ehrenfests introduced their urn to resolve a paradox: Boltzmann's H-theorem says entropy increases, yet reversible dynamics return arbitrarily close to their initial state (Poincaré recurrence). In the urn both are true — the chain is recurrent, so it returns to "all balls in one urn", but the expected return time to that state is 1/πN=2N1/\pi_N = 2^N, astronomically long for N∼1023N \sim 10^{23}, while from a typical state it drifts quickly towards the binomial bulk. In general the relative entropy D(λPn ∥ π)D(\lambda P^n \,\|\, \pi) is non-increasing in nn for every chain with stationary π\pi, a discrete second law of thermodynamics (see information theory). Metropolis's algorithm was invented to compute equilibrium properties of physical systems.

Combinatorics— Electrical networks and spanning trees

Random walks on graphs are combinatorial objects with a beautiful dictionary to electrical networks (Doyle and Snell, 1984): think of each edge as a unit resistor; the probability that a walk from aa hits bb before returning to aa is 1/(deg⁡a⋅Reff(a,b))1/(\deg a \cdot R_{\text{eff}}(a, b)), and a walk on an infinite graph is recurrent exactly when the effective resistance to infinity is infinite. On Z2\Z^2 that resistance grows like log⁡n\log n (recurrent); on Z3\Z^3 it stays bounded (transient) — a second proof of Pólya's theorem. Stationary distributions of general chains also have a combinatorial formula, the Markov chain tree theorem: πj\pi_j is proportional to the sum, over all spanning trees directed towards jj, of the products of the transition probabilities on their edges — a relative of Kirchhoff's matrix-tree theorem. See random geometry for where these ideas lead.

Category theory— Kernels compose

Transition matrices are morphisms in a category: sets with stochastic matrices P:I→JP : I \to J (rows indexed by II, distributions on JJ), composed by matrix multiplication — "first a step of PP, then a step of QQ" — with identity matrices as identities. This is the finite part of the Kleisli category of the probability (Giry) monad described in probability theory, and a Markov chain is a functor from the monoid (N,+)(\N, +) into it, sending nn to PnP^n. Mathlib follows this pattern: ProbabilityTheory.Kernel composes like matrices, and Kernel.IsIrreducible defines irreducibility through the powers κn\kappa^n.

History & global context

History and global context

  • Markov and his predecessors. Andrei Andreyevich Markov introduced chains of dependent variables in 1906 to show that the law of large numbers (and later the central limit theorem) does not require independence — partly in response to Pavel Nekrasov's claim that it did — and in 1913 applied them to the sequence of vowels and consonants in Pushkin's Eugene Onegin. Earlier, the Ehrenfests' urn (1907) and Galton and Watson's study of the extinction of family names (1874) used Markovian ideas, and Bienaymé had analysed branching processes in 1845.
  • Random walks. Karl Pearson posed the "problem of the random walk" in Nature in 1905 (Lord Rayleigh answered from his work in acoustics). Louis Bachelier (1900, modelling prices on the Paris Bourse) and Albert Einstein (1905, Brownian motion) independently linked random walks to diffusion. George Pólya proved his recurrence theorem in 1921, reportedly after noticing how often he met the same couple on walks in a park near Zürich.
  • The general theory. Andrei Kolmogorov developed the theory of chains with countably many states (1936) and the analytic theory of continuous-time Markov processes (1931). Wolfgang Doeblin, working in Paris before his death in 1940, introduced coupling and the contraction condition that bears his name (1938); a sealed envelope he sent to the Académie des sciences, opened in 2000, showed he had anticipated parts of Itô's stochastic calculus. Oskar Perron and Georg Frobenius had meanwhile developed the theory of non-negative matrices (1907–12).
  • Applications. Sewall Wright (1931) and Ronald Fisher (1930) built population genetics on the Wright–Fisher chain, later extended by Motoo Kimura's diffusion theory of neutral evolution (1968). Nicholas Metropolis, Arianna and Marshall Rosenbluth, and Augusta and Edward Teller introduced the Metropolis algorithm at Los Alamos in 1953; W. K. Hastings generalised it in 1970. Sergey Brin and Larry Page's PageRank (1998) made the stationary distribution of a Markov chain one of the most computed objects in the world.
Further reading

Further reading

  • J. R. Norris, Markov Chains (1997) — the standard rigorous introduction, in discrete and continuous time; the hitting-probability theorem and the treatment of recurrence follow it.
  • Geoffrey Grimmett and David Stirzaker, Probability and Random Processes (4th edition, 2020), Chapter 6.
  • David A. Levin and Yuval Peres (with Elizabeth Wilmer), Markov Chains and Mixing Times (2nd edition, 2017) — coupling, spectral methods and cutoff.
  • Peter G. Doyle and J. Laurie Snell, Random Walks and Electric Networks (1984) — Pólya's theorem through electrical networks.
  • Pierre Brémaud, Markov Chains: Gibbs Fields, Monte Carlo Simulation and Queues (2nd edition, 2020) — applications to physics, computation and queues.
  • Eugene Seneta, Non-negative Matrices and Markov Chains (2nd edition, 1981) — the Perron–Frobenius theory.