---
title: Markov chains
heading: Randomness with a short memory: burst errors and queues
eyebrow: A11 · Lesson 50 · Markov chains
xp: 40
---

::: hook
Lesson 4 found that a wireless link losing 1% of packets can lose the next one 40% of the time after a loss. Independent losses can't do that, but a model with two hidden states can: a "good" state where almost nothing is lost and a "bad" state, during a fade, where half the packets vanish. The link hops between them at random, and where it goes next depends only on where it is now. That's a Markov chain, the simplest model of randomness with memory. It describes burst errors, buffers filling and draining, and the state machines inside protocols.
:::

::: play
- A two-state channel starts in the good state. Each packet time it moves from good to bad with probability $a$ and from bad back to good with probability $b$.
- The curve is the chance of being in the bad state after $n$ packets. It climbs to a steady value and stays there.
- Make $b$ small: the bad state lasts longer, so losses come in longer bursts. What sets the steady value, and what sets how fast it's reached?
:::
:::

```sim plot
view: graph
x: n = 0..60
y: P = 0..0.6
slider: a = 0.005..0.2 step 0.005 = 0.05
slider: b = 0.05..0.8 step 0.05 = 0.2
plot: a/(a + b)*(1 - (1 - a - b)^floor(n)) | label: chance of the bad state | samples: 600
plot: a/(a + b) + 0*n | label: steady state | dashed | color: ch2
readout: steady-state share of time in the bad state = a/(a + b) | digits: 3
readout: mean length of a bad spell, packets = 1/b | digits: 3
readout: mean length of a good spell, packets = 1/a | digits: 3
```

::: predict
## A channel goes from good to bad with probability 0.01 per packet and from bad to good with probability 0.2. What fraction of the time is it in the bad state, in the long run?

- [ ] 1%
- [x] About 4.8%
- [ ] 20%
- [ ] 50%

::: reveal
About 4.8%. In steady state, the flow from good to bad must balance the flow back: $\pi_G \times 0.01 = \pi_B \times 0.2$. With $\pi_G + \pi_B = 1$, $\pi_B = \frac{0.01}{0.21} = 0.048$. Bad spells last $\frac{1}{0.2} = 5$ packets on average and good spells 100, which gives the same ratio.
:::
:::

::: nameit
## Markov chains

A process moving among states $1, 2, \ldots, m$ at steps $n = 0, 1, 2, \ldots$ is a **Markov chain** if the next state depends only on the current one:

$$P(X_{n+1} = j \mid X_n = i, X_{n-1}, \ldots) = P(X_{n+1} = j \mid X_n = i) = P_{ij}$$

The **transition matrix** $P$ collects these probabilities; each row adds to 1. The time spent in a state before leaving is geometric (lesson 10), with mean $\frac{1}{1 - P_{ii}}$.

## Evolving the distribution

Write the chance of each state at step $n$ as a row vector $\pi_n$. Then

$$\pi_{n+1} = \pi_nP \qquad \pi_n = \pi_0P^n$$

The entry $(P^n)_{ij}$ is the chance of going from $i$ to $j$ in exactly $n$ steps, the sum over every path of the product of its steps (lesson 4's multiplication rule).

## Steady state

For a chain that can reach every state from every other and doesn't cycle rigidly, $\pi_n$ settles to a unique **stationary distribution** $\pi$ with

$$\pi P = \pi \qquad \sum_i\pi_i = 1$$

$\pi$ is a left eigenvector of $P$ with eigenvalue 1 (A7.33). The long-run fraction of time spent in each state is $\pi_i$. For two states with $P(G \to B) = a$ and $P(B \to G) = b$:

$$\pi_B = \frac{a}{a + b} \qquad \pi_n(B) = \pi_B\big(1 - (1 - a - b)^n\big) \text{ starting from } G$$

The other eigenvalue, $1 - a - b$, sets how fast the start is forgotten.

## The Gilbert–Elliott channel

Give each state its own loss probability, $\ell_G$ small and $\ell_B$ large. The long-run loss rate is $\pi_G\ell_G + \pi_B\ell_B$, but the losses cluster in the bad spells, which is what makes them bursty. That's why interleaving (spreading a code word's bits far apart in time) helps so much on fading links: it turns one burst into scattered single errors a code can fix.
:::

::: example
## A Gilbert–Elliott channel has $a = 0.01$, $b = 0.2$, and loses packets with probability 0.001 in the good state and 0.5 in the bad. Find the long-run loss rate and the mean burst length.

::: solution
1. **Steady state.**
   $$\begin{aligned} \pi_B &= \frac{0.01}{0.21} \\ &= 0.0476 \end{aligned}$$
   and $\pi_G = 0.952$.
