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?
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:
np.dot(P[s], V) computes in the code.
This whole setup is a Markov Decision Process (MDP), defined by five pieces:
| Symbol | Name | In this problem |
|---|---|---|
| S | States | the 5 cells: {1, 2, 3, 4, 5} |
| A | Actions | {Stay, Right, Left}, available in every state |
| T(s,a,s') | Transition function | probability of landing in s' given you took action a in state s |
| R(s,a,s') | Reward function | here it simplifies to R(s): +1 for leaving state 5, else 0 |
| γ | Discount factor | 0.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.
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:
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:
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."
The second bracket is exactly Vπ evaluated at whatever state s' the agent lands in after the first step — just discounted once more.
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':
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.
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":
and since the optimal value of a state is just the value of the best action available there:
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:
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:
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)."
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:
With γ = 0.5 fixed, here are the transition probabilities T(s,a,s') that this specific problem specifies:
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.
Succeeds w.p. 1/3 (moves one cell in that direction). Fails w.p. 2/3 (stays put).
There's nowhere further left to go, so this behaves exactly like Stay at state 1: 1/2 stay, 1/2 to state 2.
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.
Here's the full implementation. Click to expand — it's heavily commented so you can match every line back to the equations above.
# 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]}")
| Equation piece | Code | What 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') | V | the 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 |
np.dot just does it without a manual for-loop.
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.
| s'=1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| s=1 | .50 | .50 | 0 | 0 | 0 |
| s=2 | .25 | .50 | .25 | 0 | 0 |
| s=3 | 0 | .25 | .50 | .25 | 0 |
| s=4 | 0 | 0 | .25 | .50 | .25 |
| s=5 | 0 | 0 | 0 | .50 | .50 |
| s'=1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| s=1 | .67 | .33 | 0 | 0 | 0 |
| s=2 | 0 | .67 | .33 | 0 | 0 |
| s=3 | 0 | 0 | .67 | .33 | 0 |
| s=4 | 0 | 0 | 0 | .67 | .33 |
| s=5 | 0 | 0 | 0 | .50 | .50 |
| s'=1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| s=1 | .50 | .50 | 0 | 0 | 0 |
| s=2 | .33 | .67 | 0 | 0 | 0 |
| s=3 | 0 | .33 | .67 | 0 | 0 |
| s=4 | 0 | 0 | .33 | .67 | 0 |
| s=5 | 0 | 0 | 0 | .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.
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.
| action a | R(5) | γ · P[5]·V | Q(5,a) |
|---|---|---|---|
| Stay | 1.0 | 0.5 × 0.0 | 1.0 |
| Right | 1.0 | 0.5 × 0.0 | 1.0 |
| Left | 1.0 | 0.5 × 0.0 | 1.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.
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.
| action a | P[4]·V | R(4) + γ·(P[4]·V) |
|---|---|---|
| Stay | .25×0 + .50×0 + .25×1.0 = 0.250 | 0 + 0.5×0.250 = 0.125 |
| Right | .67×0 + .33×1.0 = 0.333 | 0 + 0.5×0.333 = 0.167 |
| Left | .33×0 + .67×0 = 0.000 | 0 + 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.
| action a | P[5]·V | R(5) + γ·(P[5]·V) |
|---|---|---|
| Stay | .50×0 + .50×1.0 = 0.500 | 1.0 + 0.5×0.500 = 1.250 |
| Right | .50×0 + .50×1.0 = 0.500 | 1.0 + 0.5×0.500 = 1.250 |
| Left | .33×0 + .67×1.0 = 0.667 | 1.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.
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.
Running the same loop 100 times converges to:
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).