Value Iteration, From MDPs to Code

A self-contained walkthrough: the original problem, the Bellman equations built up from scratch, and a numeric trace of the algorithm — connected line by line to the Python that solves it.
Contents
  1. The problem, in plain English
  2. Building blocks: what is an MDP?
  3. The value function
  4. Deriving the Bellman equations
  5. Value iteration as an algorithm
  6. This problem's exact transition rules
  7. The Python code (click to expand)
  8. Equation → code, side by side
  9. The matrices: which row gets grabbed
  10. Iteration k=0, traced by hand
  11. Iteration k=1, traced by hand
  12. Final answer after 100 iterations

01 The problem, in plain English

An agent lives on a 1-D strip of 5 cells. It gets +1 the moment it leaves cell 5 (the rightmost cell), and 0 otherwise. The game never actually ends — it just keeps collecting reward forever, discounted by γ = 0.5 for every step into the future. The question: for every starting cell, what's the best long-run strategy, and how much is it worth?

state 1
0
state 2
0
state 3
0
state 4
0
state 5
+1
R(s) = 1 only when leaving state 5; 0 everywhere else. Reward is earned when leaving a state, not upon arrival.

At each cell the agent picks one of three actions: Stay, move Right, or move Left. None of these are guaranteed to work — this is the twist that makes the problem interesting. The exact success/failure probabilities are given in the "This problem's exact transition rules" section below; roughly:

Why this matters: because actions are unreliable, the agent can't just greedily walk right every time — it has to reason about the expected outcome of each action, averaged over everywhere it might actually end up. That expectation-taking is exactly what the Bellman equation formalizes, and exactly what np.dot(P[s], V) computes in the code.

02 Building blocks: what is an MDP?

This whole setup is a Markov Decision Process (MDP), defined by five pieces:

SymbolNameIn this problem
SStatesthe 5 cells: {1, 2, 3, 4, 5}
AActions{Stay, Right, Left}, available in every state
T(s,a,s')Transition functionprobability of landing in s' given you took action a in state s
R(s,a,s')Reward functionhere it simplifies to R(s): +1 for leaving state 5, else 0
γDiscount factor0.5 — a reward k steps away is worth γᵏ of its face value today

"Markov" means the transition only depends on the current state and action — not on the whole history of how the agent got there. That's what lets T be written as a simple function of (s, a, s') rather than the entire past trajectory.

03 The value function

Fix a policy π (a rule for picking an action in each state). If the agent follows π forever starting from state s, it will earn a sequence of rewards r₀, r₁, r₂, ... The value of state s under π is defined as the expected sum of those rewards, discounted:

Definition of the value function
Vπ(s)  =  E [ r₀ + γ·r₁ + γ²·r₂ + γ³·r₃ + ...  |  s₀ = s, following π ]

The discount γ < 1 does two jobs: it makes the infinite sum converge to a finite number, and it encodes "a reward now is worth more than the same reward later" — with γ = 0.5, a reward two steps away only counts for a quarter of its face value.

The optimal value function V*(s) is the value under the best possible policy — the highest expected return achievable from state s:

Optimal value function
V*(s)  =  maxπ  Vπ(s)

04 Deriving the Bellman equations

The value function above looks like it requires knowing an infinite future. The trick — Bellman's key insight — is to notice that the sum is self-similar: everything after the first step is just "γ times the value of wherever you end up next."

Step 1 — peel off the first term

Vπ(s) = E[ r₀ ]  +  γ · E[ r₁ + γ·r₂ + γ²·r₃ + ... ]

The second bracket is exactly Vπ evaluated at whatever state s' the agent lands in after the first step — just discounted once more.

Step 2 — average over where the first step actually lands

Taking action a = π(s) from state s doesn't land you in a single guaranteed s' — it lands you in s' with probability T(s,a,s'). So the expectation becomes a weighted sum over all possible s':

Vπ(s)  =  Σs' T(s, π(s), s')  ( R(s, π(s), s')  +  γ·Vπ(s') )

This is the Bellman equation for a fixed policy π: the value of s is the immediate expected reward, plus the discounted expected value of whatever comes next — where "expected" means averaged over T.

Step 3 — make it optimal: introduce Q*

