flowchart LR
R["0: Ready"] -->|0.2| B["1: Busy"]
B -->|0.3| R
R -->|0.8| R
B -->|0.7| B
15 Markov chains and dependent sequences
All earlier independence assumptions were made deliberately. Many systems are dependent: a server may stay busy from one time interval to the next, a queue length changes in response to its present length, and a sequence of weather states persists. Markov chains provide a tractable model in which the present state contains the relevant information for predicting the next state.
15.1 The Markov property
A discrete-time stochastic process \(X_0,X_1,\ldots\) on a finite state space \(\mathcal S\) is a time-homogeneous Markov chain if for all positive-probability histories,
\[ P(X_{t+1}=j\mid X_t=i,X_{t-1},\ldots,X_0) =P(X_{t+1}=j\mid X_t=i)=P_{ij}. \]
The transition matrix \(P\) has nonnegative entries and every row sums to one. Time homogeneity means these entries do not depend on \(t\). The Markov property does not require consecutive states to be independent; it specifies a conditional independence of the future from the past given the present.
15.1.1 Example: a service status process
Consider states 0 (ready) and 1 (busy), with per-step transitions
\[ P=\begin{pmatrix}.8&.2\\.3&.7\end{pmatrix}. \]
If the system is ready now, it remains ready next step with probability .8. If it is busy, the chance of remaining busy is .7. Knowing the earlier path adds no predictive information in this model once the current state is known.
The joint probability of a path is particularly simple. For initial distribution \(v_0\) (a row vector),
\[ P(X_0=i_0,\ldots,X_t=i_t) =v_{0,i_0}\prod_{r=1}^t P_{i_{r-1},i_r}. \]
This follows by iterating the probability chain rule and applying the Markov property at each factor. Starting in state 0, the probability of path \((0,1,1,0)\) is \(.2\cdot.7\cdot.3=.042\).
15.2 Multi-step transition probabilities
Let \(P^{(n)}_{ij}=P(X_n=j\mid X_0=i)\), with \(P^{(0)}=I\). Splitting the path through the state at time \(m\) and using total probability gives
\[ \begin{aligned} P^{(m+n)}_{ij} &=\sum_kP(X_m=k\mid X_0=i)P(X_{m+n}=j\mid X_m=k,X_0=i)\\ &=\sum_kP^{(m)}_{ik}P^{(n)}_{kj}. \end{aligned} \]
These are the Chapman–Kolmogorov equations. By induction, \(P^{(n)}=P^n\), using matrix multiplication, not elementwise powers. The marginal distribution evolves as
\[ v_{t+1}=v_tP,\qquad v_t=v_0P^t. \]
For the ready/busy chain,
\[ P^2=\begin{pmatrix}.70&.30\\.45&.55\end{pmatrix}. \]
Starting ready, the probability of being busy after two steps is .30, the sum of two paths \(.8(.2)+.2(.7)\).
Throughout the chapter we use row distributions and row-stochastic matrices. If you use column distributions, the update is instead \(v_{t+1}=P^\top v_t\). Keep the convention consistent.
15.3 Stationary distributions
A probability row vector \(\pi\) is stationary if
\[ \pi P=\pi,\qquad \sum_i\pi_i=1,\quad \pi_i\ge0. \]
Starting from \(\pi\) leaves the marginal law unchanged at every step. This does not make consecutive observations independent.
For a finite chain, at least one stationary distribution exists. To see this, take any starting distribution \(v\) and form the Cesàro averages \(\bar v_N=N^{-1}\sum_{k=0}^{N-1}vP^k\). These lie in the compact probability simplex, so some subsequence converges to \(\pi\). Moreover,
\[ \bar v_NP-\bar v_N=(vP^N-v)/N\to0. \]
Pass to the convergent subsequence to obtain \(\pi P=\pi\).
In the ready/busy example, stationarity requires \(\pi_0(.2)=\pi_1(.3)\) along with \(\pi_0+\pi_1=1\). Therefore \(\pi=(.6,.4)\). If \(b_t=P(X_t=1)\), the scalar update is
\[ b_{t+1}=.2(1-b_t)+.7b_t=.2+.5b_t. \]
Subtract the fixed point .4 to solve the recurrence:
\[ b_t=.4+(b_0-.4)(.5)^t. \]
The chain’s busy-state probability approaches .4 geometrically from either starting state.
15.4 Irreducibility, periodicity and convergence
State \(j\) is accessible from \(i\) if \((P^n)_{ij}>0\) for some \(n\ge0\). Two states communicate if they are mutually accessible. A chain is irreducible if every state communicates with every other. The period of a state is the greatest common divisor of positive return times \(\{n\ge1:(P^n)_{ii}>0\}\). An irreducible chain has a common period; it is aperiodic if that period is one.
A finite irreducible chain has a unique stationary distribution with strictly positive components. If it is also aperiodic, \(vP^t\to\pi\) for every initial distribution \(v\). We describe the main finite-dimensional proof of convergence.
First consider a matrix \(P\) with every entry positive. Write \(m=|\mathcal S|\), choose \(\epsilon=\min_{ij}P_{ij}>0\), and let \(J\) have every row equal to the uniform distribution. Then
\[ P=m\epsilon J+(1-m\epsilon)R, \]
where \(R\) is row-stochastic if \(m\epsilon<1\). If \(m\epsilon=1\), all rows are uniform already. For two probability distributions \(u,v\), \((u-v)J=0\). By the triangle inequality and row sums of \(R\), \(\|wR\|_1\le\|w\|_1\) for every signed row vector \(w\). Consequently
\[ \|uP-vP\|_1\le(1-m\epsilon)\|u-v\|_1. \]
This is a strict contraction. Compare \(vP^t\) with a stationary \(\pi P^t=\pi\) and iterate the bound to prove convergence and uniqueness. A standard finite graph fact states that for an irreducible aperiodic chain, some power \(P^k\) has every entry positive (paths can be extended to all sufficiently large lengths because return lengths have gcd one). Apply the contraction to that power and to the finitely many intervening steps. This proves the stated convergence result; the existence and uniqueness for periodic irreducible chains use the communicating-class structure.
Periodicity matters. The deterministic two-state chain with matrix \(\begin{pmatrix}0&1\\1&0\end{pmatrix}\) has stationary distribution \((.5,.5)\), but starting at state 0 its marginal distribution alternates forever. The probability law need not converge just because a stationary law exists.
15.5 Detailed balance and long-run frequencies
If a probability vector satisfies
\[ \pi_iP_{ij}=\pi_jP_{ji}\quad\text{for all }i,j, \]
then \(\pi\) is stationary. Sum over \(i\) to obtain \((\pi P)_j=\pi_j\sum_iP_{ji}=\pi_j\). These pairwise flow equalities are called detailed balance. They are sufficient but not necessary for stationarity; a stationary cycle can have nonzero net flow along edges.
The finite irreducible-chain ergodic theorem states that for any function \(g\) on the state space,
\[ \frac1N\sum_{t=1}^Ng(X_t)\longrightarrow\sum_i\pi_i g(i) \quad\text{almost surely}, \]
from any starting state. This holds even in the periodic case for time averages. One way to establish it uses successive returns to a reference state: excursions are independent with the same law by the Markov property at return times, and in a finite irreducible chain their mean length is finite (there is a positive probability of return within a bounded number of steps). Apply the iid strong law to cumulative excursion rewards and lengths. Their ratio produces long-run occupation probabilities, which satisfy the stationary equations.
The observations in such time averages are dependent. Their standard errors cannot generally be found by using the iid formula from Chapter 10. For a stationary chain and \(Y_t=g(X_t)\),
\[ \operatorname{Var}(\bar Y_N)=\frac{1}{N}\left[\gamma_0+ 2\sum_{h=1}^{N-1}(1-h/N)\gamma_h\right], \]
where \(\gamma_h=\operatorname{Cov}(Y_t,Y_{t+h})\). This follows by expanding the variance of the sum and counting the \(N-h\) pairs at lag \(h\).
15.6 Absorption and expected hitting times
A state \(j\) is absorbing if \(P_{jj}=1\). For a target set \(A\), let \(\tau_A=\min\{t\ge0:X_t\in A\}\). When expected hitting times are finite, \(h_i=E_i[\tau_A]\) obeys
\[ h_i=0\ (i\in A),\qquad h_i=1+\sum_jP_{ij}h_j\ (i\notin A). \]
Condition on the first transition: one step passes, then expected remaining time is \(h_j\). If \(Q\) is the submatrix of transitions among non-target states and eventual absorption is certain with finite expected time, then \((I-Q)h=\mathbf1\). The inverse \((I-Q)^{-1}\) equals \(\sum_{n\ge0}Q^n\): partial geometric sums telescope and \(Q^n\to0\). Its entries count expected visits to transient states before absorption.
15.6.1 Example: two-stage completion
Let states 0 and 1 represent two incomplete stages and state 2 completion, with
\[ P=\begin{pmatrix} .5&.5&0\\ .25&.5&.25\\ 0&0&1 \end{pmatrix}. \]
Then \(h_2=0\), \(h_0=1+.5h_0+.5h_1\), and \(h_1=1+.25h_0+.5h_1\). Substitution gives \(h_0=2+h_1\), \(h_1=6\), and \(h_0=8\). Although the process can move backward, each block of two steps has a positive chance of completion from either incomplete state; expected hitting times are finite.
import numpy as np
Q = np.array([[.5,.5],[.25,.5]])
h = np.linalg.solve(np.eye(2)-Q,np.ones(2))
print(h) # Expected steps starting at states 0 and 115.7 A glimpse of Markov-chain Monte Carlo
If we want samples from a target distribution \(\pi\) that is hard to sample directly, we can design a Markov chain whose stationary distribution is \(\pi\). Ergodic averages then approximate target expectations. For a finite target with all \(\pi_i>0\) and a symmetric proposal \(q_{ij}=q_{ji}\), Metropolis accepts a proposed move \(i\to j\) with probability \(a(i,j)=\min(1,\pi_j/\pi_i)\); a rejected move stays at \(i\).
For \(i\ne j\),
\[ \pi_iq_{ij}a(i,j)=q_{ij}\min(\pi_i,\pi_j)=\pi_jq_{ji}a(j,i). \]
Detailed balance proves stationarity. Under irreducibility and aperiodicity, marginal convergence and the ergodic theorem justify inference. The same design idea extends to continuous distributions. Burn-in and diagnostics matter, since a finite trajectory may not have explored the target well; dependent draws have less information than an equally sized iid sample in many settings.
15.8 Practice problems
Work in your browser with Google Colab, or download the notebooks for Jupyter.
Practice notebook
Worked solutions
15.8.1 Exercise 1: Three transitions
Use the ready/busy example to compute \(P(X_3=1\mid X_0=0)\) by the scalar recurrence and by multiplying matrices.
The recurrence gives \(b_3=.4+(0-.4)/8=.35\). The matrix calculation multiplies the first row of \(P^2\), \((.70,.30)\), by the busy column \((.2,.7)^\top\), obtaining \(.70(.2)+.30(.7)=.35\).
15.8.2 Exercise 2: A reducible chain
Find all stationary distributions for \(P=\begin{pmatrix}1&0\\0&1\end{pmatrix}\). Is the stationary distribution unique? Does every initial state converge to the same distribution?
Every probability row vector \((a,1-a)\), \(0\le a\le1\), is stationary because \(P\) is the identity. The chain is reducible; neither state can reach the other. Each initial distribution remains exactly itself, so there is no common limiting distribution.
15.8.3 Exercise 3: Geometric waiting
Consider states 0 and 1, with \(P_{00}=.75\), \(P_{01}=.25\) and state 1 absorbing. Starting at zero, find the distribution and expected number of steps to hit one.
For \(\tau=k\ge1\), the chain remains at zero for \(k-1\) steps then moves to one: \(P(\tau=k)=.75^{k-1}(.25)\). It is geometric with mean four. The hitting-time equation also gives \(h_0=1+.75h_0\), hence \(h_0=4\).
15.8.4 Exercise 4: Simulate a stationary frequency (Python)
Simulate 30,000 transitions of the ready/busy chain from state zero. Plot the running busy fraction, estimate transition probabilities from counts, and compare the long-run busy fraction with .4.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1501)
P = np.array([[.8,.2],[.3,.7]])
n = 30_000
x = np.zeros(n+1,dtype=int)
u = rng.random(n)
for t in range(n):
x[t+1] = int(u[t]<P[x[t],1])
counts = np.zeros((2,2),dtype=int)
np.add.at(counts,(x[:-1],x[1:]),1)
print(counts/counts.sum(axis=1,keepdims=True))
print("Busy fraction",x[1:].mean())
k = np.arange(1,n+1)
plt.plot(k,np.cumsum(x[1:])/k)
plt.axhline(.4,color="black",linestyle="--")
plt.xscale("log")
plt.xlabel("Steps")
plt.ylabel("Running busy fraction")
plt.show()
assert abs(x[1:].mean()-.4)<.03Transition counts must be normalized row by row (the number of departures from each state). The running fraction approaches the stationary probability by the ergodic theorem.
15.8.5 Exercise 5: Verify expected absorption time (Python)
Simulate 20,000 independent paths of the two-stage completion chain until absorption. Estimate the expected hitting time starting at zero and compare to the exact value eight. Use vectorized state updates to avoid storing all paths.
import numpy as np
rng = np.random.default_rng(1502)
P = np.array([[.5,.5,0],[.25,.5,.25],[0,0,1]])
cdf = np.cumsum(P,axis=1)
x = np.zeros(20_000,dtype=int)
tau = np.zeros_like(x)
while np.any(x!=2):
active = np.flatnonzero(x!=2)
u = rng.random(active.size)
x[active] = (u[:,None]>=cdf[x[active]]).sum(axis=1)
tau[active] += 1
se = tau.std(ddof=1)/np.sqrt(tau.size)
print("Mean steps:",tau.mean(),"MC SE:",se)
assert abs(tau.mean()-8)<5*seOnly active paths receive increments. Independent simulation replications permit the ordinary Monte Carlo standard error for the hitting-time mean, even though states within each path are dependent.
15.8.6 Exercise 6: Design a Metropolis chain (Python)
Use a target probability vector proportional to \((1,3,6)\) for states 0, 1 and 2. At each step propose one of the three states uniformly (including the current state). Apply Metropolis acceptance, check detailed balance numerically for the resulting transition matrix, and estimate the target probabilities by simulation.
import numpy as np
rng = np.random.default_rng(1503)
pi = np.array([1.,3.,6.])
pi /= pi.sum()
P = np.minimum(1,pi[None,:]/pi[:,None])/3
np.fill_diagonal(P,0)
np.fill_diagonal(P,1-P.sum(axis=1))
assert np.allclose(pi[:,None]*P,pi[None,:]*P.T)
assert np.allclose(pi@P,pi)
n = 40_000
x = np.zeros(n+1,dtype=int)
j = rng.integers(0,3,n)
u = rng.random(n)
for t in range(n):
x[t+1] = j[t] if u[t]<min(1,pi[j[t]]/pi[x[t]]) else x[t]
freq = np.bincount(x[1000:],minlength=3)/len(x[1000:])
print(P)
print("Target:",pi,"Empirical:",freq)
assert np.max(abs(freq-pi))<.03The uniform proposal is symmetric, so the ratios implement detailed balance. Rejections contribute to the diagonal. Every state is accessible, and self-transitions make the finite chain aperiodic; the empirical frequencies approximate the target.