◆ AI All-in-One

Level 3 In-Depth AI · Reinforcement Learning

Markov Decision Processes

The mathematical frame behind reinforcement learning. States, actions, transition probabilities, rewards and a discount, plus the Markov property that makes the problem solvable.

Level
●●●●● Intermediate
Reading
11 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Reinforcement Learning: The BasicsProbability Basics

This leads to

Monte Carlo Tree Search and AlphaGoValue Functions and Bellman EquationsModel-Based RL and World ModelsPolicy Gradients
The full path from zero — 5 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. How Machines Learn
  4. Supervised, Unsupervised and Reinforcement Learning
  5. Reinforcement Learning: The Basics
  6. Markov Decision Processes

Read them roughly in this order. See it on the concept map →

Why it matters

Reinforcement Learning: The Basics described reinforcement learning in words: an agent, an environment, states, actions and rewards. To build algorithms that provably work, we need to say exactly what those words mean. The Markov decision process (MDP) does that. It is the shared mathematical language of the whole field. Value iteration (Value Functions and Bellman Equations), Q-Learning, Policy Gradients, Proximal Policy Optimization and the tree search in AlphaGo are all methods for solving MDPs, or for solving them approximately when the MDP is too big to write down.

Writing a problem as an MDP also forces useful questions. What exactly does the agent observe? Is that enough to decide well? What is random? What is being rewarded? Many failed RL projects fail at this step, long before any learning happens.

The intuition

An MDP is a board game described completely by its rulebook. The rulebook lists:

  • every situation you can be in (the states),
  • the moves allowed in each situation (the actions),
  • for each situation and move, what can happen next and how likely each outcome is (the transition probabilities), and
  • how many points each outcome is worth (the rewards).

The randomness matters. In our gridworld from Reinforcement Learning: The Basics, suppose the floor is icy. When you try to move up, you go up 80% of the time but slip sideways the other 20%. You choose the action, but the world chooses the outcome, with known odds. Planning in such a world means preferring routes where a slip is harmless, such as staying away from the edge of the pit.

The agent chooses "up" 0.8 0.1 0.1 blue: current square Sₜ p(up-square | s, up) = 0.8 p(left-square | s, up) = 0.1 p(right-square | s, up) = 0.1 If a slip would hit a wall or the edge, the agent stays put with that probability. The Markov property S₀ … Sₜ Sₜ₊₁ Aₜ the path so far: irrelevant the present state holds all you need p(Sₜ₊₁ | Sₜ, Aₜ) = p(Sₜ₊₁ | S₀, A₀, …, Sₜ, Aₜ) "The future depends on the past only through the present."
Fig. 1 Left: on an icy floor, choosing "up" moves up with probability 0.8 and slips left or right with probability 0.1 each. Right: the Markov property. Once you know the current state, the earlier history adds nothing about what happens next.

The word Markov names the one assumption that holds everything together. What happens next depends only on the current state and action, not on how you got there. A chess position is Markov. To choose a move you need the board and whose turn it is, not the order in which the pieces arrived. (Strictly, chess needs a few extra facts too: castling rights, en passant, and the repetition count. Put those in the state and it is Markov again.) The position of a ball in a single photograph is not Markov. One snapshot doesn't tell you which way it is moving.

Key idea An MDP is a rulebook: states, actions, the probabilities of each next state and reward, and a discount. The Markov property says the current state contains everything relevant about the past. If your state doesn't, add to it until it does.

How it works

The five ingredients

A finite MDP is defined by:

  1. A set of states S\mathcal{S} (the state space).
  2. A set of actions A\mathcal{A} (the action space). Sometimes the actions depend on the state, written A(s)\mathcal{A}(s).
  3. A set of possible rewards R\mathcal{R}, which are numbers.
  4. The dynamics function pp, which gives the probability of each next state and reward.
  5. A discount factor γ\gamma between 0 and 1 (see Reinforcement Learning: The Basics).

The dynamics function is the heart of it. Following Sutton and Barto:

p(s′,r∣s,a)=Pr⁡{St=s′,  Rt=r∣St−1=s,  At−1=a}p(s', r \mid s, a) = \Pr\{S_t = s',\; R_t = r \mid S_{t-1} = s,\; A_{t-1} = a\}

In words: if you are in state ss and take action aa, the probability that you land in state s′s' and receive reward rr. The vertical bar "∣\mid" means "given" (conditional probability). For each ss and aa these probabilities must add up to 1 over all combinations of s′s' and rr, because something must happen.

Two quantities you can derive from pp come up all the time. The transition probability ignores the reward:

p(s′∣s,a)=∑rp(s′,r∣s,a)p(s' \mid s, a) = \sum_{r} p(s', r \mid s, a)

The expected reward for taking aa in ss averages over all outcomes:

r(s,a)=∑s′∑rr  p(s′,r∣s,a)r(s, a) = \sum_{s'} \sum_{r} r \; p(s', r \mid s, a)

The Markov property, precisely

The definition of pp already contains the Markov assumption. It conditions only on the last state and action. Formally, an environment has the Markov property when

Pr⁡{St+1,Rt+1∣St,At}=Pr⁡{St+1,Rt+1∣S0,A0,R1,…,St,At}\Pr\{S_{t+1}, R_{t+1} \mid S_t, A_t\} = \Pr\{S_{t+1}, R_{t+1} \mid S_0, A_0, R_1, \dots, S_t, A_t\}

Conditioning on the whole history gives the same answer as conditioning on the present alone. This is a property of the state you choose, not only of the world. The same physical system can be Markov or not depending on what you put in the state. When DeepMind's DQN played Atari, a single screen frame didn't show which way the ball was moving. So the state was a stack of the last four frames, which does.

Policies

A policy π\pi chooses actions. A stochastic policy gives a probability for each action, π(a∣s)\pi(a \mid s). A deterministic policy always picks the same action in a given state, written π(s)=a\pi(s) = a. A deterministic policy is the special case where one action gets probability 1.

For a finite MDP there is always at least one deterministic policy that is optimal, at least as good as every other policy in every state. That is a reassuring fact, but it doesn't make the search easy. The number of deterministic policies is ∣A∣∣S∣|\mathcal{A}|^{|\mathcal{S}|}. Our 4 × 4 gridworld has 13 squares where the agent can act (16, minus the wall and the two end squares), and 4 actions in each, so there are 413=67,108,8644^{13} = 67{,}108{,}864 deterministic policies. Brute force is hopeless even here. Value Functions and Bellman Equations gives a far better way.

What we are trying to maximise

A policy is good if it earns a high expected return: the average of the return GtG_t (Reinforcement Learning: The Basics) over all the randomness in the environment and the policy. The state-value function of a policy measures this from each starting state:

vπ(s)=Eπ[Gt∣St=s]v_\pi(s) = \mathbb{E}_\pi\left[ G_t \mid S_t = s \right]

Eπ\mathbb{E}_\pi means "the expected value when actions are chosen by π\pi". Solving an MDP means finding a policy π∗\pi_* whose value is the highest possible in every state. Value Functions and Bellman Equations covers how to compute vπv_\pi and π∗\pi_*. In this chapter we will simply estimate vπv_\pi by running the policy many times and averaging.

A worked example: the battery robot

Here is a tiny MDP, adapted from the recycling-robot example in Sutton and Barto. A robot collects empty cans. Its battery is either high or low (two states). In either state it can search for cans or wait for someone to bring one. When low, it can also go and recharge.

high battery low battery search 0.7, r = +2 0.3, r = +2 search 0.6, r = +2 0.4, r = −3 battery died, rescued recharge 1.0, r = 0 wait 1.0, r = +1 wait 1.0, r = +1 big circles: states · black dots: actions · arrows: next state with its probability and reward
Fig. 2 The battery-robot MDP. Big circles are states and black dots are actions. Each arrow leaving an action shows a possible next state with its probability and reward. Searching on a low battery risks running flat (probability 0.4), which costs −3.

