Statistical simulation

Markov Chain Simulator

Define a Markov chain through its transition matrix, choose an initial state, and watch how the state distribution converges to the stationary distribution.

Preset

Transition matrix P

Each row represents the current state; each column, the next state. Each row must sum to 1.

Select a preset or configure the matrix and click “Simulate”

Stationary distribution:

Empirical distribution (fraction of time):

Maximum difference |π − empirical|:

Interpretation:

State evolution (cumulative proportion)

Final distribution vs stationary distribution

What is a Markov chain?

A Markov chain is a discrete-time stochastic process \(\{X_0, X_1, X_2, \ldots\}\) that takes values in a finite set of states and satisfies the Markov property, or "memorylessness":

\[ \begin{gathered} P(X_{n+1} = j \mid X_0, X_1, \ldots, X_n) \\ = P(X_{n+1} = j \mid X_n) = p_{ij} \end{gathered} \]

The probability of moving to the next state depends only on the present state, not on how it was reached. This greatly simplifies the mathematical analysis without sacrificing realism in many applications.

The complete behavior of the chain is fully specified by the transition matrix \(P\), where the element \(p_{ij}\) is the probability of moving from state \(i\) to state \(j\) in one step:

\[ \begin{gathered} P = \begin{pmatrix} p_{11} & p_{12} & \cdots & p_{1n} \\ p_{21} & p_{22} & \cdots & p_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ p_{n1} & p_{n2} & \cdots & p_{nn} \end{pmatrix}, \\[6pt] \sum_{j=1}^{n} p_{ij} = 1 \text{ for every } i \end{gathered} \]

Each row of the transition matrix is a probability distribution: the values are non-negative and sum to 1. This makes \(P\) a stochastic matrix (or Markov matrix).

Stationary distribution

A stationary distribution (or equilibrium distribution) is a probability vector \(\pi = (\pi_1, \pi_2, \ldots, \pi_n)\) such that:

$$\pi P = \pi \quad \text{with} \quad \sum_{i=1}^{n} \pi_i = 1, \quad \pi_i \geq 0$$

Intuitively, if the chain is in the stationary distribution at time \(n\), it will remain in that distribution forever. In practice, it represents the long-run fraction of time the chain spends in each state.

Existence and uniqueness conditions

  • Irreducibility: every state is reachable from every other state (the chain is a strongly connected graph). This guarantees that a unique stationary distribution exists.
  • Aperiodicity: no state has a period greater than 1. Together with irreducibility, this guarantees the convergence of the state distribution toward \(\pi\) regardless of the initial state.
  • A chain that is both irreducible and aperiodic is called ergodic. For ergodic chains, \(\pi\) is the unique stationary distribution and the chain converges to it.

Absorbing state: the Customer / Churn preset

In the Customer preset, the "Churn" state is an absorbing state: \(p_{\text{churn}, \text{churn}} = 1\). Once a customer leaves, they don't come back. This makes the chain non-ergodic: eventually every customer ends up in Churn. The stationary distribution assigns probability 1 to that state and 0 to the rest.

How the simulator works, step by step

The simulator does two different things: it walks through the chain at random, step by step, and separately computes the theoretical stationary distribution. Then it compares the two.

  1. It reads the transition matrix and checks that each row sums to 1 and that there are no negative values.
  2. It places the chain in the initial state you chose.
  3. It takes one step. It looks only at the row of the current state, draws a random number between 0 and 1 and compares it with the cumulative probabilities of that row. In the Weather preset, from Sunny the row is 0.7, 0.2, 0.1: if the number is below 0.7, tomorrow is Sunny again; between 0.7 and 0.9, it moves to Cloudy; and above 0.9, to Rainy.
  4. It repeats step 3 as many times as the number of steps you asked for, recording the sequence of states.
  5. It counts what fraction of the time the chain spent in each state: this is the empirical distribution.
  6. It computes the stationary distribution π without simulating: it starts from an even split across the states and multiplies it by the matrix over and over until it stops changing (change below 10−9). With the Weather preset, 26 multiplications are enough.

Step 3 is the Markov property in action: to decide the next state, nothing of the history is consulted, only where the chain is now.

Evolution chart. Each solid line is the fraction of the time the chain has spent in a state up to that step; the dashed lines are the values of π. At first the lines jump around a lot, because few steps have accumulated, and then they settle towards the dashed ones.

Bar chart. It compares the final empirical distribution with π. The "maximum difference" is the largest gap between the two bars of the same state.

