AnyLearn
All lessons
AIadvanced

Dynamic Programming: Value and Policy Iteration

When you know the full MDP model, dynamic programming finds the optimal policy exactly. Learn the Bellman optimality equation, the contraction argument that guarantees convergence, and the concrete difference between policy iteration and value iteration — with a value-iteration code walkthrough.

Not signed in — your progress and quiz score won't be saved.
Lesson progress1 / 10

Planning vs learning

Dynamic programming (DP) sits at the planning end of the RL spectrum. You have full access to the MDP tuple (S,A,P,R,γ)(\mathcal{S}, \mathcal{A}, P, R, \gamma) and want to compute the optimal policy without interacting with the environment. Real problems rarely give you the true PP — but DP is the foundation everything else builds on, and modern model-based RL methods learn P^\hat{P} and then plan inside it.

Two key objects: the optimal value function V(s)=maxπVπ(s)V^\star(s) = \max_\pi V^\pi(s) and the optimal action-value function Q(s,a)=maxπQπ(s,a)Q^\star(s,a) = \max_\pi Q^\pi(s,a). Once you have either, extracting the optimal policy is trivial: π(s)=argmaxaQ(s,a)\pi^\star(s) = \arg\max_a Q^\star(s,a).

Full lesson text

All 10 steps on one page — for reading, reference, and search.

Show

1. Planning vs learning

Dynamic programming (DP) sits at the planning end of the RL spectrum. You have full access to the MDP tuple (S,A,P,R,γ)(\mathcal{S}, \mathcal{A}, P, R, \gamma) and want to compute the optimal policy without interacting with the environment. Real problems rarely give you the true PP — but DP is the foundation everything else builds on, and modern model-based RL methods learn P^\hat{P} and then plan inside it.

Two key objects: the optimal value function V(s)=maxπVπ(s)V^\star(s) = \max_\pi V^\pi(s) and the optimal action-value function Q(s,a)=maxπQπ(s,a)Q^\star(s,a) = \max_\pi Q^\pi(s,a). Once you have either, extracting the optimal policy is trivial: π(s)=argmaxaQ(s,a)\pi^\star(s) = \arg\max_a Q^\star(s,a).

2. The Bellman optimality equation

The optimal value functions satisfy a nonlinear recursion — the Bellman optimality equation:

V(s)=maxasP(ss,a)[R(s,a,s)+γV(s)]V^\star(s) = \max_a \sum_{s'} P(s' \mid s,a)\left[R(s,a,s') + \gamma V^\star(s')\right]

Q(s,a)=sP(ss,a)[R(s,a,s)+γmaxaQ(s,a)]Q^\star(s,a) = \sum_{s'} P(s' \mid s,a)\left[R(s,a,s') + \gamma \max_{a'} Q^\star(s',a')\right]

The max\max makes these nonlinear — unlike the expectation equation for a fixed π\pi, you cannot solve this with direct matrix inversion. But the right-hand side is a contraction mapping, so repeated application converges. That convergence is the theoretical spine of both value iteration and policy iteration.

3. The contraction argument (intuition)

Define the Bellman optimality operator T\mathcal{T}:

(TV)(s)=maxasP(ss,a)[R(s,a,s)+γV(s)].(\mathcal{T} V)(s) = \max_a \sum_{s'} P(s' \mid s,a)\left[R(s,a,s') + \gamma V(s')\right].

T\mathcal{T} is a γ\gamma-contraction in the \ell_\infty norm:

TVTVγVV.\|\mathcal{T} V - \mathcal{T} V'\|_\infty \le \gamma\, \|V - V'\|_\infty.

By the Banach fixed-point theorem, T\mathcal{T} has a unique fixed point VV^\star, and starting from any V0V_0 the iterates Vk+1=TVkV_{k+1} = \mathcal{T} V_k converge geometrically. The contraction factor γ\gamma sets the rate: with γ=0.99\gamma = 0.99, you need 700\approx 700 sweeps to reduce the initial error by 106×10^6\times.