Read off a few numbers:

  • Search when high: reward +2 for sure. With probability 0.7 the battery stays high, with 0.3 it drops to low. Expected reward r(high,search)=2r(\text{high}, \text{search}) = 2.
  • Search when low: with probability 0.6 it finds cans (+2) and stays low. With 0.4 the battery dies, a human rescues it (−3) and puts it back on the charger, so it ends up high. Expected reward 0.6×2+0.4×(−3)=1.2−1.2=00.6 \times 2 + 0.4 \times (-3) = 1.2 - 1.2 = 0.
  • Wait: +1, state unchanged.
  • Recharge: 0 reward, battery back to high.

Which is better on a low battery? Looking one step ahead, "wait" (+1) beats "search" (0) and "recharge" (0). But recharging puts the robot back in the high state, where searching pays 2 per step. A one-step view misses that. The return, discounted at γ=0.9\gamma = 0.9, captures it, and the code below shows that recharging is clearly the best choice.

In code

An MDP in plain Python is just a nested dictionary: P[state][action] lists the possible outcomes as (probability, next_state, reward). We check that each list of probabilities sums to 1, then estimate vπv_\pi for three policies by Monte Carlo: run the policy many times and average the discounted returns.

import random

# P[state][action] = list of (probability, next_state, reward)
P = {
    "high": {"search":   [(0.7, "high", 2.0), (0.3, "low", 2.0)],
             "wait":     [(1.0, "high", 1.0)]},
    "low":  {"search":   [(0.6, "low", 2.0), (0.4, "high", -3.0)],   # battery died: rescued
             "wait":     [(1.0, "low", 1.0)],
             "recharge": [(1.0, "high", 0.0)]},
}
for s in P:                                   # sanity check: each row sums to 1
    for a in P[s]:
        assert abs(sum(p for p, _, _ in P[s][a]) - 1) < 1e-9

def step(s, a):
    """Sample (next_state, reward) from p(s', r | s, a)."""
    x, total = random.random(), 0.0
    for p, s2, r in P[s][a]:
        total += p
        if x < total:
            return s2, r
    return s2, r

def mc_value(policy, s0, gamma=0.9, episodes=5000, horizon=100):
    """Monte Carlo estimate of v_pi(s0): average discounted return."""
    total = 0.0
    for _ in range(episodes):
        s, G, disc = s0, 0.0, 1.0
        for _ in range(horizon):              # 0.9**100 ≈ 0.00003, so 100 steps is plenty
            s, r = step(s, policy[s])
            G += disc * r
            disc *= gamma
        total += G
    return total / episodes

random.seed(0)
policies = {"always search":     {"high": "search", "low": "search"},
            "recharge when low": {"high": "search", "low": "recharge"},
            "wait when low":     {"high": "search", "low": "wait"}}
for name, pi in policies.items():
    print(f"{name:18s} v(high) ≈ {mc_value(pi, 'high'):5.2f}   v(low) ≈ {mc_value(pi, 'low'):5.2f}")

# always search      v(high) ≈ 12.54   v(low) ≈  9.80
# recharge when low  v(high) ≈ 15.73   v(low) ≈ 14.18
# wait when low      v(high) ≈ 12.71   v(low) ≈ 10.00

Recharging when low is worth about 14.2 from the low state, against 10.0 for waiting, even though waiting earns more on the very next step. Solving the Bellman equations exactly (Value Functions and Bellman Equations) gives 15.75 and 14.17 for that policy, so the Monte Carlo estimates are within about 0.03.

Note what this code uses: the full table P. Here we only used it to simulate, but an agent that has P could plan without ever acting. That is the dividing line between planning (the MDP is known, as in Value Functions and Bellman Equations) and reinforcement learning proper (the agent only sees samples, as in Q-Learning). Model-Based RL and World Models sits in between: learn P from experience, then plan with it.