What is random and what is not. The path is random: each click on "Simulate" gives a different one. The distribution π is not: it depends only on the matrix. With 100 steps of the Weather preset it is normal to see maximum differences of about 0.07; with 1000 steps, about 0.02. This is not a fault: the fraction of time approaches π slowly, at a rate of \(1/\sqrt{n}\), like any average.

Customer / Churn preset. Here π equals 1 at Churn, but the fraction of time in Churn does not reach 1: on average the chain spends its first 11 steps outside that state, and those steps still count. With 50 steps, the fraction is usually around 0.8; with 1000, 0.99.

Custom. You can enter your own matrix with 2 to 5 states. Each row is the split of probabilities for "where do I go from here" and must sum to 1.

The arithmetic, with the Weather preset

The preset's matrix, with the states in the order Sunny, Cloudy and Rainy, is

\[ P = \begin{pmatrix} 0.7 & 0.2 & 0.1 \\ 0.3 & 0.4 & 0.3 \\ 0.2 & 0.3 & 0.5 \end{pmatrix}. \]

The distribution n steps from now

If today the probability of being in each state is the row vector \(\pi^{(0)}\), tomorrow's follows from the law of total probability: to be in state j tomorrow you must be in some state i today and move from i to j.

\[ \pi^{(1)}_j = \sum_i \pi^{(0)}_i\,p_{ij} \quad\Longleftrightarrow\quad \pi^{(1)} = \pi^{(0)}P. \]

Repeating the argument, n steps from now:

\[ \pi^{(n)} = \pi^{(0)}P^{\,n}. \]

For example, if today is Sunny, the probability that it is Sunny again in two days adds up the three possible paths (via Sunny, via Cloudy or via Rainy):

\[ 0.7 \cdot 0.7 + 0.2 \cdot 0.3 + 0.1 \cdot 0.2 = 0.57. \]

Carrying on like this, starting from Sunny:

StepsSunnyCloudyRainy
0100
10.7000.2000.100
20.5700.2500.180
30.5100.2680.222
50.4690.2790.252
80.4580.2820.260
Limit (π)0.4570.2830.261

Within a week, the information that today is Sunny has almost been lost. Starting from Rainy leads to the same limiting values.

Solving πP = π

The stationary distribution is the one that does not change after one step. Writing \(\pi = (s, c, r)\), the condition \(\pi P = \pi\) gives one equation per column of P; two are enough, together with the probabilities summing to 1:

\[ \begin{aligned} s &= 0.7\,s + 0.3\,c + 0.2\,r \\ c &= 0.2\,s + 0.4\,c + 0.3\,r \\ 1 &= s + c + r \end{aligned} \]

From the first, \(3s = 3c + 2r\); from the second, \(6c = 2s + 3r\). Substituting one into the other gives \(c = \tfrac{13}{12}\,r\) and \(s = \tfrac{21}{12}\,r\), and with the third:

\[ \pi = \left( \frac{21}{46},\ \frac{13}{46},\ \frac{12}{46} \right) \approx (0.457,\ 0.283,\ 0.261). \]

In the long run, 45.7% of days are sunny, whatever the weather today. It is the same result the simulator gets by multiplying repeatedly by P.

How fast it gets there

The speed depends on the second largest eigenvalue of P in absolute value. In the Weather preset it is \(\lambda_2 \approx 0.47\): at each step, the distance between \(\pi^{(n)}\) and \(\pi\) is multiplied by roughly 0.47, and after 8 steps it is below 0.003. With two states the calculation is direct. If the matrix is

\[ P = \begin{pmatrix} 1-a & a \\ b & 1-b \end{pmatrix}, \]

at equilibrium the flow from 1 to 2 equals the flow from 2 to 1, \(\pi_1 a = \pi_2 b\), and therefore

\[ \pi = \left( \frac{b}{a+b},\ \frac{a}{a+b} \right), \qquad \lambda_2 = 1 - a - b. \]

If a and b are small, the chain rarely changes state, \(\lambda_2\) is close to 1 and convergence is slow. You can check this in Custom mode with 2 states.

Two ways of "converging"

Two things are worth telling apart. The distribution at step n, \(\pi^{(n)}\), converges to π very quickly (geometrically), and is the one in the table above. The fraction of time a single path spends in each state, which is what the simulator plots, also converges to π (this is the ergodic theorem), but much more slowly, like \(1/\sqrt{n}\), because it is an average over a random path.

Customer / Churn preset: time until churn