4. Policy evaluation

The subroutine that computes VπV^\pi for a given fixed π\pi is called iterative policy evaluation. It applies the Bellman expectation operator repeatedly:

Vk+1(s)aπ(as)sP(ss,a)[R(s,a,s)+γVk(s)].V_{k+1}(s) \leftarrow \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s,a)\left[R(s,a,s') + \gamma V_k(s')\right].

This is a contraction in \ell_\infty with factor γ\gamma, so it converges to the true VπV^\pi. In practice you run it until Vk+1Vk<ϵ\|V_{k+1} - V_k\|_\infty < \epsilon for some small threshold. Policy evaluation is O(S2A)O(|\mathcal{S}|^2 |\mathcal{A}|) per sweep — the costly step that policy iteration must repeat for each new policy.

5. Policy improvement

Given VπV^\pi, can you build a strictly better policy? Yes — the policy improvement theorem guarantees it.

Define the greedy policy with respect to VπV^\pi:

π(s)=argmaxasP(ss,a)[R(s,a,s)+γVπ(s)].\pi'(s) = \arg\max_a \sum_{s'} P(s' \mid s,a)\left[R(s,a,s') + \gamma V^\pi(s')\right].

Then Vπ(s)Vπ(s)V^{\pi'}(s) \ge V^\pi(s) for all ss. The proof is a one-step argument: taking the greedy action in ss and then following π\pi is at least as good as just following π\pi, because the greedy action maximises the one-step look-ahead.

If π=π\pi' = \pi everywhere, improvement has stalled — and we've proved the policy is optimal.

6. Policy iteration

Policy iteration alternates evaluation and improvement until convergence:

StepWhat happens
EvaluateRun iterative policy evaluation to get VπkV^{\pi_k}
ImproveSet πk+1(s)=argmaxasP[R+γVπk(s)]\pi_{k+1}(s) = \arg\max_a \sum_{s'} P[R + \gamma V^{\pi_k}(s')]
CheckIf πk+1=πk\pi_{k+1} = \pi_k, stop — πk\pi_k is optimal

Policy iteration converges in a finite number of policy updates (the policy space is finite), typically far fewer than you'd expect. Empirically, 10-20 iterations often suffices even for large tabular MDPs. The bottleneck is the evaluation step, which itself requires many sweeps.

7. Value iteration

Value iteration skips full policy evaluation. It applies one sweep of the Bellman optimality operator per iteration:

Vk+1(s)maxasP(ss,a)[R(s,a,s)+γVk(s)].V_{k+1}(s) \leftarrow \max_a \sum_{s'} P(s' \mid s,a)\left[R(s,a,s') + \gamma V_k(s')\right].

Convergence is guaranteed by the contraction argument. The extracted policy at any iteration kk is πk(s)=argmaxa()\pi_k(s) = \arg\max_a(\cdot) — not necessarily optimal yet, but approaching it.

Practical trade-off:

  • Policy iteration: fewer outer iterations, each expensive (full evaluation).
  • Value iteration: more outer iterations, each cheap (one sweep).

For most problems, value iteration wins on wall-clock time because full policy evaluation is wasteful — the policy changes after just one improvement step anyway.

8. Value iteration in code

A compact NumPy implementation:

import numpy as np

def value_iteration(P, R, gamma, n_states, n_actions, tol=1e-8):
    """P[s, a, s'] = transition prob, R[s, a] = expected reward."""
    V = np.zeros(n_states)
    while True:
        Q = np.zeros((n_states, n_actions))
        for a in range(n_actions):
            # Q[s, a] = R[s, a] + gamma * sum_{s'} P[s,a,s'] * V[s']
            Q[:, a] = R[:, a] + gamma * (P[:, a, :] @ V)
        V_new = Q.max(axis=1)
        if np.max(np.abs(V_new - V)) < tol:
            break
        V = V_new
    policy = Q.argmax(axis=1)
    return V, policy

The inner loop vectorises over states; the @ is the transition-weighted sum. Stopping criterion: Vk+1Vk<ϵ\|V_{k+1}-V_k\|_\infty < \epsilon guarantees the extracted policy is within 2γϵ1γ\frac{2\gamma\epsilon}{1-\gamma} of optimal.

9. Convergence guarantees and stopping criteria

Three facts worth knowing precisely:

  1. Value iteration converges to VV^\star in the limit; it never reaches it in finite steps (unless the MDP has a special structure). The bound VkVγkV0V\|V_k - V^\star\|_\infty \le \gamma^k \|V_0 - V^\star\|_\infty gives the iteration count needed for any target accuracy.

  2. Policy iteration reaches VV^\star exactly in finite steps (the policy space is finite). In practice it also terminates when Vπk+1Vπk<ϵ\|V^{\pi_{k+1}} - V^{\pi_k}\|_\infty < \epsilon, accepting near-optimality.

  3. Modified policy iteration interpolates: run mm evaluation sweeps instead of full convergence before improving. At m=1m=1 it becomes value iteration; at m=m=\infty it becomes policy iteration. Choosing m10m \approx 103030 often dominates both extremes.

10. Why DP doesn't scale — and what comes next

DP's fatal flaw is the curse of dimensionality. A robot with 10 joint angles discretised to 100 positions each has 102010^{20} states — one sweep of value iteration is cosmically infeasible.

Three escape routes:

ProblemFix
Unknown PPModel-free methods (Monte Carlo, TD)
Huge $\mathcal{S}
Continuous actionsPolicy gradient methods

DP remains essential because:

  • It defines the target every approximate method is chasing.
  • Linear function approximation + DP gives approximate policy/value iteration with provable error bounds.
  • Modern model-based RL (MuZero, Dreamer) learns P^\hat{P} and then plans inside it, often with short-horizon DP rollouts.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. The Bellman optimality operator $\mathcal{T}$ is a $\gamma$-contraction in $\ell_\infty$. What does this guarantee?
    • The optimal policy is unique for every MDP.
    • Starting from any $V_0$, the iterates $V_{k+1} = \mathcal{T} V_k$ converge geometrically to $V^\star$.
    • Policy iteration terminates in at most $|\mathcal{A}|^{|\mathcal{S}|}$ steps.
    • Value iteration reaches $V^\star$ exactly in a finite number of sweeps.
  2. Policy iteration is guaranteed to terminate because:
    • Each policy update strictly increases $V^\pi$ at every state simultaneously.
    • The policy improvement theorem rules out cycles, and the finite policy space must eventually repeat.
    • The Bellman operator contracts the policy space with factor $\gamma$ at each step.
    • The evaluation step converges before the policy can change again.
  3. In the value iteration stopping criterion $\|V_{k+1} - V_k\|_\infty < \epsilon$, the sub-optimality of the extracted policy is bounded by:
    • $\epsilon$
    • $\gamma \epsilon$
    • $\dfrac{2\gamma \epsilon}{1-\gamma}$
    • $\dfrac{\epsilon}{1-\gamma}$
  4. What distinguishes value iteration from a single step of policy iteration?
    • Value iteration uses the expectation Bellman operator; policy iteration uses the optimality operator.
    • Value iteration applies one sweep of the optimality operator; policy iteration runs full policy evaluation before improving.
    • Value iteration requires knowledge of $P$; policy iteration is model-free.
    • Policy iteration updates all states simultaneously; value iteration updates states one at a time.
  5. Why does dynamic programming fail on problems with very large state spaces?
    • The Bellman equations are nonlinear and cannot be solved analytically in high dimensions.
    • Each sweep requires iterating over all states and actions, making cost exponential in the number of state variables.
    • The discount factor $\gamma$ must decrease as the state space grows to preserve convergence.
    • Policy evaluation is non-convex in high-dimensional state spaces.

Related lessons