2. **Loss rate.**
   $$\begin{aligned} P &= 0.952 \times 0.001 \\ &\quad + 0.0476 \times 0.5 \\ &= 0.00095 + 0.0238 \\ &= 0.0248 \end{aligned}$$
3. **Burst length.** Bad spells last $\frac{1}{0.2} = 5$ packets on average, during which about half the packets are lost.

**Answer:** the long-run loss rate is 0.0248, and bad spells last 5 packets on average.
:::
:::

::: example
## Starting in the good state, what is the chance the same channel is bad two packets later?

::: solution
1. **Path G→B→B.** This is one of the two paths that end in B:
   $$0.01 \times 0.8 = 0.008$$
2. **Path G→G→B.**
   $$0.99 \times 0.01 = 0.0099$$
3. **Add the paths.**
   $$0.008 + 0.0099 = 0.0179$$
4. **Check with the formula.**
   $$\begin{aligned} \pi_B(1 - 0.79^2) &= 0.0476 \times 0.376 \\ &= 0.0179 \end{aligned}$$

**Answer:** the channel is bad two packets later with chance 0.0179.
:::
:::

::: example
## A two-state channel goes from good to bad with probability 0.01 per packet and recovers with probability 0.2. What fraction of the time is it bad, and how long do bad spells last?

::: solution
1. **Balance the flows.** In the steady state,
   $$\pi_\text{good} \times 0.01 = \pi_\text{bad} \times 0.2$$
2. **Fraction of time bad.**
   $$\begin{aligned} \pi_\text{bad} &= \frac{0.01}{0.21} \\ &= 0.048 \end{aligned}$$
   about 5%.
3. **Length of a bad spell.** Each bad spell lasts a geometric number of packets with mean
   $$\frac{1}{0.2} = 5$$
4. **What it means.** Errors come in bursts of about five packets, which is why codes for such channels interleave their data.

**Answer:** the channel is bad about 5% of the time, in spells of 5 packets on average.
:::
:::

::: check
given: a = 0.01 | 0.05; b = 0.1 | 0.3
answer: a/(a + b)
tolerance: 0.5%

## A two-state channel moves good→bad with probability {a} and bad→good with probability {b} per step. What fraction of the time is it bad, in the long run?

::: right
Right. $\frac{a}{a + b}$ = {answer}.
:::

::: misses
- [a] That's the chance of entering the bad state from good in one step.
- [b/(a + b)] That's the good state's share.
- [any] Not yet. Balance the flows: $\pi_Ga = \pi_Bb$.
:::
:::

::: check
given: b = 0.1 | 0.25 | 0.5
answer: 1/b
tolerance: 0.5%

## A channel leaves its bad state with probability {b} per packet. How many packets does a bad spell last on average?

::: right
Right. A geometric wait: $\frac{1}{b}$ = {answer}.
:::

::: misses
- [b] That's the chance of leaving per packet.
- [1/b - 1] Count the packet where it leaves, too: the spell has mean $1/b$.
- [any] Not yet. Geometric with success probability $b$.
:::
:::

::: check
given: a = 0.02 | 0.05; b = 0.2 | 0.4
answer: a*(1 - b) + (1 - a)*a
tolerance: 0.5%

## With good→bad probability {a} and bad→good {b}, starting in the good state, what is the chance of being bad two steps later?

::: right
Right. G→B→B plus G→G→B: {answer}.
:::

::: misses
- [a^2] That's G→B twice; there are other paths.
- [2*a] Account for staying put along each path.
- [any] Not yet. Add the chances of the two paths that end in B.
:::
:::

::: check
given: a = 0.01 | 0.02; b = 0.2 | 0.25; lg = 0.001 | 0.002; lb = 0.3 | 0.5
answer: b/(a + b)*lg + a/(a + b)*lb
tolerance: 0.5%

## A Gilbert–Elliott channel has $a$ = {a}, $b$ = {b}, and loses packets with probability {lg} when good and {lb} when bad. What is the long-run loss rate?

::: right
Right. $\pi_G\ell_G + \pi_B\ell_B$ = {answer}.
:::

::: misses
- [(lg + lb)/2] Weight each state by its share of time, not equally.
- [any] Not yet. Total probability over the two states.
:::
:::

::: check
given: a = 0.05 | 0.1; b = 0.15 | 0.3; n = 3 | 10
answer: a/(a + b)*(1 - (1 - a - b)^n)
tolerance: 0.5%

## Starting in the good state, with $a$ = {a} and $b$ = {b}, what is the chance of being in the bad state after {n} steps?

::: right
Right. $\pi_B(1 - (1 - a - b)^n)$ = {answer}.
:::

::: misses
- [a/(a + b)] That's the long-run value; after only {n} steps it hasn't got there.
- [any] Not yet. $\pi_B\big(1 - (1 - a - b)^n\big)$.
:::
:::