When there is an absorbing state, the interesting question is not where the chain ends up, but how long it takes. Let \(t_A\) and \(t_D\) be the expected number of steps to Churn starting from Active and from Dormant. Taking one step and seeing where you land:

\[ \begin{aligned} t_A &= 1 + 0.80\,t_A + 0.15\,t_D \\ t_D &= 1 + 0.20\,t_A + 0.60\,t_D \end{aligned} \]

Solving the system gives \(t_A = 11\) and \(t_D = 8\): an active customer lasts 11 periods on average before churning, 8 of them as active and 3 as dormant.

Real-world applications

  • PageRank (Google): the web is modeled as a Markov chain in which the states are pages and the transitions are hyperlinks. The stationary distribution determines the relevance of each page.
  • Weather models: states such as Sunny, Cloudy and Rainy with transition probabilities fitted to historical data.
  • Customer lifecycle: Active → Dormant → Churn. Lets you compute the expected value of a customer and design retention strategies.
  • Text generation: n-gram models are Markov chains in which the state is the sequence of the last \(n\) words and the transition picks the next one.
  • MCMC in Bayesian statistics: the Metropolis-Hastings and Gibbs sampling algorithms build Markov chains whose stationary distribution is the posterior of interest.
  • Population genetics: the Wright-Fisher model describes how allele frequencies change in a finite population through a Markov chain.
  • Queueing theory: Markov chains model the number of customers in an M/M/1 or M/M/k queue, allowing the computation of waiting times and service rates.

Frequently asked questions

How many steps are needed to reach equilibrium?

It depends on the chain's mixing time, which is related to the second-largest eigenvalue (in absolute value) of the transition matrix, \(|\lambda_2|\). The closer \(|\lambda_2|\) is to 1, the slower the convergence: the chain "remembers" its initial state for a long time. Formally, the distance between the distribution at step \(t\) and the stationary distribution decreases approximately as \(|\lambda_2|^t\). For the Weather preset, mixing is relatively fast; for chains with nearly absorbing states or low connectivity, it can take thousands of steps.

Does the chain always converge to the same distribution regardless of the initial state?

Yes, as long as the chain is ergodic (irreducible and aperiodic). In that case, the Markov Ergodic Theorem guarantees that the distribution at step \(n\) converges to the unique stationary distribution \(\pi\) for any initial state. The Weather preset is ergodic. On the other hand, if the chain has several absorbing states or is not irreducible, the limiting distribution can depend on the starting state.

What happens with the Customer / Churn preset?

The "Churn" state is absorbing: \(p_{\text{Churn},\text{Churn}} = 1\) and the other \(p_{\text{Churn},j} = 0\). Once in Churn, there's no way out. This means the chain is not irreducible, and the only stationary distribution is \(\pi_{\text{Churn}} = 1\), \(\pi_{\text{Active}} = \pi_{\text{Dormant}} = 0\). If you run the simulation for many steps, you'll see the proportion of time spent in Churn keep growing toward 1. This is the basis of time-to-absorption analysis, a key metric in customer management.

How is the stationary distribution computed numerically?

The simulator uses power iteration: it starts from an initial probability vector (the uniform distribution) and repeatedly multiplies it by the matrix \(P\) until the change between iterations is smaller than \(10^{-9}\). This process converges to the stationary distribution (if it exists and is unique) within a few thousand iterations. Analytically, \(\pi\) is the left eigenvector of \(P\) associated with eigenvalue 1.

Why does the simulator show horizontal reference lines in the evolution chart?

The dashed horizontal lines mark the theoretical value of the stationary distribution \(\pi_i\) for each state \(i\). As the simulation progresses, the solid lines (cumulative proportion of time spent in each state) converge toward those reference values. This convergence is the empirical manifestation of the ergodic theorem.

References and further reading

  • Markov chain — Wikipedia. Definitions, classification of states and examples.
  • Hayes, B. (2013). First links in the Markov chain. American Scientist, 101(2), 92. A popular account of the origin of the chains: Markov counting vowels and consonants in a poem by Pushkin.
  • Norris, J. R. (1997). Markov Chains. Cambridge University Press. A standard textbook, rigorous and accessible.
  • Levin, D. A. and Peres, Y. (2017). Markov Chains and Mixing Times (2nd ed.). American Mathematical Society. On the speed of convergence to equilibrium.
  • Brin, S. and Page, L. (1998). The anatomy of a large-scale hypertextual Web search engine. Computer Networks and ISDN Systems, 30(1–7), 107–117. PageRank: the stationary distribution of a random walk on the web.

Related tools