◆ AI All-in-One

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
↗ Plan a path here

Read first

Markov Decision Processes

This leads to

Actor-Critic MethodsQ-Learning
The full path from zero — 6 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
  7. 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: v(s)=E[R+γ v(S′)]v(s) = \mathbb{E}[R + \gamma\, v(S')]. 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 p(s′,r∣s,a)p(s', r \mid s, a), policy π(a∣s)\pi(a \mid s), discount γ\gamma, and return Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}.

Two value functions

The state-value function of a policy π\pi is the expected return when you start in state ss and follow π\pi from then on:

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

The action-value function is the expected return when you start in ss, take action aa first (whatever π\pi would do), and follow π\pi after that:

qπ(s,a)=Eπ[Gt∣St=s,At=a]q_\pi(s, a) = \mathbb{E}_\pi\left[ G_t \mid S_t = s, A_t = a \right]

Action values are more directly useful. With qq you can choose the best action without knowing the environment's rules: just compare the numbers. That is why Q-Learning learns qq.

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: vπ(s)=∑aπ(a∣s) qπ(s,a)v_\pi(s) = \sum_a \pi(a \mid s)\, q_\pi(s, a).

The Bellman expectation equation

Start from Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1} and take expectations. The value of ss 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:

vπ(s)=∑aπ(a∣s)∑s′,rp(s′,r∣s,a)[r+γ vπ(s′)]v_\pi(s) = \sum_{a} \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a) \Big[ r + \gamma\, v_\pi(s') \Big]

Reading from left to right: for each action aa the policy might pick (with probability π(a∣s)\pi(a \mid s)), for each outcome (s′,r)(s', r) the world might produce (with probability pp), take the reward rr plus γ\gamma 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.

π(a | s) Bellman expectation backup: vπ average over the policy's actions, then over outcomes s a p(s′,r|s,a) r, s′ vπ(s) = Σₐ π(a|s) Σ p(s′,r|s,a) [ r + γ vπ(s′) ] max Bellman optimality backup: v* take the best action, average over outcomes s a p(s′,r|s,a) r, s′ v*(s) = maxₐ Σ p(s′,r|s,a) [ r + γ v*(s′) ] open circles: states · black dots: actions · information flows up, from the leaves to the root
Fig. 1 Backup diagrams. Left: the Bellman expectation equation averages over the policy's actions and then over the environment's outcomes. Right: the Bellman optimality equation takes the maximum over actions instead of the policy's average.

Worked example: the battery robot. Take the policy "search when high, recharge when low" from Markov Decision Processes, with γ=0.9\gamma = 0.9. The Bellman equation gives one equation per state:

v(high)=2+0.9 [0.7 v(high)+0.3 v(low)]v(low)=0+0.9 v(high)\begin{aligned} v(\text{high}) &= 2 + 0.9\,\big[0.7\, v(\text{high}) + 0.3\, v(\text{low})\big] \\ v(\text{low}) &= 0 + 0.9\, v(\text{high}) \end{aligned}

Substitute the second into the first: v(high)=2+0.63 v(high)+0.243 v(high)v(\text{high}) = 2 + 0.63\,v(\text{high}) + 0.243\,v(\text{high}), so 0.127 v(high)=20.127\, v(\text{high}) = 2. That gives v(high)=15.75v(\text{high}) = 15.75 and v(low)=0.9×15.75=14.17v(\text{low}) = 0.9 \times 15.75 = 14.17. 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 nn states, the Bellman equations for a fixed policy are nn linear equations in nn unknowns. You could solve them directly with matrix algebra, but that costs about n3n^3 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 v∗(s)v_*(s) is the largest value any policy can achieve from ss. 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

v∗(s)=max⁡a∑s′,rp(s′,r∣s,a)[r+γ v∗(s′)]v_*(s) = \max_{a} \sum_{s', r} p(s', r \mid s, a) \Big[ r + \gamma\, v_*(s') \Big]

and, for action values,

q∗(s,a)=∑s′,rp(s′,r∣s,a)[r+γmax⁡a′q∗(s′,a′)]q_*(s, a) = \sum_{s', r} p(s', r \mid s, a) \Big[ r + \gamma \max_{a'} q_*(s', a') \Big]

Once you know q∗q_*, an optimal policy is simply to pick arg⁡max⁡aq∗(s,a)\arg\max_a q_*(s, a) 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 v∗v_*, 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 V(s)=0V(s) = 0 everywhere. Then sweep through the states repeatedly, replacing each value with its one-step-lookahead maximum:

V(s)←max⁡a∑s′,rp(s′,r∣s,a)[r+γ V(s′)]V(s) \leftarrow \max_{a} \sum_{s', r} p(s', r \mid s, a) \Big[ r + \gamma\, V(s') \Big]

Stop when no value changes by more than a tiny threshold. Each sweep shrinks the worst error by at least a factor of γ\gamma (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:

  1. Policy evaluation: compute vπv_\pi for the current policy, by repeatedly applying the expectation equation until it settles.
  2. Policy improvement: make the policy greedy with respect to vπv_\pi. 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 γ=0.9\gamma = 0.9. Value iteration converges in 18 sweeps:

0.72 0.83 0.94 goal+1 0.63 wall 0.64 pit−1 0.54 0.47 0.53 0.37 0.47 0.42 0.46 0.40 start v*(s) and the greedy policy Icy floor: 80% intended move, 10% slip to each side. γ = 0.9 Darker green = higher value. Arrows: the action with the best one-step lookahead. Check one square (value 0.94): choose → next to the goal 0.8 × (1 + 0.9 × 0) goal + 0.1 × (0 + 0.9 × 0.94) slip ↑, bumps edge + 0.1 × (0 + 0.9 × 0.64) slip ↓ = 0.80 + 0.085 + 0.057 = 0.94 ✓ Next to the pit, the policy steers away: below the pit it picks ↓, the one move whose slips (← or → into the edge) can't reach the pit.
Fig. 2 Optimal values and the greedy policy for the icy gridworld, computed by the code below. Values are highest next to the goal and fall off with distance. Near the pit the policy chooses moves whose sideways slips cannot reach it.

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 0.8×(1+0.9×0)=0.8000.8 \times (1 + 0.9 \times 0) = 0.800.
  • With probability 0.1 it slips up, hits the edge and stays put: 0.1×(0+0.9×0.942)=0.0850.1 \times (0 + 0.9 \times 0.942) = 0.085.
  • With probability 0.1 it slips down to the square with value 0.635: 0.1×(0+0.9×0.635)=0.0570.1 \times (0 + 0.9 \times 0.635) = 0.057.

Total: 0.800+0.085+0.057=0.9420.800 + 0.085 + 0.057 = 0.942. 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 p(s′,r∣s,a)p(s', r \mid s, a). 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.
  • γ=1\gamma = 1 with loops. In a task where the agent can wander forever, undiscounted values may never converge. Use γ<1\gamma < 1 or make sure every policy eventually ends.
  • Comparing values across different γ\gamma. Values are in units of discounted reward, and they change with γ\gamma. 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 p(s′,r∣s,a)p(s', r \mid s, a) 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 q∗q_* using sampled transitions instead of the known pp. It is value iteration without a model, one experience at a time.
  • Deep Q-Networks represents qq with a neural network, so the idea scales to Atari screens.
  • Actor-Critic Methods methods learn vπv_\pi 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

  1. Set GAMMA = 0.5 and rerun. How do the values and the arrows change? Does the agent still avoid the pit?
  2. Remove the ice: make the move go the intended way with probability 1. Check that every value equals 0.9k−10.9^{k-1}, where kk is the number of steps to the goal.
  3. 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.

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. Under a policy, state s leads with certainty to state s′ with reward 1, and v(s′) = 5. With γ = 0.9, what does the Bellman equation give for v(s)?

  2. What is the one change that turns the Bellman expectation equation into the Bellman optimality equation?

  3. A bug gives the goal (a terminal state) a value of 0.8 instead of 0. What goes wrong?

  4. In the icy gridworld, the optimal policy just below the pit chooses 'down' rather than the natural 'left'. Why?

  5. What is the difference between value iteration and policy iteration?

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/bellman-equations.md