Module contents
Lesson 7 of 37Core 105 min

Bellman optimality and value iteration

Derive Bellman optimality, value iteration and policy-loss bounds, then solve finite-horizon decisions by backward induction.

After this lesson you can

  • Prove contraction of the discounted Bellman optimality operator.
  • Use value iteration and residuals to certify value accuracy.
  • Bound the loss of a policy greedy with respect to an approximate value.
  • Solve finite-horizon and stopping problems by backward induction.
  • Compare synchronous, asynchronous and prioritized updates.

Before you start

From evaluating a policy to choosing one

In a finite MDP with SS states and AA actions available in each state there are ASA^S stationary deterministic policies. You could evaluate each and compare their values, but enumeration grows quickly. The optimality principle lets us reuse solutions to subproblems: after choosing an action, the optimal continuation value again depends only on the next state.

We work with finite states and actions, bounded expected rewards and 0≤γ<10\leq\gamma<1. These assumptions matter: in a continuing task with γ=1\gamma=1, sums can diverge and the operator need not be a contraction. An undiscounted episodic task can be solved under other conditions, but needs a specific argument.

Equations for the best continuation

Let r(s,a)=E[Rt+1∣s,a]r(s,a)=\mathbb E[R_{t+1}\mid s,a] and P(s′∣s,a)P(s'\mid s,a) be the transition. Optimal value V∗(s)V^*(s) is the supremum of expected return from ss over admissible policies; Q∗(s,a)Q^*(s,a) forces the first action and optimizes afterward. The Bellman optimality equations are

V∗(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a)V∗(s′)],V^*(s)=\max_a\left[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)V^*(s')\right], Q∗(s,a)=r(s,a)+γ∑s′P(s′∣s,a)max⁡a′Q∗(s′,a′).Q^*(s,a)=r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)\max_{a'}Q^*(s',a').

A greedy policy with respect to value VV chooses an action maximizing the expression in brackets. With respect to V∗V^*, any tie-breaking choice among maxima is optimal under the above assumptions. With respect to an approximation, that policy may be suboptimal. Nor should you confuse vector VV used for selection with the actual value VπV^\pi of the resulting policy.

The operator contracts distances

