Explainer
Simulating A Weather Chain In Code
Stepping through state probabilities one loop at a time.
A Markov chain is a list of states and a table of odds. Each step, the system is in one state. The table says how likely it is to move to each other state next. Weather works well as the example: a day is either sunny or rainy, and tomorrow depends only on today. Write the odds down first, then let the code roll the dice one step at a time.
Code · python
The transition table
weather_chain.py
import random
states = ["sunny", "rainy"]
# Each row must add up to 1.0.
# Row = today's state, column = tomorrow's state.
transition = {
"sunny": {"sunny": 0.8, "rainy": 0.2},
"rainy": {"sunny": 0.4, "rainy": 0.6},
}A single step needs one random draw. Pick a number between 0 and 1. Walk through the current state's options, subtracting each probability until the number falls inside one bucket. That bucket is tomorrow's state. This is the whole engine. Every later step is the same move repeated.
Worked Example · PROBABILITY
Rolling one day forward
The problem
Start on a sunny day. The table says sunny stays sunny 80 percent of the time. Use one random draw to decide tomorrow.
- 1
Start with state = "sunny".
Every run begins from a known state, so the result is reproducible in your head.
Code · python
The loop
weather_chain.py
def step(state):
r = random.random()
cumulative = 0.0
for next_state, p in transition[state].items():
cumulative += p
if r < cumulative:
return next_state
return next_state # guards against float rounding
state = "sunny"
history = []
for day in range(30):
state = step(state)
history.append(state)
print(history)What changed · python
for day in range(30):– state = transition[state]["sunny"]+ state = step(state)
The common bug is hard-coding one branch. The diff above shows the mistake: the first version always picks the sunny column, so the chain never rains and never reacts to today. The symptom is a history that is a flat line of "sunny". Route every step through the draw, and the odds do the work.
Tip
Check the table before you run anything
Sum each row of the transition table and confirm it equals 1.0. A row that adds to 0.9 quietly drops one tenth of the draws, and the chain still runs without any error.
Examples
- Print sum(transition[s].values()) for every state.
- Add an assert before the loop so a bad table fails loudly.
Add a third state, such as cloudy, and nothing in the loop changes. Only the table grows. Each row still lists every possible next state and sums to 1. The method stops being simple only when the number of states gets very large, because the table grows with the square of that number. The idea itself does not get harder.
Choose
