Bellman equations
贝尔曼方程
Derive policy and optimality equations, solve a two-state model, and stop value iteration using a checked residual bound.
bellman-equationsAn unrewarding move can lead to a valuable state
At workshop A, you can stay and earn 1 each step, or move to workshop B for immediate reward 0. At B, staying earns 2 each step. Use discount . Staying at A forever is worth 10. Moving to B is worth 18, because the first step earns nothing and later steps earn more.
Choosing the largest immediate reward would keep you at A. Choosing the largest immediate reward plus discounted continuation value sends you to B. The Bellman equations express this accounting exactly for a specified Markov decision process.
Expectation for a policy, maximum for an optimum
For a policy , define as expected return starting in state and following that policy. Split the return into its first reward and remaining return, then condition on the chosen action and next outcome:
This is the Bellman expectation equation. The outer sum averages over the policy’s actions, and the inner sum averages over environmental outcomes. In a finite model, let collect expected immediate rewards and collect transition probabilities under that policy. The same equation is linear:
For , the inverse exists for a stochastic ; equivalently, the convergent series of discounted powers defines the solution. This is policy evaluation: the action rule is fixed. Sutton and Barto, second-edition working draft, Section 3.7
For the optimal value in a finite discounted MDP with bounded rewards, choose the best first action and then continue optimally:
The maximum is outside the expectation over outcomes: an agent chooses an action before observing which random outcome occurs. Moving the maximum inside would grant extra information. A policy greedy with respect to this one-step lookahead at is optimal; it need not be greedy with respect to immediate reward. Sutton and Barto, working draft, Section 3.8
Value iteration repeatedly applies the operator to a current estimate. It is an algorithm for approaching a fixed point, whereas the Bellman optimality equation states what that fixed point satisfies. Using the maximum-norm distance and normalized transition probabilities gives:
Indeed, each action’s expected continuation differs by at most , and taking maxima cannot enlarge that bound. This contraction implies a unique fixed point. Combining it with the triangle inequality gives a useful stopping certificate:
CS188, Value Iteration develops the contraction argument. The residual bound here concerns the current , so the code returns that same vector when the bound is small enough.
Return an error bound with the values
For the opening example, , and moving from A gives . Staying at A forever gives 10. The Bellman comparison at the optimal value is between staying for one step then acting optimally, worth , and moving now, worth 18. These are different comparisons; do not substitute 10 for the first lookahead value.
The complete program uses synchronous updates: all new values read the same previous vector. It validates the model, returns a greedy policy and a residual-based value-error bound, and checks the analytic solution.
import math
model = {'A':{'stay':[(1.0,'A',1)], 'move':[(1.0,'B',0)]},
'B':{'stay':[(1.0,'B',2)]}}
def value_iteration(model, gamma=0.9, tolerance=1e-8, max_steps=10000):
if not 0 <= gamma < 1 or not math.isfinite(tolerance) or tolerance <= 0:
raise ValueError("discount in [0,1) and positive finite tolerance required")
if not model or type(max_steps) is not int or max_steps < 1:
raise ValueError("nonempty model and positive iteration limit required")
for actions in model.values():
if not actions:
raise ValueError("each state must have an action")
for outcomes in actions.values():
if not outcomes or any(not math.isfinite(p) or p < 0 or s not in model
or not math.isfinite(r) for p,s,r in outcomes):
raise ValueError("invalid transition")
if not math.isclose(sum(p for p,_,_ in outcomes),1,abs_tol=1e-12,rel_tol=0):
raise ValueError("transition probabilities must sum to one")
values = {s:0.0 for s in model}
for _ in range(max_steps):
new, policy = {}, {}
for s,actions in model.items():
q = {a:sum(p*(r+gamma*values[n]) for p,n,r in outcomes)
for a,outcomes in actions.items()}
if not all(math.isfinite(v) for v in q.values()):
raise ArithmeticError("nonfinite backup")
policy[s] = max(q, key=q.get)
new[s] = q[policy[s]]
bound = max(abs(new[s]-values[s]) for s in values)/(1-gamma)
if bound <= tolerance:
return values, policy, bound
values = new
raise RuntimeError("iteration limit reached before certification")
values, policy, bound = value_iteration(model)
error = max(abs(values['A']-18),abs(values['B']-20))
assert error <= bound+1e-12 and bound <= 1e-8
assert policy == {'A':'move','B':'stay'}
assert math.isclose(1+0.9*18,17.2)
assert value_iteration(model,gamma=0)[0] == {'A':1.0,'B':2.0}
assert value_iteration(model,gamma=0)[1]['A'] == 'stay'
try:
value_iteration(model,max_steps=1)
except RuntimeError:
pass
else:
raise AssertionError("uncertified values returned")
Let be the number of stored transition outcomes across all state–action pairs. Each sweep costs , so sweeps cost . A dense state-transition model has for bounded outcome storage per next state. Value vectors need extra memory, in addition to model and policy storage. A dense direct linear solve is an alternative for evaluating a fixed policy, not a direct solution of the maximum equation.
Discount and model assumptions carry the guarantee
As approaches one, the residual bound becomes less forgiving and the contraction slower. At , this proof no longer works. Proper terminating tasks, finite-horizon backward induction, and average-reward problems need their own assumptions and formulations.
The certificate assumes an exact specified model and exact arithmetic. Floating-point rounding adds numerical error; estimated transitions and rewards add modeling error not covered by this bound. The program’s tolerance is deliberately loose enough for its small example. A small value error also need not identify a unique action when competing action values are nearly tied.
For a large state space, representing all values or transitions can be impossible. Sampling and function approximation change both computation and convergence questions. A Bellman-style target inside a neural loss does not inherit every guarantee of tabular exact value iteration.
Read the order of operations
- Why is the optimality maximum outside the outcome expectation? Answer: the action is chosen before the random next outcome is known.
- At , which action is selected at A? Answer: stay, because only its immediate reward 1 matters.
- If and the Bellman residual is 0.02, what bound follows? Answer: value error is at most 0.2 under the stated exact-model assumptions.
- Does setting satisfy the equations? Answer: yes. At B, ; at A, the maximum of 17.2 and 18 is 18.
A shared equation does not mean a shared algorithm
Policy iteration alternates evaluation and improvement. Value iteration applies the optimality backup directly. Temporal-difference methods estimate related targets from samples, and Q-learning works with action values. Identify which operator is being estimated, which policy supplies data, and which assumptions justify the update. The cited Sutton–Barto PDF is a 2014–2015 working draft, explicitly distinguished from the final 2018 edition.
Make a prediction, then check
With γ=0.9 and Bellman residual 0.02, what is the value-error bound for the exact model?
Learning objectives
- Derive policy expectation and optimality equations from return recursion.
- Derive a residual error bound from contraction and implement value iteration with a stopping certificate.
Prerequisites & connections
Explore related knowledge →References
- CS188 Textbook — Value Iteration
UC Berkeley CS188 course contributors - Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Re-derived expectation/optimality equations, contraction, and the residual error bound for the returned vector; recalculated A=18, B=20 and the distinction from immediate-reward greediness.
- For 12 random three-state MDPs, enumerated eight deterministic policies and solved each with independent elimination; results matched value iteration and its residual certificate; executed γ=0 and iteration-limit rejection.
- Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.
Source locations checked:
- CS188 Textbook — Value Iteration · §4.3: Bellman optimality backup and maximum-norm contraction
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · 2014–2015 working draft, §§3.7–3.8; PDF pp.85 and 90–91: expectation, optimality, and greedy continuation
Related topics