Define Q*(s,a) as: the value of being in state s, taking action a right now (regardless of whether a is "optimal"), and then acting optimally forever after. This separates "which action am I taking this instant" from "what happens afterward":

Q*(s,a)  =  Σs' T(s,a,s')  ( R(s,a,s')  +  γ·V*(s') )

and since the optimal value of a state is just the value of the best action available there:

V*(s)  =  maxa  Q*(s,a)

Step 4 — substitute one into the other

Plugging the V*(s) equation into the Q*(s,a) equation (replacing the V*(s') term inside it with maxa' Q*(s',a')) gives the recursive form of Q* purely in terms of itself:

Q*(s,a)  =  Σs' T(s,a,s')  ( R(s,a,s')  +  γ·maxa' Q*(s',a') )

And plugging the Q* equation into the V*(s) = maxa Q*(s,a) line gives the form we actually compute with — the Bellman optimality equation for V:

Bellman optimality equation
V*(s)  =  maxa  [  Σs' T(s,a,s')  ( R(s,a,s') + γ·V*(s') )  ]

This single equation packs in everything: "average over where each action might actually take you (Σs' T·(...)), then pick whichever action gives the best expected outcome (maxa)."

Why we can't just solve this directly: V* appears on both sides of the equation — it's a fixed-point equation, not a formula. Value iteration is the fix: start with a guess (V₀ = 0 everywhere), plug it into the right-hand side to get a better guess V₁, and repeat. This is guaranteed to converge to the true V* because the update is a "contraction" — each pass shrinks the error toward zero (roughly by a factor of γ per iteration).

05 Value iteration as an algorithm

Turning the fixed-point equation into an iterative update — replace the V* on the right with the current estimate Vk, and call the result Vk+1:

Value iteration update rule
Vk+1(s)  =  maxa  [  Σs' T(s,a,s')  ( R(s,a,s') + γ·Vk(s') )  ]
  1. Initialize V₀(s) = 0 for every state s.
  2. For each state s, compute Qk(s,a) for every action a, using the current Vk.
  3. Set Vk+1(s) = the largest of those Q-values, and record which action achieved it.
  4. Repeat. Once V stops changing (or after a fixed number of iterations), the recorded actions form the optimal policy π*.

06 This problem's exact transition rules