Define (TV)(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a)V(s′)](\mathcal T V)(s)=\max_a[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)V(s')]. If V≤WV\leq W componentwise, nonnegative transitions imply TV≤TW\mathcal T V\leq\mathcal T W. For a constant cc, T(V+c1)=TV+γc1\mathcal T(V+c\mathbf1)=\mathcal T V+\gamma c\mathbf1: the translation is discounted once.

To prove the Bellman contraction, use ∣max⁡afa−max⁡aga∣≤max⁡a∣fa−ga∣|\max_a f_a-\max_a g_a|\leq\max_a|f_a-g_a| and that each transition row is a distribution:

∣TV(s)−TW(s)∣≤γmax⁡a∑s′P(s′∣s,a)∣V(s′)−W(s′)∣≤γ∥V−W∥∞.|\mathcal T V(s)-\mathcal T W(s)| \leq\gamma\max_a\sum_{s'}P(s'\mid s,a)|V(s')-W(s')| \leq\gamma\|V-W\|_\infty.

Taking the maximum over ss, ∥TV−TW∥∞≤γ∥V−W∥∞\|\mathcal T V-\mathcal T W\|_\infty\leq\gamma\|V-W\|_\infty. This is an upper bound: the observed ratio can be smaller, even zero. If γ=0\gamma=0, the operator forgets the previous value in one application.

InteractiveTwo values in, two values out

Preparing the contraction.

Move two value functions and compare their distance with that between their Bellman images.

By Banach’s theorem, T\mathcal T has a unique fixed point UU. Choose a deterministic policy π∗\pi^* greedy with respect to UU: then Tπ∗U=TU=U\mathcal T_{\pi^*}U=\mathcal T U=U, and uniqueness of evaluation implies Vπ∗=UV^{\pi^*}=U. For any other stationary policy, TπU≤TU=U\mathcal T_\pi U\leq\mathcal T U=U; by monotonicity and evaluation convergence, Vπ≤UV^\pi\leq U. For history-dependent policies the same domination follows by comparing finite horizons and letting the discounted tail tend to zero. Thus U=V∗U=V^* and a stationary deterministic optimal policy exists in this finite discounted model. The proof does not automatically extend that conclusion to arbitrary continuous spaces or undiscounted criteria.

Sweeps and residual

Value iteration applies Vk+1=TVkV_{k+1}=\mathcal T V_k from an initial vector. By contraction,

∥Vk−V∗∥∞≤γk∥V0−V∗∥∞.\|V_k-V^*\|_\infty\leq\gamma^k\|V_0-V^*\|_\infty.

If rewards lie in [0,Rmax⁡][0,R_{\max}] and V0=0V_0=0, then ∥V0−V∗∥∞≤Rmax⁡/(1−γ)\|V_0-V^*\|_\infty\leq R_{\max}/(1-\gamma). For 0<γ<10<\gamma<1, requiring that bound to be at most ε\varepsilon gives a sufficient number of sweeps via logarithms; if the quotient is negative, zero suffice. With γ=0\gamma=0 handle the case separately: one sweep computes the immediate optimal value.

InteractivePropagating information across the board

Preparing the sweeps.

Advance sweeps and compare values, residual and greedy actions; the geometric bound is an upper limit.

An observable stopping rule uses residual δ(V)=∥TV−V∥∞\delta(V)=\|\mathcal T V-V\|_\infty. From the triangle inequality and contraction,

∥V−V∗∥∞≤δ(V)+γ∥V−V∗∥∞,∥V−V∗∥∞≤δ(V)1−γ.\|V-V^*\|_\infty\leq\delta(V)+\gamma\|V-V^*\|_\infty, \qquad \|V-V^*\|_\infty\leq\frac{\delta(V)}{1-\gamma}.

Thus, if you return that same VV, δ(V)≤(1−γ)ε\delta(V)\leq(1-\gamma)\varepsilon guarantees value error at most ε\varepsilon. If you stop when comparing Vk+1V_{k+1} with VkV_k, state which of the two you return and which residual you checked. Visual stabilization of the policy alone does not bound value error; a policy can also already be optimal while value error remains.

How costly is acting on an approximate value?

Suppose ∥V−V∗∥∞≤ε\|V-V^*\|_\infty\leq\varepsilon and choose π\pi greedy with respect to VV, so TV=TπV\mathcal T V=\mathcal T_\pi V. The greedy policy loss bound follows by writing

∥V∗−Vπ∥∞=∥TV∗−TπVπ∥∞≤∥TV∗−TV∥∞+∥TπV−TπVπ∥∞≤γε+γ(ε+∥V∗−Vπ∥∞).\begin{aligned} \|V^*-V^\pi\|_\infty &=\|\mathcal T V^*-\mathcal T_\pi V^\pi\|_\infty\\ &\leq\|\mathcal T V^*-\mathcal T V\|_\infty +\|\mathcal T_\pi V-\mathcal T_\pi V^\pi\|_\infty\\ &\leq\gamma\varepsilon+\gamma(\varepsilon+\|V^*-V^\pi\|_\infty). \end{aligned}

Rearranging yields ∥V∗−Vπ∥∞≤2γε/(1−γ)\|V^*-V^\pi\|_\infty\leq2\gamma\varepsilon/(1-\gamma). If you only know the residual of VV, you can substitute ε≤δ(V)/(1−γ)\varepsilon\leq\delta(V)/(1-\gamma); this gives a sufficient policy guarantee, which may be loose. For γ=0\gamma=0, the greedy immediate reward choice is optimal and the factor is zero.

InteractiveA guarantee versus observed error

Preparing the stopping-criteria comparison.

Compare residual and bounds with values and policies calculated for explicit models.

When remaining time matters

For finite horizon HH and terminal reward gg, define VH(s)=g(s)V_H(s)=g(s) and solve backward

Vt(s)=max⁡a[rt(s,a)+γ∑s′Pt(s′∣s,a)Vt+1(s′)],t=H−1,…,0.V_t(s)=\max_a\left[r_t(s,a)+\gamma\sum_{s'}P_t(s'\mid s,a)V_{t+1}(s')\right],\quad t=H-1,\ldots,0.

Backward induction produces a potentially different policy for each remaining time. In optimal stopping, one action terminates with a known payoff and another continues with an expected value. The classical secretary problem assumes random order, a known number of candidates, only relative ranks, no recall and the goal of choosing the best. The rule of rejecting approximately a fraction 1/e1/e is an asymptotic limit under those assumptions, not the exact threshold for every finite size.

In an American option on a binomial tree, each node compares exercise value with discounted continuation computed under the model’s valuation probabilities. Exercise depends on remaining time and the underlying asset price; parameters must satisfy the chosen tree’s assumptions. The lab implements both problems without presenting the asymptotic rule as a measured result.

A synchronous sweep uses previous iteration values for all states. Gauss–Seidel reuses updates already made during the sweep. An asynchronous update changes only some states; convergence guarantees require update coverage conditions. Prioritized sweeping concentrates work on states with significant residuals and their predecessors, but queue and maintenance costs matter. In all cases the number of states and transitions can make a full tabular representation impractical: this is one form of the curse of dimensionality.

First we solve our own 2×3 grid with deterministic moves, a step cost and two terminals. Then we reconstruct the classic 4×4 FrozenLake map and its slippery transitions: the intended action and its two neighbors are executed with probability 1/3. Goal and holes are absorbing with no subsequent reward; reaching the goal pays 1. The gambler’s problem uses capital 0 to 20, positive stakes up to the allowed limit, heads probability 0,4 and reward 1 on reaching 20. It uses γ=1 for this episodic problem: here the residual is diagnostic and cannot use the contraction bound for γ<1γ<1.

[ ]Value iteration, FrozenLake and the gamblerBrowser
import heapq
import numpy as np

def backups(P,R,V,gamma,legal):
    q=R+gamma*np.einsum('san,n->sa',P,V)
    return np.where(legal,q,-np.inf)

def value_iteration(P,R,gamma,legal,tol=1e-8,method='sync',limit=20000):
    S=len(R); V=np.zeros(S); updates=0
    if method in ('sync','gs'):
        for sweeps in range(1,limit+1):
            if method=='sync':
                V=backups(P,R,V,gamma,legal).max(axis=1)
                updates+=S
            else:
                for s in range(S):
                    q=R[s]+gamma*P[s]@V
                    V[s]=np.max(np.where(legal[s],q,-np.inf))
                    updates+=1
            residual=float(np.max(np.abs(backups(P,R,V,gamma,legal).max(axis=1)-V)))
            if residual<=tol: break
    elif method=='priority':
        # Predecesores del estado modificado, para actualizar solo prioridades afectadas.
        predecessors=[set(np.where(P[:,:,s].any(axis=1))[0]) | {s} for s in range(S)]
        versions=np.zeros(S,dtype=int); queue=[]
        def enqueue(s):
            q=R[s]+gamma*P[s]@V
            error=abs(np.max(np.where(legal[s],q,-np.inf))-V[s])
            versions[s]+=1
            heapq.heappush(queue,(-error,int(versions[s]),s))
        for s in range(S): enqueue(s)
        while queue and updates<limit*S:
            _,version,s=heapq.heappop(queue)
            if version!=versions[s]: continue
            q=R[s]+gamma*P[s]@V
            new=float(np.max(np.where(legal[s],q,-np.inf)))
            if abs(new-V[s])<=tol: continue
            V[s]=new; updates+=1
            for pred in predecessors[s]: enqueue(pred)
        residual=float(np.max(np.abs(backups(P,R,V,gamma,legal).max(axis=1)-V)))
    else:
        raise ValueError('Método desconocido')
    q=backups(P,R,V,gamma,legal)
    return V,np.argmax(q,axis=1),residual,updates

def small_grid():
    # Tablero 2×3: terminal negativo en 2, meta en 5; sin resbalamiento.
    S,A=6,4
    P=np.zeros((S,A,S)); R=np.zeros((S,A)); legal=np.ones((S,A),dtype=bool)
    moves=((0,-1),(1,0),(0,1),(-1,0))
    for s in range(S):
        row,col=divmod(s,3)
        for a,(dr,dc) in enumerate(moves):
            if s in (2,5):
                P[s,a,s]=1
                continue
            nr=min(1,max(0,row+dr)); nc=min(2,max(0,col+dc)); dest=3*nr+nc
            P[s,a,dest]=1
            R[s,a]=1.0 if dest==5 else (-1.0 if dest==2 else -.02)
    return P,R,legal

def frozenlake():
    grid=('SFFF','FHFH','FFFH','HFFG'); S=16; A=4
    P=np.zeros((S,A,S)); R=np.zeros((S,A)); legal=np.ones((S,A),dtype=bool)
    # Orden Gymnasium: izquierda, abajo, derecha, arriba.
    moves=((0,-1),(1,0),(0,1),(-1,0))
    for s in range(S):
        row,col=divmod(s,4)
        for a in range(A):
            if grid[row][col] in 'HG':
                P[s,a,s]=1
                continue
            for move in ((a-1)%4,a,(a+1)%4):
                dr,dc=moves[move]; nr=min(3,max(0,row+dr)); nc=min(3,max(0,col+dc))
                dest=4*nr+nc
                P[s,a,dest]+=1/3
                R[s,a]+=(grid[nr][nc]=='G')/3
    return P,R,legal

def gambler(goal=20,p_head=.4):
    P=np.zeros((goal+1,goal//2+1,goal+1)); R=np.zeros((goal+1,goal//2+1))
    legal=np.zeros_like(R,dtype=bool)
    for s in range(goal+1):
        if s in (0,goal):
            P[s,0,s]=1; legal[s,0]=True
        else:
            for stake in range(1,min(s,goal-s)+1):
                legal[s,stake]=True
                P[s,stake,s+stake]=p_head; P[s,stake,s-stake]=1-p_head
                R[s,stake]=p_head*float(s+stake==goal)
    return P,R,legal

P,R,legal=small_grid()
assert np.allclose(P.sum(axis=2),1) and np.allclose(R[[2,5]],0)
results={m:value_iteration(P,R,.9,legal,method=m) for m in ('sync','gs','priority')}
reference=results['sync'][0]
for method,(v,policy,residual,updates) in results.items():
    print('Cuadrícula 2×3',method,'actualizaciones de valor',updates,'residuo',round(residual,10),
          'cota error',round(residual/.1,8),'diferencia con síncrona',round(float(np.max(np.abs(v-reference))),8),
          'valor inicial',round(float(v[0]),6))

P,R,legal=frozenlake()
assert np.allclose(P.sum(axis=2),1) and np.allclose(R[[5,7,11,12,15]],0)
for gamma in (.9,.99):
    results={m:value_iteration(P,R,gamma,legal,method=m) for m in ('sync','gs','priority')}
    reference=results['sync'][0]
    for method,(v,policy,residual,updates) in results.items():
        # El residuo de la última tabla certifica error máximo ≤ residuo/(1−γ).
        print('FrozenLake',gamma,method,'actualizaciones de valor',updates,'residuo',round(residual,10),
              'cota error',round(residual/(1-gamma),8),'diferencia con síncrona',round(float(np.max(np.abs(v-reference))),8),
              'valor inicial',round(float(v[0]),6))

P,R,legal=gambler()
v,policy,residual,updates=value_iteration(P,R,1.0,legal,method='sync',tol=1e-9)
print('Jugador episódico γ=1: actualizaciones de valor',updates,'residuo',round(residual,10),
      'valor capital 10',round(float(v[10]),6),'apuesta voraz',int(policy[10]))
if residual>1e-9:
    print('Se agotó el límite antes de alcanzar la tolerancia')

The counter measures state-value updates, not total work: residual checks and priority updates also recompute values and are not included. The three variants are compared here by residual and updates; this does not prove which is faster. Ties are resolved by the first valid index and another tied policy may be equally optimal. The gambler’s terminal state has value zero because reward is paid on entering the goal.

In the secretary problem we assume uniformly random arrival order, observation of relative ranks only, one irrevocable choice and reward 1 only for choosing the absolute best person. For the American option we use a dividend-free CRR binomial tree and compare the right to exercise at each node with continuation. These are different stopping problems: the 1/e rule is only asymptotic for the first.

[ ]Secretary and American option via backward inductionBrowser
import math

def secretary(n):
    if not isinstance(n,int) or isinstance(n,bool) or n<1:
        raise ValueError('n debe ser entero positivo')
    # V[t]: probabilidad óptima antes de observar el candidato t.
    V=[0.0]*(n+2); stop=[False]*(n+1)
    for t in range(n,0,-1):
        continuation=V[t+1]
        stop[t]=t/n>=continuation
        V[t]=(max(t/n,continuation)+(t-1)*continuation)/t
    return V[1],stop

def cutoff_probability(n,skip):
    if not isinstance(n,int) or isinstance(n,bool) or n<1 or not isinstance(skip,int) or isinstance(skip,bool) or not 0<=skip<n:
        raise ValueError('Corte fuera de rango')
    if skip==0:
        return 1/n
    return (skip/n)*sum(1/j for j in range(skip,n))

def american_put(spot,strike,rate,volatility,maturity,steps):
    if not all(math.isfinite(x) for x in (spot,strike,rate,volatility,maturity)) or min(spot,strike,volatility,maturity)<=0 or not isinstance(steps,int) or isinstance(steps,bool) or steps<1:
        raise ValueError('Parámetros inválidos')
    dt=maturity/steps
    try:
        up=math.exp(volatility*math.sqrt(dt)); down=1/up
        p=(math.exp(rate*dt)-down)/(up-down)
    except (OverflowError,ZeroDivisionError) as exc:
        raise ValueError('Árbol no representable numéricamente') from exc
    if not 0<p<1:
        raise ValueError('Se requiere d < exp(r·dt) < u para ausencia de arbitraje')
    discount=math.exp(-rate*dt)
    european=[max(strike-spot*up**j*down**(steps-j),0) for j in range(steps+1)]
    american=european.copy()
    early=0
    for t in range(steps-1,-1,-1):
        next_e=[]; next_a=[]
        for j in range(t+1):
            e=discount*((1-p)*european[j]+p*european[j+1])
            continuation=discount*((1-p)*american[j]+p*american[j+1])
            intrinsic=max(strike-spot*up**j*down**(t-j),0)
            next_e.append(e); next_a.append(max(intrinsic,continuation))
            if intrinsic>continuation: early+=1
        european=next_e; american=next_a
    return american[0],european[0],early,p

n=50
optimal,stop=secretary(n)
cutoffs=[cutoff_probability(n,m) for m in range(n)]
best=max(range(n),key=lambda m:cutoffs[m])
asymptotic=int(n/math.e)
assert abs(optimal-cutoffs[best])<1e-12
assert abs(secretary(1)[0]-1)<1e-12
print('Secretaria: n',n,'corte exacto',best,'probabilidad',round(optimal,6),
      'corte floor(n/e)',asymptotic,'probabilidad',round(cutoffs[asymptotic],6))

american,european,nodes,p=american_put(100,100,.05,.2,1,50)
assert american+1e-12>=european
print('Put americano',round(american,6),'europeo',round(european,6),
      'nodos con ejercicio estrictamente preferido',nodes,'probabilidad neutral',round(p,6))

In the secretary problem the cutoff is the number of people rejected before accepting the next who exceeds all previous candidates. If none appears, the attempt fails; no final choice is forced. The tree requires the strict no-arbitrage condition d<exp⁡(r dt)<ud < \exp(r\,dt) < u. The American and European comparison shares parameters and exercise dates; the difference is the early-exercise premium for this discretization, not an observed quote.

Exercises

ProofThe Bellman contraction
Prove: Prove that the optimality operator T is a contraction in the supremum norm.
0
The MDP has finite state and action sets, bounded expected rewards, stochastic transition P and 0≤γ<1. Define (TV)(s)=maxₐ[r(s,a)+γΣs' P(s'|s,a)V(s')].

Step 1 of 3. How do you bound the difference between maxima at one state?

ProofFrom value error to decision loss
Prove: Bound the loss of a greedy policy with respect to an approximation V.
0
Let V be the optimal fixed point, ||V−V||∞≤ε and π a deterministic policy greedy with respect to V, so TπV=TV. For 0≤γ<1, Tπ is the evaluation operator of π.

Step 1 of 3. How do you compare V* and Vπ?

NumericHow many sweeps guarantee accuracy
For rewards in [0,1], V₀=0 and γ=0,99 (decimal comma), use ||Vₖ−V*||∞≤γᵏ/(1−γ). What is the smallest integer k guaranteeing error at most 10⁻⁶ under that bound?
QuizOptimal policies that look strange
In the episodic gambler’s problem, two legal stakes in a state have exactly the same optimal Q value. What does this imply for optimal policies?
CodeValue iteration by residual
Implement value_iteration(P,R,gamma,tol). P has shape (S,A,S), with 1≤S≤50, 1≤A≤10 and finite nonnegative stochastic rows; R has shape (S,A) with finite values in [−1,1]. gamma is finite real in [0, 0.99] (written [0,0,99] using a decimal comma in the source), tol is finite real in [10⁻⁹,1], excluding booleans. Rows of P must sum to one with absolute tolerance 10⁻¹². Start with V=0 and apply T(V)=maxₐ[R+gamma·Σs' P·V] synchronously until ||T(V)−V||∞≤tol, checked on the returned table. Return V, Q=R+gamma·P V and policy=argmaxₐ Q, breaking ties by the smallest index. Reject invalid data with ValueError and do not modify inputs.
import numpy as np

def value_iteration(P,R,gamma,tol):
  pass
Shift+Enter to run
[ ]Check the guaranteed number of sweepsBrowser
import math
k=math.ceil(math.log(1e-8)/math.log(.99))
print('Barridos garantizados:',k,'cota',.99**k/(1-.99),'cota anterior',.99**(k-1)/(1-.99))