Level 3 In-Depth AI · Reinforcement Learning
Value Functions and Bellman Equations
How good is each state, and each action in each state? Bellman's equations answer by relating every value to the values one step ahead, and value iteration and policy iteration use them to solve a gridworld exactly.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
Read first
Markov Decision ProcessesThe full path from zero — 6 concepts before this one
- What Is AI?
- Probability Basics
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Reinforcement Learning: The Basics
- Markov Decision Processes
- Value Functions and Bellman Equations
Read them roughly in this order. See it on the concept map →
Why it matters
To act well, an agent needs to know which situations are good to be in and which actions lead to them. A value function puts a number on exactly that. Once you have the right value function, acting optimally is easy: at each step, pick the action that leads to the highest value.
The Bellman equations are what make value functions computable. They say that the value of a state equals the reward you get now plus the discounted value of where you end up. That turns an infinite sum over the future into a small local relationship between neighbouring states. Every value-based RL method rests on this idea, from the exact dynamic programming in this chapter to Q-Learning, Deep Q-Networks, the critic in Actor-Critic Methods methods, and the value network of AlphaGo.
The intuition
Imagine you're lost in a city and every street corner has a sign showing how far it is to the train station. You don't need a map. At each corner, walk towards the neighbouring corner with the smallest number. The signs have done all the planning for you.
A value function is that set of signs. How would you put the signs up in the first place? Start at the station, where the distance is 0. Every corner next to it is 1 block away. Every corner next to those is 2 blocks away, and so on. Each sign is computed from its neighbours' signs. That is a Bellman equation: my value = what this step gives me + the value of where it takes me.
With randomness the idea is the same, except "where it takes me" becomes an average over the places you might end up, weighted by their probabilities.
The trick that makes this work is called bootstrapping: you update a guess using other guesses. At first all the signs are wrong. Each round of updates makes the signs near the goal correct, then the ones next to those, and the correct values spread outward until the whole map settles.
Key idea The value of a state is the expected immediate reward plus the discounted value of the next state: . Apply that rule over and over to every state and the values converge to the true ones. Then act greedily on them.
How it works
We use the notation of Markov Decision Processes: dynamics , policy , discount , and return .
Two value functions
The state-value function of a policy is the expected return when you start in state and follow from then on:
The action-value function is the expected return when you start in , take action first (whatever would do), and follow after that:
Action values are more directly useful. With you can choose the best action without knowing the environment's rules: just compare the numbers. That is why Q-Learning learns .
The two are linked. The value of a state is the average of its action values, weighted by how often the policy picks each action: .
The Bellman expectation equation
Start from and take expectations. The value of is an average over the action the policy picks, then over what the environment does, of the immediate reward plus the discounted value of the next state:
Reading from left to right: for each action the policy might pick (with probability ), for each outcome the world might produce (with probability ), take the reward plus times the value of the new state. Add it all up.
The backup diagram draws the same calculation as a tree. Values flow up, from the possible next states to the current one. Computing one node from its children is called a backup.
Worked example: the battery robot. Take the policy "search when high, recharge when low" from Markov Decision Processes, with . The Bellman equation gives one equation per state:
Substitute the second into the first: , so . That gives and . These are the exact values that the Monte Carlo simulation in Markov Decision Processes estimated as 15.73 and 14.18. Two equations replace thousands of simulated episodes.
For states, the Bellman equations for a fixed policy are linear equations in unknowns. You could solve them directly with matrix algebra, but that costs about operations. The iterative methods below scale much better.
The Bellman optimality equation
We want the best policy, not just the value of a given one. The optimal value function is the largest value any policy can achieve from . It satisfies a version of the Bellman equation with the policy's average replaced by a max. The optimal agent takes the best action, so
and, for action values,
Once you know , an optimal policy is simply to pick in every state. A policy that picks the highest-valued action is called greedy with respect to those values. The surprising fact is that being greedy with respect to , looking only one step ahead, is globally optimal. The value function has already folded the entire future into each number.
The max makes these equations nonlinear, so we can't solve them with one matrix inversion. We iterate instead.
Value iteration
Value iteration turns the optimality equation into an update rule. Start with everywhere. Then sweep through the states repeatedly, replacing each value with its one-step-lookahead maximum:
Stop when no value changes by more than a tiny threshold. Each sweep shrinks the worst error by at least a factor of (mathematically, the update is a contraction), so convergence is guaranteed and fast.
This family of methods, which compute values from a known model by sweeping the Bellman equation, is called dynamic programming, Bellman's own term from the 1950s.
Policy iteration
Policy iteration alternates two steps:
- Policy evaluation: compute for the current policy, by repeatedly applying the expectation equation until it settles.
- Policy improvement: make the policy greedy with respect to . In every state, switch to the action with the highest one-step lookahead.
The policy improvement theorem guarantees the new policy is at least as good as the old one in every state. Since a finite MDP has finitely many deterministic policies, the loop must end. It ends at an optimal policy, usually after very few rounds. Value iteration is the extreme case where evaluation is cut short after a single sweep.
Sutton and Barto call the general pattern generalized policy iteration: let an evaluation process and an improvement process push on each other until both are satisfied. Almost every RL algorithm in the following chapters fits that description. Actor-Critic Methods methods even name the two parts.
Solving the icy gridworld
Back to the gridworld from Reinforcement Learning: The Basics, now with the icy floor from Markov Decision Processes: each move goes the intended way with probability 0.8 and slips sideways with probability 0.1 each way. The goal gives +1, the pit −1, and . Value iteration converges in 18 sweeps:
Worked check. The square left of the goal has value 0.942. Its best action is "right":
- With probability 0.8 it reaches the goal: reward 1, and the goal is terminal, so its value is 0. That contributes .
- With probability 0.1 it slips up, hits the edge and stays put: .
- With probability 0.1 it slips down to the square with value 0.635: .
Total: . The equation holds exactly, as it must at convergence.
Look at the square just below the pit. Going "left" would usually be the natural move, but a slip up would drop the agent into the pit. The greedy policy picks "down" instead. Its sideways slips go left (harmless) or right (into the edge, so it stays put), and it can never fall into the pit. Nobody programmed that caution. It falls out of the equations.
For comparison, the start square is worth 0.473 under the optimal policy. Evaluating the uniformly random policy with the expectation equation gives −0.063 there. Policy iteration, started from "always go up", reaches the same optimal policy after 4 improvement rounds.
In code
Value iteration on the icy gridworld in plain Python. outcomes is the dynamics function . q_value is the one-step lookahead inside the Bellman equation.
import numpy as np
ROWS, COLS, GAMMA = 4, 4, 0.9
WALL, GOAL, PIT = (1, 1), (0, 3), (1, 3)
MOVES = {"↑": (-1, 0), "↓": (1, 0), "←": (0, -1), "→": (0, 1)}
SIDEWAYS = {"↑": "←→", "↓": "←→", "←": "↑↓", "→": "↑↓"}
STATES = [(r, c) for r in range(ROWS) for c in range(COLS) if (r, c) != WALL]
def move(s, a):
r, c = s[0] + MOVES[a][0], s[1] + MOVES[a][1]
ok = 0 <= r < ROWS and 0 <= c < COLS and (r, c) != WALL
return (r, c) if ok else s
def outcomes(s, a):
"""p(s', r | s, a) as a list: 80% intended move, 10% each sideways slip."""
result = []
for prob, a2 in [(0.8, a), (0.1, SIDEWAYS[a][0]), (0.1, SIDEWAYS[a][1])]:
s2 = move(s, a2)
reward = 1.0 if s2 == GOAL else -1.0 if s2 == PIT else 0.0
result.append((prob, s2, reward))
return result
def q_value(V, s, a): # one-step lookahead
return sum(p * (r + GAMMA * V[s2]) for p, s2, r in outcomes(s, a))
V = {s: 0.0 for s in STATES} # terminal states stay at 0
for sweep in range(1, 1000):
delta = 0.0
for s in STATES:
if s in (GOAL, PIT): continue
best = max(q_value(V, s, a) for a in MOVES) # Bellman optimality backup
delta = max(delta, abs(best - V[s]))
V[s] = best
if delta < 1e-6: break
print(f"converged after {sweep} sweeps\n")
for r in range(ROWS):
cells = []
for c in range(COLS):
s = (r, c)
if s == WALL: cells.append(" wall ")
elif s == GOAL: cells.append(" GOAL ")
elif s == PIT: cells.append(" PIT ")
else:
a = max(MOVES, key=lambda a: q_value(V, s, a)) # greedy policy
cells.append(f"{V[s]:.3f}{a}")
print(" ".join(cells))
# converged after 18 sweeps
#
# 0.717→ 0.827→ 0.942→ GOAL
# 0.629↑ wall 0.635↑ PIT
# 0.545↑ 0.473← 0.533↑ 0.368↓
# 0.473↑ 0.424↑ 0.458↑ 0.399←
This version updates V in place, so later states in a sweep already use the new values of earlier ones. That usually converges a little faster than keeping two copies. Replace max(...) with the policy's weighted average, sum(0.25 * q_value(V, s, a) for a in MOVES), and the same loop performs policy evaluation of the random policy.
Common pitfalls
- Giving terminal states a value. A terminal state's value must stay 0. Otherwise the agent "collects" the goal reward again and again. In the code the loop simply skips them.
- with loops. In a task where the agent can wander forever, undiscounted values may never converge. Use or make sure every policy eventually ends.
- Comparing values across different . Values are in units of discounted reward, and they change with . A value of 0.47 means nothing on its own.
- Ties in the greedy policy. Several actions can share the same value. Any of them is optimal, but your code should break ties consistently, or the printed policy will flicker between runs.
- The curse of dimensionality. Each sweep touches every state. That is fine for 16 squares and hopeless for Go or for raw pixels. Dynamic programming needs both a known model and a state space you can enumerate.
Watch out Dynamic programming assumes you know exactly. Real agents rarely do. If your model is wrong, the "optimal" policy is optimal for the wrong world. That is the gap that learning from experience (Q-Learning) and Model-Based RL and World Models address.
Where it leads
- Q-Learning applies the Bellman optimality equation for using sampled transitions instead of the known . It is value iteration without a model, one experience at a time.
- Deep Q-Networks represents with a neural network, so the idea scales to Atari screens.
- Actor-Critic Methods methods learn as a "critic" to guide the policy, which is generalized policy iteration with two networks.
- AlphaGo and its successors use a learned value network to judge Go positions, which cuts short the search tree.
- Asynchronous and prioritised dynamic programming update the states that are changing most, instead of sweeping everything.
A bit of history
Richard Bellman developed dynamic programming at the RAND Corporation in the early 1950s. He later said he chose the name partly because it sounded impressive and was hard to object to. His principle of optimality, that an optimal plan's remainder must itself be optimal, is what the Bellman equation expresses, and his book Dynamic Programming appeared in 1957. Ronald Howard introduced policy iteration in 1960. These methods were standard in operations research and control for decades before machine learning adopted them. In the 1980s and 1990s, the RL community, led by Sutton, Barto, Watkins and Bertsekas (whose Neuro-Dynamic Programming with Tsitsiklis appeared in 1996), recast them as the target that sample-based learning algorithms approximate. Bellman also coined the phrase "curse of dimensionality", the reason we need those approximations.
Try it
- Set
GAMMA = 0.5and rerun. How do the values and the arrows change? Does the agent still avoid the pit?- Remove the ice: make the move go the intended way with probability 1. Check that every value equals , where is the number of steps to the goal.
- Add a reward of −0.04 for every move (a "living cost"). What happens to the policy just below the pit? Try −0.5 as well.
Hint for 3: with a high enough living cost, risking the pit becomes better than taking the long safe way round.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Reinforcement Learning: An Introduction
The foundational RL textbook by the field's founders. Free PDF.
UCL Course on Reinforcement Learning
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.
A (Long) Peek into Reinforcement Learning
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.
Spinning Up in Deep RL
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/bellman-equations.md