Common pitfalls

  • A non-Markov state. If the state leaves out something that matters, such as velocity, a timer, or what the user said three turns ago, no algorithm can learn the best policy, because two situations that need different actions look identical. Add the missing information: stack recent frames, include a time feature, or use a recurrent network (Recurrent Neural Networks) as memory.
  • Probabilities that don't sum to 1. Hand-built MDPs often have a typo in one row. Assert the sums, as the code does.
  • Forgetting terminal states. In an episodic task the end state must stop the return. Treat it as an absorbing state that loops to itself with reward 0 forever, and the maths works unchanged.
  • Huge state spaces. Go has about 2×101702 \times 10^{170} legal positions. Tables are out of the question, so you need function approximation (Deep Q-Networks) or search (Monte Carlo Tree Search and AlphaGo).
  • Confusing p(s′∣s,a)p(s' \mid s, a) with the policy. The environment chooses s′s' and the agent chooses aa. Keep them apart in your head and in your code.

Watch out Most real problems are not perfectly Markov in what the agent can observe. A robot's camera can't see behind it, and a poker player can't see the other hands. Treating observations as states usually works well enough, but when it doesn't, you need the partially observable framework below.

Where it leads

  • Partially observable MDPs (POMDPs). The agent receives an observation that only hints at the true state. The ideal agent keeps a belief, a probability distribution over states updated with Bayes' Theorem, and acts on that. In deep RL, a recurrent network or transformer usually plays the role of memory.
  • Continuous states and actions. A robot arm has real-valued joint angles and torques. Sums over states become integrals, tables become neural networks, and policies output, for example, the mean and spread of a Gaussian over torques.
  • Average-reward and continuing tasks. Instead of discounting, maximise the long-run reward per step.
  • Multi-agent settings. When other learners share the environment, it stops being stationary from any one agent's point of view (games, markets, Multi-Agent Systems).

Next, Value Functions and Bellman Equations turns the definition of vπv_\pi into equations you can solve, and solves the icy gridworld exactly.

A bit of history

Andrey Markov studied chains of random events in which each step depends only on the previous one in 1906. Richard Bellman added decisions and rewards. His 1957 paper "A Markovian Decision Process" and his book Dynamic Programming gave the framework its name and its central equation. Ronald Howard's 1960 book Dynamic Programming and Markov Processes introduced policy iteration and made MDPs a standard tool in operations research, where they still schedule maintenance, manage inventories and price airline seats. Partial observability was added by Karl Åström in 1965. In the late 1980s, researchers including Sutton, Barto and Watkins connected MDPs to learning from experience. That union is modern reinforcement learning.

Try it

  1. Add a third state, "dead", that the robot enters when searching on a low battery fails, with no rescue: it is absorbing with reward 0 forever. How does the value of "always search" change?
  2. Change the rescue penalty from −3 to −1. Is recharging still the best choice when low?
  3. Count the deterministic policies of the battery robot. (High has 2 actions, low has 3.) Evaluate them all with mc_value and find the best.

Hint for 3: there are 2×3=62 \times 3 = 6.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A single Atari frame does not show which way the ball is moving. What is the standard fix that makes the state close to Markov?

  2. In the battery robot, searching on a low battery pays +2 with probability 0.6 and −3 with probability 0.4. What is the expected reward?

  3. On a low battery, waiting earns +1 now and recharging earns 0, yet recharging is the better choice. Why?

  4. You build an MDP by hand and one row of transition probabilities for a state–action pair sums to 0.9. What does that mean?

  5. A robot's camera cannot see behind it, so two situations needing different actions can look identical. Which framework describes this setting?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

UCL Course on Reinforcement Learning

David Silver · 2015 · Intermediate · Free

Ten recorded lectures with slides by the lead researcher behind AlphaGo. Covers MDPs, dynamic programming, TD learning, function approximation, policy gradients and planning; follows Sutton & Barto closely.

Article

A (Long) Peek into Reinforcement Learning

Lilian Weng · 2018 · Intermediate · Free

A dense, well-organised tour of the core ideas: MDPs, Bellman equations, dynamic programming, Monte Carlo and TD methods, Q-learning, DQN and policy gradients.

Tutorial

Spinning Up in Deep RL

Joshua Achiam (OpenAI) · 2018 · Intermediate · Free

OpenAI's short, precise introduction to deep RL: key concepts and notation, the policy-gradient derivation, and clean reference implementations of VPG, PPO, DDPG, TD3 and SAC.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/mdps.md