Solving MDPs
From the Bellman equations to actual algorithms that produce an optimal policy. Dynamic programming, iterative policy evaluation, the policy-improvement theorem, policy iteration, value iteration, and the linear-programming view — three families of method, all driving the same fixed point into existence.
01 · Motivation
Why does this matter?
Chapter 8 introduced the language of Markov decision processes: states, actions, transitions, rewards, the Bellman equations that relate the value of a state to the values of its successors. We have the definition of what an optimal policy is. We do not yet have a way to actually find one. That is the missing piece, and it is what this chapter fills in.
Before we build any algorithm, let’s pin down what “solving an MDP” actually means. It is the conjunction of two outputs:
- Optimal value function $V^*$
- a vector in telling us, for each state, the best possible expected discounted return achievable from that state.
- Optimal policy $\pi^*$
- a rule that achieves — that is, for every .
These two outputs are tightly coupled: once you have , the optimal policy is just “act greedily with respect to ”; once you have , the optimal value function is just “evaluate ”. The three algorithms in this chapter differ only in which of these two objects they compute first.
The naive approach is straightforward and catastrophic. Enumerate every deterministic Markov policy , evaluate each one, keep the best. The number of such policies is : with just 20 states and 4 actions, that’s policies. With 100 states the universe ends before we finish counting. We need a fundamentally smarter method.
Plans share structure
The value of being in state is determined by the values of the states you reach in one step. If we already know for every successor , computing takes one Bellman backup. Subproblems overlap massively.
The Bellman equations are recursive
Recursion + caching = dynamic programming. The Bellman expectation and optimality equations are textbook examples of “the principle of optimality applies.”
A model unlocks planning
When and are known, we don’t need experience — we can plan. The agent computes the optimal policy offline, then executes it. This is the foundation that model-free RL (Ch. 10) tries to imitate without a model.
The conceptual shift
Chapter 8 was a language: how to write down a sequential decision problem. Chapter 9 is a workshop: three different machines that take that description and return an optimal policy. All three are mathematically equivalent — they compute the same fixed point — but each exposes a different facet of the structure, and each pays a different computational price.
Quick recap from Chapter 8 — V and Q
The state-value is the expected discounted return starting from and following thereafter. The action-value starts from , takes action right now, and follows only from the next step. They are linked by
Their starred versions and replace the policy-weighted sum with a maximum. The Q-form is the natural object for comparing actions — we reach for it whenever we improve a policy.
This chapter assumes full knowledge of the MDP — every and every is given. That assumption is what distinguishes planning (this chapter) from reinforcement learning (next chapter). When the model is unknown, we’ll estimate values from sampled experience — but the algorithms there are direct relatives of the ones we build here.
02 · Intuition
The idea in plain language
Forget the algebra for a moment. Imagine you stand at the entrance of a maze with a one-step lookahead. You want to know “how good is each cell” — if I follow the best plan from here, how much reward will I collect? The trick that makes the whole chapter tick: the value of a cell is the immediate reward for moving, plus a discounted copy of the value of wherever you land. The far future is already baked into the values of your neighbours. If you knew your neighbours’ values, computing your own is one arithmetic operation. We never enumerate plans.
Reward information flowing backward through states
Imagine the rewards as drops of dye placed at certain transitions. A Bellman backup at state inspects the dye at the immediately reachable transitions and stains a little. After two backups, dye from two steps away has reached ; after backups, dye from steps away has soaked in. In the limit, every state knows about every reachable reward — discounted by distance. Both value iteration and the inner loop of policy iteration are doing exactly this: pumping reward information backward through the transition graph, one hop per sweep. With , far-away rewards fade as they propagate, so finitely many sweeps suffice to any chosen accuracy.
Two nested loops, two ways to break the recursion
The Bellman equations talk about a value function that satisfies itself. There are two ways to handle the circular reference, and they give us the two main algorithms.
Policy iteration
Lock the policy. Solve the (now-linear) Bellman equations exactly for it — policy evaluation. Then update the policy by acting greedily with respect to those values — policy improvement. Repeat until the policy stops changing. Few iterations, each one a linear solve.
Value iteration
Don’t bother with explicit policies. Treat the Bellman optimality equation as an update rule: plug any current estimate into the right-hand side, get a better one, repeat. The values converge to ; read off the greedy policy at the end. Many iterations, each one cheap.
And as a third voice, linear programming. The Bellman optimality equation with its can be linearised by replacing the with one inequality per action. The result is a textbook LP — solve once, get directly. Different machinery, same answer.
Why greedy improvement cannot hurt
Here is the load-bearing intuition for policy iteration. Suppose you’ve evaluated and know and . In some state there is an action with . Modify to take at but keep it identical everywhere else. Two things happen: at you now collect strictly more expected return (by definition of ); and after that single deviation you revert to , so the tail of the trajectory is unchanged in distribution. The new policy is at least as good at and identical elsewhere — so it is globally at least as good. One greedy step is never a step backwards.
The chapter in one sentence
Plug the Bellman equations into themselves until they stop changing. Policy iteration alternates “solve the linear Bellman expectation for a fixed policy” and “be greedy.” Value iteration iterates the non-linear Bellman optimality directly. LP solves the optimality equation as a set of inequalities. All three machines drive the same fixed point, , into existence.
A value function silently contains a policy
Once you have any value function — optimal or not — there is automatically a corresponding greedy policy: the one that, at each state, picks the action with the highest one-step lookahead value,
This is why value iteration doesn’t track policies during the loop. Every silently induces ; at convergence . Policy iteration just makes this greedy extraction explicit at every step, which lets it terminate exactly rather than asymptotically. Two sides of one coin.
Why iterating converges at all
Why doesn’t the loop oscillate forever or diverge? Because the Bellman optimality operator is a contraction: applying it to two different value estimates always brings them closer together by a factor of at least . Any two starting points converge to the same fixed point, geometrically fast. The reason is the discount factor — it scales down all disagreements between iterations. Discounting is what makes infinite-horizon dynamic programming possible at all; without it, the future could swamp the present and iterates would never settle.
03 · Formalism
Definitions and equations
We assume the setting of Chapter 8: a discounted infinite-horizon MDP with finite and , .
The Bellman operators (recap from Ch. 8)
For a fixed policy , the Bellman expectation operator acts on a value function by
In matrix form, with and , this is simply . Linear in .
The Bellman optimality operator replaces the policy-weighted sum with a maximum:
Non-linear in because of the . Still a contraction in .
- Fixed points
- is the unique fixed point of ; is the unique fixed point of .
- Contraction
- for any : , and the same for .
- Monotonicity
- if componentwise, then .
Deep dive
Before the infinite-horizon machinery, the cleanest possible DP. If the agent acts for exactly steps, the optimal value is computed by backward recursion:
with terminal condition . The optimal action at stage is the argmax of the same bracket. Total cost — versus for brute force. The infinite-horizon discounted case is the limit : the recursion no longer terminates, so we replace “step backward from the horizon” with “iterate the Bellman operator to its fixed point.”
Iterative policy evaluation
For a fixed policy , satisfies the linear system . Two ways to compute it:
Cost . Always invertible because makes strictly diagonally dominant.
Cost per sweep . Converges geometrically: .
Policy improvement
Given any value function , the greedy policy with respect to is
Ties broken arbitrarily. If , this is the action that maximises .
Policy improvement theorem
Let be deterministic policies. If for every , then for every .
In particular, the greedy policy with respect to is at least as good as . If equality holds everywhere, is already optimal. (Proof in the exam-intel section — the unrolling argument is short and worth memorising.)
Policy iteration
Putting the pieces together:
Two phases per iteration: policy evaluation (solve the linear system) and policy improvement (act greedily). Terminates exactly when the policy stops changing.
Because there are only finitely many deterministic policies and each iteration strictly improves the policy (or terminates), PI converges in a finite number of steps.
Value iteration
Iterate the Bellman optimality operator directly:
No explicit policy. After convergence, extract as the greedy policy of .
An equivalent formulation works directly with Q-values:
Reads off the optimal policy with no separate greedy step: . Memory is instead of , but no model query at extraction time — exactly why model-free RL (Ch. 10) prefers Q-values.
Value iteration converges
For any initial , the sequence converges to in , with .
A practical stopping rule
If , then
A looser but commonly cited form replaces with in the numerator. We can only measure successive-iterate differences, never the gap to directly — this inequality converts the measurable signal into a certificate.
Linear programming — primal
The fixed-point condition (componentwise) characterises supersolutions of the Bellman equation. is the smallest supersolution — which is exactly an LP:
variables, constraints. The weights (often the initial-state distribution) make the objective strictly proper without changing the optimum.
The constraints encode ” lies above the Bellman backup.” Among all such , the LP picks the one with smallest weighted sum — and that point is exactly .
Linear programming — dual
The dual introduces variables , one per state-action pair:
variables, equality constraints. The dual variables admit a beautiful interpretation.
The dual variables are the discounted state-action occupancy measures under a policy : how often, in present value, the agent visits when starting from and following ,
The equality constraints are the discounted Chapman–Kolmogorov flow equations: occupancy in comes from initial probability plus discounted transitions into . Maximising over flows gives the best long-run reward, and the optimal policy is read off as .
Three machines, one fixed point
Policy Iteration
Alternate exact evaluation and greedy improvement. Few iterations, each expensive (a linear system). Terminates exactly in finitely many steps. Cost: eval + improve .
Value Iteration
Iterate Bellman optimality. Many iterations, each cheap. Geometric convergence at rate . Stop when iterates differ by less than . Cost: per sweep.
Linear Programming
One LP, polynomial-time solver. Strong worst-case bounds; impractical at large state-action counts due to constraint blow-up. The dual exposes occupancy measures. Cost: .
04 · Worked example
Three states, two actions, by hand
We solve a tiny MDP three different ways — policy iteration, value iteration, and the LP — and watch the same answer drop out.
Why this example is instructive
Three things to watch. One: the “obvious greedy” plan (grab the from immediately) turns out suboptimal — the discounted infinite loop beats it. That kind of finding requires a solver. Two: the three algorithms reach the same answer through visibly different paths. Three: the LP’s constraints “select” the optimal action at each state by going tight.
1 · The MDP
Three states , where is an absorbing terminal with zero reward. Two actions in and . Discount . Transitions deterministic; rewards on transition.
| State | Action | Next state | Reward |
|---|---|---|---|
| · |
Intuition first: the big prize is the at . We should reach from (action , reward 5), then cash out (action , reward 10). Let’s confirm by algorithm.
2 · Policy iteration — from a bad guess
Start with that always picks : , . Evaluate: both states go straight to , so , . Improve greedily:
So , — the policy changed at . Continue.
3 · Policy iteration — the surprise, then convergence
Evaluate : , . Improve:
At , action now beats ! Update to , . Evaluate : now both states cycle, :
Improve once more: and . Policy unchanged. Stop. , .
The optimal policy says: stay in the loop forever, collecting every two steps. Our naive intuition was wrong — discounting doesn’t kill the loop because .
4 · Value iteration
Initialise and sweep the optimality operator. At , and . The values march toward at rate :
| 0 | 0.00 | 0.00 | — |
| 1 | 5.00 | 10.00 | 10.00 |
| 2 | 14.00 | 10.00 | 9.00 |
| 3 | 14.00 | 12.60 | 2.60 |
| 5 | 16.34 | 14.71 | 2.11 |
| 10 | 22.08 | 19.87 | — |
| 50 | 26.31 | 23.68 | — |
| 26.32 | 23.68 | — |
Once stable, the greedy policy is (since ) and (since ). Same answer as PI.
5 · The LP view
Set . The primal LP is
At the optimum, exactly one constraint per state is tight — the optimal action. The tight set , , is the same linear system we solved in step 3: . The slack on the two non-tight constraints (action at and ) certifies those actions are suboptimal.
Three lenses, one fixed point
- PI: 3 iterations until the policy stops changing; each solved a 2×2 linear system exactly.
- VI: dozens of one-step max-backups; geometrically convergent.
- LP: a single 3-variable, 5-constraint program, solved by simplex in a constant number of pivots.
All three return , , , with optimal action at both non-terminal states.
05 · Visual explanation
The geometry of dynamic programming
The Bellman backup as a tree
Every Bellman update is a one-step game tree: from a state, branch on actions; from each action, branch on possible next states (weighted by ); collect reward; bring back the discounted value of the leaf. averages over actions using ; takes the max.
The shape is identical. The only difference is the action node: expectation averages with ; optimality takes a . That one symbol — sum vs max — is the entire algorithmic gap between evaluating a policy and finding the best one.
Why the iteration converges
Picture the space of value functions as . The operator maps this space to itself, and applying it to any two value functions brings them at least a factor closer in max-norm. After sweeps the disagreement with has radius . For the error halves every sweeps; for , every . Convergence is geometric but slows as — you can watch this directly in the contraction widget below.
Generalized Policy Iteration — the unifying picture
Every algorithm in this chapter is an instance of one master pattern. Two arrows are in tension: one pulls toward (evaluation makes the value consistent with the policy); the other pulls toward (improvement makes the policy consistent with the value). Both arrows are zero at exactly one point: .
Policy iteration takes the evaluation arrow all the way (exact ) before improving. Value iteration applies one tiny piece of evaluation before each improvement — and because the greedy step is implicit in the of , the two arrows fuse into a single update. Modified policy iteration sits between: run the inner evaluation loop for sweeps instead of to convergence, then improve. recovers value iteration; recovers exact policy iteration; intermediate is often fastest in practice.
The LP polytope
In the primal LP, each constraint is a half-space in . The feasible set — the intersection of these half-spaces — contains all overestimates of , anything satisfying . The objective with positive picks the smallest such overestimate, which is itself, sitting at a vertex where exactly one constraint per state is tight — and the tight constraint names the optimal action there.
06 · Hands-on
Try it yourself
Three widgets, each illustrating one core idea. Drag, click, watch the numbers update.
First, step value or policy iteration on a 4×4 gridworld (constant reward, two terminal corners). Press Step to apply one Bellman optimality backup (VI) or one full evaluation + greedy improvement (PI), and watch converge and the greedy arrows settle.
Step value & policy iteration on a 4×4 gridworld
A 4×4 grid; the top-left and bottom-right squares are terminal (shaded). Every move costs −1 until termination. Pick a discount γ, choose VI or PI, and press Step to apply one Bellman optimality sweep (VI) or one full evaluation + greedy improvement (PI). Numbers are Vₖ; arrows show the greedy policy.
Next, walk policy iteration through the exact 3-state worked example, alternating evaluation and greedy improvement with the full -table exposed — watch the argmax flip and the policy converge to .
Policy iteration, evaluation ↔ improvement
The 3-state worked-example MDP. Pick a starting policy and a discount, then step the algorithm: each iteration evaluates the current policy exactly (a 2×2 linear system) and improves it greedily from the full Q-table. PI stops the moment the greedy action equals the current action in every state.
Finally, feel the contraction: run value iteration on the same 3-state MDP and plot on a log scale against . Slide and watch the slope — it is exactly , the geometric rate the contraction guarantees.
Feel the contraction — how fast does VI converge?
Value iteration on the 3-state MDP of §04. The plot shows ‖Vₖ − V*‖∞ on a log scale against the sweep count k. The dashed amber line is the contraction guarantee γᵏ·‖V₀ − V*‖∞ — slide γ and watch the actual error hug a straight line of slope log γ.
V* ≈ (s₁: 26.32, s₂: 23.68, s₃: 0.00)
07 · Exam intel
What the exam actually tests
This chapter loads several short proofs and at least one numerical walk-through. Seven patterns cover essentially every question.
Prove the policy improvement theorem
Hypothesis: for all . Goal: for all . One chain of inequalities, applying the hypothesis once per unrolling step:
The infinite sum converges because and rewards are bounded. Corollary: greedy improvement either strictly improves the policy or leaves it unchanged — in which case Bellman optimality holds and .
Show that T-star is a γ-contraction in max-norm
Fix a state and let maximise the backup for , so . Then
A symmetric argument (swap and ) gives the lower bound, so . Banach’s fixed-point theorem then gives existence, uniqueness, and the geometric rate .
Derive the practical stopping rule
Suppose . By the contraction, . Telescoping and the triangle inequality give, for (so ),
The §3 version with a factor of 2 also accounts for the gap at iterate itself, giving . Either form works; the tighter one is preferable when available.
Run policy iteration on a small MDP
Typical setup: 2–3 states, 2 actions, . Start from a given policy, evaluate exactly (solve a 2×2 or 3×3 system), greedily improve, repeat — expect 2–3 iterations. Three things to nail: (i) write the Bellman equations in matrix form and solve; (ii) compute the full Q-table at each improvement, not just one action; (iii) stop only when every state’s greedy action matches the current policy.
State and interpret the dual LP
Write down both primal and dual. The dual variables are discounted occupancy measures, . The flow constraint says occupancy at = initial probability + discounted inflow. Maximising finds the occupancy pattern collecting the most discounted reward; read off .
Expectation vs optimality — which goes where?
A reliable trap. The Bellman expectation (sum over actions weighted by ) appears in iterative policy evaluation and the inner loop of policy iteration. The Bellman optimality (max over actions) appears in the value-iteration backup, the primal LP constraints, and policy improvement (one-step lookahead). The mnemonic: expectation evaluates, optimality optimises.
Compare the costs of DP methods
| Method | Per iteration | Iterations |
|---|---|---|
| Iterative policy eval | ||
| Direct policy eval | once | 1 |
| Value iteration | ||
| Policy iteration | cubic eval + improve | few (strongly polynomial) |
| Linear programming | end-to-end | — |
08 · Common mistakes
Where students get this wrong
Value iteration produces a policy at every step
Intermediate iterates need not correspond to any achievable policy — they are abstract fixed-point iterates. Only after convergence do we extract a policy by being greedy w.r.t. . The greedy policy can even be a non-monotone function of ; what is monotone is the contraction toward .
PI converges in fewer iterations, therefore PI is faster
Fewer iterations, yes — but each PI iteration solves a full linear system (or runs many evaluation sweeps). VI iterations are individually much cheaper. Which wins depends on , , , structure, and implementation. Modified PI (truncated evaluation) is often best in practice.
The iterate difference tells me the gap to V-star
Almost. The exact relation is when — a multiplicative blow-up by . With that factor is : an iterate change of only guarantees a gap of , not .
Confusing T-pi and T-star
is linear in — just . is non-linear because of the . Iterative policy evaluation uses (no policy update); value iteration uses (the greedy policy is updated implicitly every step). Mixing them up is the single most common slip on “which algorithm does what” questions.
DP is polynomial, so MDPs are easy
Polynomial in the number of states — and the number of states is typically exponential in the number of state variables (the curse of dimensionality). A 10×10 screen with 256 colours already has states, far beyond any DP method. That is exactly the motivation for function approximation and deep RL.
Classical PI evaluates the policy approximately
Classical PI evaluates exactly. The variant that evaluates approximately (run sweeps of iterative evaluation, then improve) is modified policy iteration. is value iteration; is exact PI. Related, but not the same algorithm.
09 · Self-check
Can you answer these?
Which statement about value iteration is true?
Policy iteration in a fully observable MDP with |S| states and |A| actions:
In the LP formulation of an MDP, what does the dual variable λ(s, a) mean?
You run value iteration with γ = 0.95 and observe ‖V_{k+1} − V_k‖∞ < 10⁻³. What can you conclude?
10 · Recap
One-screen summary
Chapter 09 — load-bearing ideas
- Brute-force is impossible. deterministic policies. Dynamic programming exploits the Bellman recursion to cache and reuse subproblem solutions.
- Two operators run the show. The Bellman expectation is linear in ; the optimality is non-linear (the max). Both are γ-contractions in .
- Policy evaluation. Solve either directly in or iteratively as at per sweep with rate .
- Policy improvement theorem. If everywhere, then everywhere. Greedy improvement is always safe.
- Policy iteration. Alternate exact evaluation and greedy improvement. Terminates exactly in finitely many iterations — few iterations, each expensive.
- Value iteration. Iterate to with . Stop when and certify .
- Linear programming. Primal: s.t. . Dual: optimise reward-weighted occupancy . Optimal policy .
- Curse of dimensionality. DP is polynomial in , but is typically exponential in the problem variables — the motivation for the approximate, sample-based methods of Chapter 10.
Could you teach this back?
Without looking back, can you: state what “solving an MDP” means in terms of and ; write the Bellman expectation and optimality equations and say which appears in which algorithm; explain in plain English why one greedy improvement step cannot make a policy worse; explain why value iteration converges (contraction) and at what rate (); sketch one iteration of policy iteration on a 2-state MDP; and write the primal LP and state what its dual variables mean physically? If any of those stick, revisit the matching section. If all six flow, you’re ready for Chapter 10 — where the model goes away and we learn these same values from samples.