Visual walkthrough — Q-learning algorithm
We assume you have never seen the notation , , , or . Every one of these is earned before it is used.
Step 1 — What are we even trying to measure?
WHAT. Picture a little robot standing on one square of a grid. It can step in four directions. We want a single number that answers: "If I am standing HERE and I step THIS way, how good is that in the long run?"
We name that number .
- (state) = which square the robot stands on — a situation.
- (action) = which way it steps — a choice.
- = the quality of making choice in situation .
WHY a number per (situation, choice)? Because "how good is this square" alone isn't enough — the square is only as good as the move you make from it. A square next to a cliff is fine if you step away, deadly if you step off. So goodness lives on the pair (square, move), not the square alone.
PICTURE. The robot on square , four arrows leaving it, each arrow labelled with its own value. The move we're scoring is the red one.

Step 2 — "In the long run" needs a ruler: the discount
WHAT. "Reward collected forever" could be an infinite pile of numbers. We tame it by making future rewards count a little less than present ones. Each step into the future, we multiply the reward by a shrink factor (Greek "gamma"), a number between and .
- = reward right now, counted fully (multiplied by ).
- = next reward, shrunk once.
- = two steps out, shrunk twice — and so on.
WHY shrink at all? Two reasons, one mathematical, one human. Mathematical: if the infinite sum stays finite (it's a geometric series), so is always a real number. Human: a reward today is worth more than the same reward in a hundred steps — impatience is built in.
PICTURE. A row of future rewards, each drawn shorter than the last because shrinks them; the red bar is the full-height now reward.

Step 3 — The recursion: value of here hides the value of there
WHAT. Look again at that long sum. Group everything after the first reward:
The bracket is exactly the same kind of thing we started with — the total future value, but starting from the next square . So the long sum folds up into one short line:
WHY fold it? Because we can never sum infinitely many terms by hand. But we can peel off one term and point at the rest. This trick — "value here = reward now + shrunk value of next" — is the Bellman idea, the backbone of all of TD learning.
PICTURE. Two squares linked by the red action arrow: current carries an immediate reward ; next square carries a "folded" blob standing for all remaining future value.

Step 4 — Which value of the next square? Take the best move:
WHAT. The "value of the next square " is still ambiguous — value doing which move next? Since we want the robot to eventually behave optimally, we assume that from it will pick the best available move. The tool for "pick the biggest of a set" is .
- = "scan over all next-actions , return the biggest value."
- The little star means "the optimal Q" — the true goodness once we act perfectly.
WHY and not average, and not the action we actually take? Because we're defining the value of ideal play. Ideal play never picks a worse move when a better one exists. This single is what makes Q-learning learn the optimal policy even while the robot wanders randomly — the hallmark that separates it from SARSA (which uses the move actually taken).
PICTURE. At , four candidate arrows with values ; the red one () is selected by and fed back as the next square's value.

Step 5 — We don't have the rulebook, so we sample
WHAT. The clean equation above secretly hides an average over all possible next squares (the world may be random). We don't know those odds. So instead of computing the average, we just try it once: take action , and see what the world actually hands us — one concrete reward and one concrete next square .
WHY sampling? This is what "model-free" means: no map, no probabilities. We learn purely from lived experience . That's why the same algorithm runs on Atari and robots where nobody can write the world's rulebook.
PICTURE. A slot machine of possible next squares; a single lever-pull lands on one red outcome — our one sample.

Step 6 — One sample is noisy, so nudge, don't replace: the learning rate and the TD error
WHAT. Our current stored guess is . Our fresh sample says it should be the target. First, name the gap between them the TD error (Greek "delta"):
- : things went better than our stored guess expected.
- : things went worse.
- : our guess was already spot-on — nothing to learn here.
Now, if we trusted one noisy sample completely we'd overreact. Instead, take a small step of size along that surprise:
Decoding every piece, right where it sits:
- = "replace the left with the right" (an update, not an equation).
- = the TD error we just defined — how surprised were we?
- (learning rate, ) = how far along that surprise we travel. Small = cautious averaging; = overwrite completely.
WHY a fraction ? Because the target jiggles from sample to sample. Nudging a little each time silently averages many samples, smoothing the noise — like slowly zeroing in rather than teleporting to each new rumour.
PICTURE. A number line: the old guess on the left, the target on the right, and a red arrow stepping a fraction of the gap. The gap itself is .

Step 7 — Edge cases: terminal states, , and
WHAT. Four corners the reader will eventually hit, each breaking the general picture in its own predictable way:
- Terminal (goal) state. When the episode ends there is no next square, so its future value is defined as . The update collapses to
— pure reward, nothing folded in. This is the seed: the true reward first enters the system only through terminal transitions, then spreads backward.
-
. The whole future term vanishes: . The robot becomes utterly short-sighted, chasing only the immediate reward.
-
(no discounting). Now future rewards are counted at full height forever. In a never-ending task the sum can grow without bound — diverges and the geometric-series trick of Step 2 no longer converges. So is only safe for episodic tasks (every run is guaranteed to hit a terminal state in finite time), where the reward pile is a finite sum. Our grid world is episodic, so would be legal there; a robot balancing forever needs or it explodes.
-
vs . At the old guess is thrown away entirely each step (fast but jittery). As the robot stops learning (frozen). Real training lives between.
WHY show these? Because a reader who has met all four corners is never ambushed — not by "why is my goal square value exactly the reward?", not by "why did my undiscounted blow up to infinity?"
PICTURE. Three mini-panels: a terminal square with its folded-blob crossed out (red), a arrow with the future greyed away, and an slider from frozen to jittery.

Step 8 — Watch a reward crawl backward (the payoff)
WHAT. Trace the parent note's grid. Reward: per step, at the goal, , , and every starts at . We follow the single pair — the square just left of the goal — across the first few times the robot happens to step through it.
First visit (old , since all start at ):
Second visit (old from last time; goal still worth ):
Third visit (old ):
Each visit closes of the remaining gap to , so climbs . No mystery starting value — every number is derived from the one before it, all the way back to the honest .
WHY it matters. Once knows it is worth something, the square before it samples its value and lights up too. Step by step the flows upstream against the direction of motion — value is not designed, it seeps backward from wherever reward lives.
PICTURE. The grid across episodes: the goal glows, then its neighbour, then the next — a red wave of value spreading backward toward the start.

The one-picture summary
Everything above is one loop: sample a transition → compute the TD error → nudge by → the goal's value seeps backward. This is the picture to keep — the five circled stages are exactly the five arrows you just walked through, closed into a cycle you repeat forever.

Recall Feynman retelling — say it like a story
I'm a robot on a square. I want one number per (square, move) telling me how good that move is in the long run — call it . "Long run" would be an endless pile of rewards, so I shrink each future one by ; that keeps the pile finite (unless , which only survives in tasks that always end) and makes me a bit impatient. That endless pile has a beautiful shortcut: value-of-here equals reward-now plus times value-of-the-next-square. Since I want to end up playing perfectly, I assume from the next square I'll pick my best move — that's the , and it's why I learn the optimal plan even while wandering. But I have no map, so I can't average over all possible next squares; I just try it once and see the reward and next square the world hands me. One try is noisy, so I measure my surprise (the TD error) and step a small fraction along it — not overwrite. Special cases: at the goal there's no future, so I just soak up the raw reward — and that's the spark. Each visit, that spark of value creeps one square backward, until eventually the very first square knows the shortest path home.
Recall Quick self-test
What does make Q-learning learn, and why is that off-policy? ::: It makes the target use the best next action, so converges to the optimal values even though the robot may be exploring randomly — the learned target ignores the actual (possibly suboptimal) action taken. That's the off-policy hallmark separating it from SARSA. In the terminal-state update, what happened to the term? ::: It's dropped (set to 0) because there is no next state — the update becomes , pure reward. Why can be dangerous, and when is it safe? ::: Undiscounted, an unending task sums infinitely many rewards and can diverge; it is only safe for episodic tasks that always reach a terminal state in finite time. Write the TD error and the update in terms of it. ::: , and .
Where to go next: the overestimation caused by that is fixed in Double Q-learning; scaling to huge state spaces needs Function Approximation and Deep Q-Networks (DQN), sped up by Prioritized Experience Replay. The exploration that guarantees convergence is the Exploration-Exploitation Trade-off over an MDP.