With γ = 0.5 fixed, here are the transition probabilities T(s,a,s') that this specific problem specifies:

Action: Stay

Succeeds (stays put) w.p. 1/2. Otherwise, w.p. 1/2 total, it slides to a neighbor — split evenly (1/4 each) between left and right neighbors at inner cells, or the full 1/2 to the single neighbor at an edge cell.

Action: Right / Left (general case)

Succeeds w.p. 1/3 (moves one cell in that direction). Fails w.p. 2/3 (stays put).

Edge case: Left from state 1

There's nowhere further left to go, so this behaves exactly like Stay at state 1: 1/2 stay, 1/2 to state 2.

Edge case: Right from state 5

There's nowhere further right to go, so this behaves exactly like Stay at state 5: 1/2 stay, 1/2 to state 4.

Note the asymmetry: moving Left from state 5 (toward the interior) is not a special case — it's a normal move with 1/3 success, 2/3 fail. Only moving further off the strip is special-cased.

07 The Python code

Here's the full implementation. Click to expand — it's heavily commented so you can match every line back to the equations above.

▶ value_iteration.py click to expand / collapse
# Import numpy, a library that lets us work with vectors and matrices
# (arrays of numbers) instead of writing manual for-loops for math.
import numpy as np

# ==================================================================
# STEP 1: Define the basic constants of the problem
# ==================================================================
n_states = 5          # the grid has 5 cells
gamma = 0.5            # discount factor from the Bellman equation
n_iterations = 100      # run value iteration exactly 100 times

# ==================================================================
# STEP 2: Define the reward function R(s)
# ==================================================================
# R(s) is earned when LEAVING state s. It's 1 only when s = state 5
# (0-indexed as R[4]), and 0 everywhere else.
R = np.zeros(n_states)
R[4] = 1.0

# ==================================================================
# STEP 3: Define the transition probability matrices
# ==================================================================
# For each action, P[s][s'] = probability of landing in s' given you
# started in state s and took that action. Every row sums to 1.

# --- Action = "Stay" ---
P_stay = np.array([
    [1/2, 1/2, 0,   0,   0  ],   # state 1 (edge): 1/2 stay, 1/2 to neighbor
    [1/4, 1/2, 1/4, 0,   0  ],   # state 2 (inner): 1/2 stay, 1/4 each side
    [0,   1/4, 1/2, 1/4, 0  ],   # state 3 (inner)
    [0,   0,   1/4, 1/2, 1/4],   # state 4 (inner)
    [0,   0,   0,   1/2, 1/2],   # state 5 (edge)
])

# --- Action = "Right" ---
P_right = np.array([
    [2/3, 1/3, 0,   0,   0  ],   # state 1: general rule (1/3 success)
    [0,   2/3, 1/3, 0,   0  ],   # state 2
    [0,   0,   2/3, 1/3, 0  ],   # state 3
    [0,   0,   0,   2/3, 1/3],   # state 4
    [0,   0,   0,   1/2, 1/2],   # state 5: SPECIAL CASE, same as Stay
])

# --- Action = "Left" ---
P_left = np.array([
    [1/2, 1/2, 0,   0,   0  ],   # state 1: SPECIAL CASE, same as Stay
    [1/3, 2/3, 0,   0,   0  ],   # state 2: general rule
    [0,   1/3, 2/3, 0,   0  ],   # state 3
    [0,   0,   1/3, 2/3, 0  ],   # state 4
    [0,   0,   0,   1/3, 2/3],   # state 5: general rule (not special!)
])

# Sanity-check: every row of every matrix must sum to 1
for name, P in [("Stay", P_stay), ("Right", P_right), ("Left", P_left)]:
    row_sums = P.sum(axis=1)
    assert np.allclose(row_sums, 1.0), f"{name} matrix rows don't sum to 1: {row_sums}"

actions = {"Stay": P_stay, "Right": P_right, "Left": P_left}

# ==================================================================
# STEP 4: Run value iteration
# ==================================================================
V = np.zeros(n_states)          # V_0(s) = 0 for all s
best_action = [None] * n_states

for k in range(n_iterations):
    V_new = np.zeros(n_states)

    for s in range(n_states):
        q_values = {}

        for action_name, P in actions.items():
            # P[s] = row s of the transition matrix = T(s, a, ·)
            # np.dot(P[s], V) = Σ_s' T(s,a,s') * V(s')  <- the Bellman sum
            expected_future_value = np.dot(P[s], V)

            # Q(s,a) = R(s) + gamma * (that expected future value)
            q_values[action_name] = R[s] + gamma * expected_future_value

        # V_{k+1}(s) = max_a Q(s,a)
        best_a = max(q_values, key=q_values.get)
        V_new[s] = q_values[best_a]
        best_action[s] = best_a

    V = V_new   # commit the whole sweep before the next iteration

# ==================================================================
# STEP 5: Print results
# ==================================================================
print("Value function after 100 iterations:")
for s in range(n_states):
    print(f"  V*(state {s+1}) = {V[s]:.6f}")

print("\nImplied optimal policy:")
for s in range(n_states):
    print(f"  state {s+1}: {best_action[s]}")

08 Equation → code, side by side

Bellman optimality update
Vk+1(s)  =  maxa [ Σs' T(s,a,s') · ( R(s,a,s') + γ·Vk(s') ) ]
Equation pieceCodeWhat it actually is
T(s,a,s')P[s]row s of the matrix for action a — a length-5 array of probabilities, one per landing state s'
Vk(s')Vthe current length-5 value array — index s' is Vk(s')
Σs' T(s,a,s')·Vk(s')np.dot(P[s], V)the entire summation, done in one call — this is the dot product
R(s,a,s')R[s]doesn't depend on a or s' here, so it's added once, outside the dot product
maxa [ ... ]max(q_values, key=q_values.get)picks the action whose Q-value dictionary entry is largest
Where the dot product comes from: the sum Σs' T(s,a,s')·V(s') is literally "multiply each transition probability by the value of where it leads, then add them up." That is the definition of a dot product between the probability row and the value vector — np.dot just does it without a manual for-loop.

09 The matrices: which row gets grabbed

P[s] pulls out one row — the row for the state you're standing in. Below, the row for state 4 (0-indexed row 3) is highlighted in all three action matrices. Reading that row left to right tells you: probability of landing in state 1, 2, 3, 4, 5.

P_stay
s'=12345
s=1.50.50000
s=2.25.50.2500
s=30.25.50.250
s=400.25.50.25
s=5000.50.50
P_right
s'=12345
s=1.67.33000
s=20.67.3300
s=300.67.330
s=4000.67.33
s=5000.50.50
P_left
s'=12345
s=1.50.50000
s=2.33.67000
s=30.33.6700
s=400.33.670
s=5000.33.67

Row s=4 in P_right already ends in [0,0,0,.67,.33] — no special-casing needed, it's the general "1/3 success, 2/3 fail" rule. The special cases only kick in at the true edges: row s=1 of P_left and row s=5 of P_right, both copied straight from P_stay.

10 Iteration k=0: V₀ = [0,0,0,0,0]

With everything at zero, the dot product term vanishes everywhere — only the reward R(s) can make a Q-value nonzero. This is why the reward first "seeps in" at state 5.

State 5, action = Left winner (tied)

P[5] · V =
0×V(1)=0
+
0×V(2)=0
+
0×V(3)=0
+
.33×V(4)=0
+
.67×V(5)=0
=
0.0
Q(5, Left) = R(5) + γ·0 = 1.0 + 0.5 × 0 = 1.0
action aR(5)γ · P[5]·VQ(5,a)
Stay1.00.5 × 0.01.0
Right1.00.5 × 0.01.0
Left1.00.5 × 0.01.0

All three tie at 1.0 (Python's max keeps the first max it sees in dict order — ties are broken arbitrarily). Every other state stays at Q=0 for every action, since R(s)=0 and the dot product is 0.

Result of iteration 0V₁ = [ 0,  0,  0,  0,  1.0 ]

11 Iteration k=1: V₁ = [0, 0, 0, 0, 1.0]

Now V(5)=1 is nonzero, so the dot product finally has something to grab onto for any state whose row has a nonzero entry in column 5 — that's states 4 and 5.

State 4, action = Right winner

P[4] · V =
0×V(1)=0
+
0×V(2)=0
+
0×V(3)=0
+
.67×V(4)=0
+
.33×V(5)=1.0
=
0.333
Q(4, Right) = R(4) + γ · 0.333 = 0 + 0.5 × 0.333 = 0.1667
action aP[4]·VR(4) + γ·(P[4]·V)
Stay.25×0 + .50×0 + .25×1.0 = 0.2500 + 0.5×0.250 = 0.125
Right.67×0 + .33×1.0 = 0.3330 + 0.5×0.333 = 0.167
Left.33×0 + .67×0 = 0.0000 + 0.5×0 = 0.000

"Right" wins because it puts the most probability mass (.33 vs .25 for Stay) directly on the one state that currently has value — moving toward the goal pays off first.

State 5, action = Left winner

P[5] · V =
.33×V(4)=0
+
.67×V(5)=1.0
=
0.667
Q(5, Left) = R(5) + γ · 0.667 = 1.0 + 0.5 × 0.667 = 1.333
action aP[5]·VR(5) + γ·(P[5]·V)
Stay.50×0 + .50×1.0 = 0.5001.0 + 0.5×0.500 = 1.250
Right.50×0 + .50×1.0 = 0.5001.0 + 0.5×0.500 = 1.250
Left.33×0 + .67×1.0 = 0.6671.0 + 0.5×0.667 = 1.333

At state 5, "Left" gives the highest chance (.67) of staying at/near state 5 itself, since moving left from 5 is a general-rule move with 2/3 failure probability — failing means staying at 5, which is good here. States 1–3 still get Q=0 everywhere, since their rows have zero weight on states 4 or 5.

Result of iteration 1V₂ = [ 0,  0,  0,  0.1667,  1.3333 ]

Each further iteration repeats the same dot-product mechanics, just with a less-zero V feeding in — the nonzero region spreads leftward by roughly one cell per iteration, like ripples from state 5.

12 After all 100 iterations

Running the same loop 100 times converges to:

state 1
0.0083
Stay
state 2
0.0250
Right
state 3
0.1000
Right
state 4
0.4000
Right
state 5
1.6000
Left

The optimal policy pushes right everywhere except at the goal, where "Left" maximizes the chance of not drifting away from the +1 reward once you're there (recall: the game never halts in this version).