::: check
kind: choice

## Which of these makes a process a Markov chain?

- [ ] Its states are independent from step to step
- [x] Given the current state, the next state doesn't depend on earlier ones
- [ ] It always settles into a single state
- [ ] Its transition probabilities are all equal

::: right
Right. The present carries all the memory the future needs.
:::

::: misses
- [1] Independent steps are a special Markov chain with no memory at all; Markov allows dependence on the current state.
- [3] It settles into a distribution over states, not a single state.
- [4] The probabilities can be anything, as long as each row adds to 1.
:::
:::

::: check
kind: parts
given: a = 0.01 | 0.05; b = 0.2 | 0.5

## A channel goes bad with probability {a} per packet and recovers with probability {b}.

::: part
answer: a/(a + b)
tolerance: 0.5%

### What fraction of the time is it bad?

::: misses
- [b/(a + b)] That's the good fraction.
- [any] Balance: $\pi_\text{good}a = \pi_\text{bad}b$.
:::
:::

::: part
answer: 1/b
tolerance: 0.5%

### How long does a bad spell last, in packets, on average?

::: misses
- [1/a] That's how long a good spell lasts.
- [any] Geometric with exit probability $b$.
:::
:::
:::

::: check
kind: derivation
vars: a = 0.01..0.3, b = 0.1..0.5, n = 1..10

## Starting good, the chance of being bad after $n$ steps is $\pi_b(1 - (1 - a - b)^n)$ with $\pi_b = \frac{a}{a + b}$.

::: step
answer: a/(a + b)*(1 - (1 - a - b)^n)

### Evaluate it.
:::

::: right
Right. It approaches the steady state geometrically, at rate $1 - a - b$ per step.
:::
:::

::: check
kind: python

## Simulate the two-state channel (bad with probability 0.01 per step from good, good with 0.2 from bad) for 10⁶ steps (`np.random.default_rng(7)`), starting good. Set `frac_bad` and `mean_spell`, the average length of bad spells.

```python starter
import numpy as np

frac_bad = mean_spell = 0.0
print(frac_bad, mean_spell)
```

```python solution
import numpy as np

rng = np.random.default_rng(7)
u = rng.random(10**6)
state = 0
bad = np.zeros(10**6, dtype=bool)
for i in range(10**6):
    if state == 0 and u[i] < 0.01:
        state = 1
    elif state == 1 and u[i] < 0.2:
        state = 0
    bad[i] = state == 1
frac_bad = bad.mean()
starts = np.sum(bad[1:] & ~bad[:-1])
mean_spell = bad.sum() / starts
print(frac_bad, mean_spell)
```

```python tests
assert abs(frac_bad - 0.01 / 0.21) < 0.004, f"The bad fraction is 0.01/0.21 = 0.0476; got {frac_bad}."
assert abs(mean_spell - 5) < 0.3, f"Bad spells last 1/0.2 = 5 steps on average; got {mean_spell}."
```

::: right
Right. 4.8% of the time, in spells of about 5: the steady state and the geometric spell length, measured.
:::
:::

::: explain
## Why does a two-state channel produce bursty losses even though its long-run loss rate can be small?

::: model
The channel remembers its state from one packet to the next: once in the bad state, it stays there for a geometric number of packets with mean $1/b$. While it's there, losses are frequent, so they cluster into bursts. Averaged over a long time, the bad state may be rare, so the overall loss rate $\pi_G\ell_G + \pi_B\ell_B$ is low. But given that a loss just happened, the channel is probably in the bad state, so another loss is likely. That's the dependence that independent-loss models miss.
:::
:::

::: practice

::: check
given: p = 0.9 | 0.95 | 0.99
answer: 1/(1 - p)
tolerance: 0.5%

## A state has a self-transition probability of {p}. How long does a visit last on average, in steps?

::: misses
- [any] Geometric: $\frac{1}{1 - P_{ii}}$.
:::
:::

::: check
given: a = 0.1 | 0.2; b = 0.3 | 0.5
answer: 1 - a - b
tolerance: 0.5%

## For a two-state chain with $a$ = {a} and $b$ = {b}, what is the second eigenvalue of the transition matrix, which sets how fast it forgets its start?

::: misses
- [any] $1 - a - b$.
:::
:::

::: check
given: pg = 0.6 | 0.8; a = 0.1 | 0.2; b = 0.4 | 0.5
answer: pg*a + (1 - pg)*(1 - b)
tolerance: 0.5%

## A two-state chain is in G with probability {pg} now. With $a$ = {a} and $b$ = {b}, what is the chance it's in B next step?

::: misses
- [any] $\pi_Ga + \pi_B(1 - b)$.
:::
:::
:::
