Worked examples — Q-learning algorithm
Before we start, let's re-anchor the one machine we use over and over. Everything below is just this equation, run with different numbers:
The picture below is that same equation drawn as a number line — keep it in your head for every example.

Reading the figure. The blue dot on the left is our old belief . The yellow dot on the right is the TD target . The gap between them is the TD error (red span). The update slides the blue dot a fraction of the way toward yellow — landing at the green dot. Big = long slide; = lands exactly on yellow; = dots coincide, no motion. Every worked example is just "where do the two dots sit, and where does green land."
Let me define each letter once so nothing is unearned:
- = the state I'm in right now (e.g. a square on a grid). Think "where am I."
- = the action I just chose (e.g. "move right"). Think "what I did."
- = the reward the environment handed me for doing in . A single number, can be positive, negative, or zero.
- = the state I landed in after acting. Read "s-prime."
- = a possible next action, used only inside the . We look at all of them and keep the best.
- (alpha), the learning rate: how big a step I take, between 0 and 1. Small = cautious, big = jumpy.
- (gamma), the discount factor: how much I care about the future, between 0 and 1. 0 = only now, 1 = future matters as much as now.
- = the largest Q-value among all actions available in the next state. It answers "if I play perfectly from onward, how good is that?"
- (delta), the TD error: defined as — the gap between fresh evidence and old belief. It measures "how surprised was I?" The whole update is just "": nudge by alpha times the surprise. When , evidence agrees with belief and nothing changes.
- (a-star), the optimal action: the action with the highest Q-value in a state, . "Arg-max" means "the action that achieves the max," as opposed to which gives the max value. It answers "which move is best?" while answers "how good is the best move?"
- (epsilon), the exploration rate in ==-greedy==: a probability between 0 and 1. With probability the agent picks a random action (explore); with probability it picks the greedy (exploit). Typically start high (e.g. ) and decay toward 0 as learning matures — see Exploration-Exploitation Trade-off.
The scenario matrix
Every Q-update falls into one (or more) of these cells. The examples below are each labelled with the cell they cover.
| Cell | Scenario class | What's special about it |
|---|---|---|
| A | Next state is terminal | by definition — the future term vanishes |
| B | Zero reward () | Nudge comes purely from the discounted future |
| C | Negative reward () | Target can drop below old value; Q can go negative |
| D | (myopic) | Future is ignored entirely; Q collapses to immediate reward |
| E | (undiscounted) | Full future value; only safe in episodic tasks |
| F | (full replace) | Old belief thrown away; Q becomes the target exactly |
| G | Ties in the max | Two next-actions equal — max still well-defined, pick either |
| H | Off-policy update (suboptimal action taken) | The still points at optimal future |
| I | Stochastic reward (maximization bias) | Averaging over noisy targets; where Double Q-learning helps |
| J | Real-world word problem | Translating a messy story into |
| K | Exam twist — multi-step backward propagation | Watch value flow backward across several updates |
Nine of the eleven cells are single-line arithmetic; two (I, K) show emergent behaviour. Let's fill them all.
Worked examples
Forecast: Guess — does go up a little, up a lot, or down? Write your guess.
- Identify the future term. is terminal, so by definition — there is no future after the episode ends. Why this step? Terminal states are seeded with precisely so the recursion stops. If we forgot this we'd add phantom future value.
- Build the TD target. . Why this step? The target is "reward now plus discounted best future" — with no future, it's just the reward.
- Compute the TD error. . Why this step? The error is how surprised we are. We badly under-valued this move.
- Nudge. . Why this step? We move 10% of the way toward the target, not all the way — one lucky sample shouldn't overwrite everything.
Verify: Old value 0.5, target 10, we should land strictly between them and one-tenth of the gap up: . ✓ It went up a lot but not to 10 — matching cell A behaviour.
Forecast: With zero reward, is the update dead (no change) or does it still move? Guess.
- TD target. . Why this step? Even with no immediate reward, the discounted promise of a good next state (value 6) pulls this Q up.
- TD error. .
- Nudge. . Why this step? Value flows backward from good states even across zero-reward steps — this is how paths get "wired" toward distant goals.
Verify: . ✓ The update is alive — cell B proves reward does not freeze learning.
Forecast: Will stay at 0, go slightly negative, or crash way down?
- TD target. . Why this step? Punishment now, nothing good ahead — the target is squarely negative.
- TD error. .
- Nudge with the larger . . Why this step? A bigger learning rate means we believe this bad news faster. The agent will now avoid this square.
Verify: , negative as expected. ✓ Cell C confirmed: Q-values are signed, and half a step of lands us at .
Forecast: Which pushes higher, and by how much roughly?
- target. . Update: . Why this step? literally deletes the future term — the agent is a pleasure-seeking goldfish, caring only about the reward in front of it.
- target. . Update: . Why this step? counts the full future value (8) with no shrinkage. This is only safe in episodic tasks that end; in an endless task it can blow up to infinity.
Verify: myopic , undiscounted . The undiscounted update is bigger because it sees the reward ahead. ✓ Cells D and E covered — is the dial between short-sighted and far-sighted.
Forecast: Does the tie cause trouble? Where does end up with ?
- Resolve the max despite the tie. . Why this step? returns a value, not an action — two actions sharing the top value 6 is fine, the value is unambiguously 6. Ties only matter when we later choose an action (pick either winner), not here.
- TD target. .
- Full replace with . . Why this step? With the old value is completely discarded — becomes the target exactly. Great for deterministic worlds, terrible for noisy ones (one bad sample overwrites everything).
Verify: , which equals the target exactly. ✓ Cell F: . Cell G: the tie is harmless — still returns 6.
Forecast: We took the wrong action. Does the update still learn something useful?
- We update only the action we took, . Its old value is 2. Why this step? Q-learning updates the pair actually experienced — here .
- The target uses , not the action we took. . Why this step? This is the off-policy heart of the algorithm: the future term assumes we'll play optimally from (, i.e. it credits the optimal action of the next state), even though right now we're exploring badly. That's why Q-learning learns while misbehaving. (Contrast: SARSA would use the value of the action it actually takes next.)
- Nudge. .
Verify: . ✓ Cell H: even a suboptimal move produces a correct-toward-optimal update. See Temporal Difference Learning and Exploration-Exploitation Trade-off for why exploring is required for convergence.
Forecast: The true best next value is 0. Guess what reports.
- Take the max of the noisy estimates. . Why this step? always grabs the highest number, and noise pushes some estimate above the true 0. So systematically reports a value above the true 0 — this is maximization bias.
- Feed it into a target. With : — but the honest target is . We over-shot by . Why this step? Repeatedly selecting and evaluating with the same noisy max bakes in a positive error.
- The fix — Double Q-learning. Keep two independent tables and , each learned from different samples so their noise is uncorrelated. On each update we flip a coin to decide which table gets updated; the OTHER one supplies the evaluation. Concretely, when updating : first select the greedy action using , ; then evaluate that action with , giving target . In our numbers, if picks but , the target becomes — no systematic upward bias. Why this step? Independent tables mean the table that picks the winner isn't the same one that rates it, so an estimate that got lucky-high in is rated by an independent that did not share that luck — the bias cancels on average. The diagram below shows this select-in-one / evaluate-in-the-other split.

