Markov chains
A Markov chain moves between finitely many states, choosing each step with probabilities that depend only on where it is. Everything a course asks of one, from the long-run share of time in each state to the chance of ending in each absorbing state, comes from linear algebra over the rationals, so here it is exact.
A chain and its long run
import { markovChain } from "@ratmath/stats";
const weather = markovChain({ sun: { sun: "9/10", rain: "1/10" }, rain: { sun: "1/2", rain: "1/2" } });
weather.distribution("rain", 3); // { sun: 39/50, rain: 11/50 } three days after rain
weather.stationary().distribution; // { sun: 5/6, rain: 1/6 }
weather.meanReturnTime("rain"); // 6 = 1/π(rain)
weather.hitting("rain").expected.sun; // 10 days from sun to the next rain
weather.simulate("sun", 12, { seed: 3 }).join(" ");
With the probability of moving from to , the distribution after steps is , and power(n) computes by repeated squaring. A stationary distribution solves with : one linear system, solved exactly. For an irreducible chain it is unique, and by Kac's lemma the expected time to return to state is .
Expected hitting times solve another linear system: on the target, and elsewhere. From sun, , so .
Classes and periods
const cycle = markovChain([[0, 1, 0], [0, 0, 1], [1, 0, 0]]);
cycle.classes(); // [{ states: [0, 1, 2], closed: true, recurrent: true, period: 3 }]
cycle.isErgodic(); // false: Pⁿ cycles and never settles, though π = (1/3, 1/3, 1/3) exists
States communicate when each can reach the other; the classes are found from reachability. In a finite chain a class is recurrent exactly when no probability leaves it. The period of a class is the greatest common divisor of the lengths of its cycles, found from a breadth-first search. An irreducible chain with period 1 is ergodic: converges to a matrix whose rows all equal .
Absorption
// gambler's ruin with fair bets, from 0 to 4 dollars
const ruin = markovChain([[1, 0, 0, 0, 0], ["1/2", 0, "1/2", 0, 0], [0, "1/2", 0, "1/2", 0],
[0, 0, "1/2", 0, "1/2"], [0, 0, 0, 0, 1]]);
const a = ruin.absorption();
a.probabilities[1]; // { "0": 3/4, "4": 1/4 }
a.steps; // { 1: 3, 2: 4, 3: 3 }: k(N − k) bets on average
Order the states with the transient ones first, so that . The fundamental matrix counts the expected visits to each transient state. Then gives the absorption probabilities and the expected number of steps before absorption. Each is exact; fundamental returns itself.
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.