Reading the figure. Two stacked boxes are the tables (blue) and (green). The blue arrow shows selecting the winning action (arg-max), and the green arrow shows that same being evaluated by to form the target. The dashed coin at the top decides which table is the "selector" this step; next step the roles swap. The red label marks where ordinary Q-learning would instead evaluate with the same table — the source of the bias.
Verify: biased target ; unbiased-example target . ✓ Cell I demonstrated. Related: Deep Q-Networks (DQN), Prioritized Experience Replay.
Forecast: Translate the story into numbers first, then guess the new Q.
- Extract the tuple . , next-state best value . The messy sentence collapses to four objects. Why this step? Q-learning is domain-blind — grids, elevators, and servers are all just streams.
- Build the TD target. . Why this step? Reward now (latency met, ) plus the discounted promise of a lightly-loaded next state (value 7, shrunk by ).
- Compute the TD error. . Why this step? We badly under-rated this assignment — the surprise is large and positive.
- Nudge. . Why this step? We move 20% of the way toward the target. The scheduler now rates this assignment higher and will repeat it under similar load. Same math powers Atari Game Playing and Robot Control.
Verify: , and it lands strictly between the old value 3.5 and target 10.65 (sanity: units are all "expected discounted reward," consistent). ✓ Cell J: an English paragraph became one arithmetic line.
This example uses a figure — watch value seep backward from the goal.

The figure, read left to right. Four boxes are the states (green). The white arrows are the corridor moves, each tagged with its reward (yellow): three steps and the final into the goal. The red row underneath shows every value after episode 1 — notice only has tasted the goal (); the earlier states still read . The green row shows the same values after episode 2 — now has jumped to because the goal's value has crawled one box to the left. The yellow annotation arrow points at exactly this one-box-per-episode diffusion.
Forecast: After ONE pass, how many of the three Q-values are non-zero, and how many have actually "felt" the +10 goal? (Careful — this surprises people.)
Answer to the forecast: All three become non-zero after one pass, but only one () has felt the goal; the other two just recorded the step penalty. The goal's value has not reached or yet.
Ordering convention: within an episode the agent physically visits first, then , then , then GOAL — so the updates fire in that order. Keep this in mind; it is the whole trick.
- Ep 1, update at (fires first). At this moment (nothing learned yet). , . With : . Why this step? The first update sees only the step penalty; the downstream value is still 0.
- Ep 1, update at (fires second). Still . . Why this step? hasn't touched the goal yet at this instant, so again only registers.
- Ep 1, update at (fires third). GOAL is terminal so . . After episode 1: . Only felt the goal — the red row of the figure.
- Ep 2, update at (fires first). Now . . Why this step? absorbs 's (still goal-less) value — it gets slightly worse before it gets better.
- Ep 2, update at (fires second). Now . . Why this step? The goal's value has now crawled from into — one box left, exactly as the figure's yellow arrow shows.
- Ep 2, update at (fires third). (unchanged). After episode 2: — the green row.
Verify: After ep1: . After ep2: , . ✓ Cell K: value crawls one state backward per episode. The Bellman Equations fixed point is only reached after enough passes. This is exactly Markov Decision Processes planning done by trial and error.
Recall
Recall What is the TD error
and how does it drive the update? , the "surprise" ::: the whole update is ; when nothing changes.
Recall When is
equal to zero? When is terminal ::: because terminal states are seeded with , so the future term vanishes (Cell A).
Recall With
, what does become after an update? Exactly the TD target ::: the old value is fully discarded (Cell F).
Recall In
-greedy, what does control? The probability of picking a random (exploratory) action ::: with probability the agent picks the greedy optimal action .
Recall Why does Q-learning learn the optimal policy even while exploring badly?
The target uses ::: it evaluates the best future action , not the one actually taken — this is what "off-policy" means (Cell H).
Recall What causes maximization bias and what fixes it?
Taking over noisy estimates over-values states ::: Double Q-learning fixes it by using separate tables to select and to evaluate (Cell I).
Recall In a 3-state corridor, how far does goal-value propagate per episode?
One state backward per episode ::: value diffuses one hop at a time (Cell K).