Say you are training a value function and you have two standard choices. One-step TD learning updates after every step but learns slowly, because each reward moves back only one state per episode. Monte Carlo waits until the episode ends and uses the full return, which is unbiased but noisy. Neither one is the best choice on most problems.
n-step bootstrapping is the family of methods in between. An n-step TD update uses the next n real rewards and then adds the current value estimate of the state reached after n steps. With n = 1 it is one-step TD, and with n as long as the episode it is Monte Carlo. The idea and the algorithms come from chapter 7 of Sutton and Barto’s Reinforcement Learning: An Introduction (2nd edition). This guide explains the n-step return, implements n-step TD prediction on the book’s 19-state random walk, and shows real results: in our run, intermediate values of n beat both extremes.
Key Takeaways
- The n-step return adds up
ndiscounted rewards, then bootstraps from the estimated value of the statensteps ahead. - One-step TD (
n = 1) and Monte Carlo (n= episode length) are the two ends of the same family. - Larger
nuses more real reward and less of the current estimate: less bias, more variance. - On the 19-state random walk, our best setting was
n = 4with step size 0.4 (RMS error 0.263), better than the best one-step TD result (0.345) and the bestn = 32result (0.363). - The best
nand the best step size depend on each other. Largernneeds a smaller step size.
The Source: Sutton and Barto, Chapter 7
Richard S. Sutton and Andrew G. Barto’s Reinforcement Learning: An Introduction, second edition (MIT Press, 2018), is the standard textbook for this topic. Chapter 7, “n-step Bootstrapping”, introduces n-step TD prediction, n-step Sarsa and related methods. The authors make the full book available free on the book’s official page. The notation and the random walk example below follow section 7.1.
What Is Bootstrapping in Reinforcement Learning?
In reinforcement learning, bootstrapping means updating an estimate partly from another estimate. One-step TD learning does this: it moves V(S_t) toward R_{t+1} + γ V(S_{t+1}), which mixes one real reward with the current guess for the next state.
The word means something different in statistics, where the bootstrap is a resampling method for measuring uncertainty. We cover that one in our post on the Poisson bootstrap. The two share a name but not a method.
The n-Step Return
The n-step return from time t is:
G_{t:t+n} = R_{t+1} + γ R_{t+2} + ... + γ^(n-1) R_{t+n} + γ^n V(S_{t+n}) The first part is n real rewards, discounted by γ. The last term is the bootstrap: the current estimate of the value of the state reached after n steps. If the episode ends before step t + n, the return is just the rewards up to the end, with no bootstrap term.
The update rule then moves the estimate toward that return, with step size α:
V(S_t) ← V(S_t) + α [ G_{t:t+n} − V(S_t) ] There is one catch. The return for time t needs rewards up to time t + n, so the update for S_t can only happen n steps later. n-step methods always run n steps behind the agent.
Why an Intermediate n Can Win
Think about a reward that arrives at the end of a long episode. With one-step TD, that reward moves back by one state per episode, so it takes many episodes to reach the start. With Monte Carlo, it reaches every state at once, but each update depends on the whole random path, so the estimates jump around.
An n-step update spreads the reward n states back in one episode while still averaging over the noise beyond that point through V(S_{t+n}). Sutton and Barto show this on a random walk, and the experiment below reproduces the same setup.
The 19-State Random Walk
The environment is a row of 19 states, numbered 1 to 19, with a terminal state at each end. Every episode starts in the middle state (10). At each step the agent moves left or right with equal probability. Reaching the left end gives a reward of −1, reaching the right end gives +1, and every other step gives 0. With no discounting (γ = 1), the true value of state k is (k − 10) / 10, from −0.9 to 0.9.
Because we know the true values, we can measure the error of each method exactly: the root mean square (RMS) error between the estimated and true values across all 19 states.
n-Step TD Prediction in Python
The code runs each method for 10 episodes, records the RMS error after each episode, and averages over 100 independent runs. It needs only NumPy.
import numpy as np
N_STATES = 19 # non-terminal states 1..19
START = 10 # start in the middle
TRUE_V = np.arange(-18, 20, 2) / 20.0 # -0.9, -0.8, ..., 0.9
def episode(rng):
"""Random walk: returns visited states and rewards (rewards[t] = R_{t+1})."""
states, rewards = [START], []
s = START
while True:
s += rng.choice((-1, 1))
if s == 0:
rewards.append(-1.0); states.append(s); break
if s == N_STATES + 1:
rewards.append(1.0); states.append(s); break
rewards.append(0.0); states.append(s)
return states, rewards
def n_step_td(V, states, rewards, n, alpha, gamma=1.0):
"""n-step TD prediction for one episode (Sutton and Barto, section 7.1)."""
T = len(rewards)
for tau in range(T): # tau = time whose estimate is updated
end = min(tau + n, T)
G = sum(gamma ** (i - tau - 1) * rewards[i - 1] for i in range(tau + 1, end + 1))
if tau + n < T:
G += gamma ** n * V[states[tau + n]]
V[states[tau]] += alpha * (G - V[states[tau]])
def rms_error(n, alpha, runs=100, episodes=10, seed=0):
rng = np.random.default_rng(seed)
total = 0.0
for _ in range(runs):
V = np.zeros(N_STATES + 2) # terminal states stay at 0
for _ in range(episodes):
states, rewards = episode(rng)
n_step_td(V, states, rewards, n, alpha)
total += np.sqrt(np.mean((V[1:-1] - TRUE_V) ** 2))
return total / (runs * episodes)
if __name__ == "__main__":
alphas = [0.1, 0.2, 0.4, 0.6, 0.8]
print("RMS error over 19 states, first 10 episodes, 100 runs")
print("n " + "".join(f"a={a:<6}" for a in alphas))
for n in [1, 2, 4, 8, 16, 32]:
row = "".join(f"{rms_error(n, a):<8.3f}" for a in alphas)
print(f"{n:<6}{row}") A note on the loop in n_step_td: the book’s pseudocode updates V(S_τ) while the episode is still running, at time τ + n − 1. Our version collects the episode first and then makes the same updates in the same order. Each update sees exactly the values it would have seen online, so the results are identical. The online form matters when episodes are very long or never end.
Results: Which n Works Best?
This is the real output (Python 3.13, NumPy 2.5; the run took about 28 seconds):
RMS error over 19 states, first 10 episodes, 100 runs
n a=0.1 a=0.2 a=0.4 a=0.6 a=0.8
1 0.506 0.471 0.412 0.367 0.345
2 0.470 0.406 0.311 0.276 0.316
4 0.412 0.322 0.263 0.307 0.388
8 0.346 0.277 0.316 0.393 0.474
16 0.319 0.324 0.420 0.502 0.573
32 0.363 0.424 0.538 0.611 0.666 Three patterns stand out:
- Intermediate n wins. The lowest error, 0.263, comes from
n = 4withα = 0.4. The best one-step TD result is 0.345, and the best result forn = 32(which behaves almost like Monte Carlo on most episodes) is 0.363. - Larger n wants a smaller step size. One-step TD does best at the largest
αwe tried,n = 4at 0.4,n = 8at 0.2 andn = 16at 0.1. Longer returns are noisier, so each update has to move the estimate less. - A bad step size can erase the gain.
n = 16withα = 0.8(0.573) is worse than one-step TD with any step size we tried. Tunenandαtogether, never one at a time.
These numbers follow the same shape as the book’s Figure 7.2, which plots the same experiment. Exact values will vary a little with the random seed.
Beyond Prediction
The same n-step return carries over to control. n-step Sarsa replaces V(S_{t+n}) with Q(S_{t+n}, A_{t+n}) and learns action values while acting. For off-policy learning, chapter 7 covers importance sampling and the tree backup algorithm, which avoids importance sampling entirely. Chapter 12 then shows how eligibility traces average over all values of n at once (TD(λ)), which removes the need to pick a single n.
If you came here from the LLM side, note that “agent” in reinforcement learning means a learner acting in an environment for reward. That is related to, but not the same as, the tool-calling agents in our guide to implementing AI agents in Python.
Back to the Two Choices
The choice from the opening was a false one. One-step TD and Monte Carlo are two settings of one dial, and on the random walk the middle of that dial did better than either end: four real rewards plus one bootstrapped estimate cut the error by about a quarter compared with the best one-step TD result. In practice, try a few values of n such as 1, 4 and 16, tune the step size for each, and keep the pair with the lowest error on your problem.
Frequently Asked Questions
Is n-Step TD the Same as TD(λ)?
No, but they are close relatives. n-step TD uses one fixed n. TD(λ) averages the n-step returns for all n, weighting them by λ^(n−1), and can be computed online with eligibility traces. Sutton and Barto cover TD(λ) in chapter 12.
What Happens When n Is Larger Than the Episode?
The return simply runs to the end of the episode with no bootstrap term. In that case the n-step update is the same as a Monte Carlo update with a constant step size. That is why large values of n behave like Monte Carlo in the results table.
How Do I Choose n in Practice?
Treat it as a hyperparameter and tune it together with the step size. Values such as 3 to 5 are common starting points in deep reinforcement learning, but the right value depends on reward delay and noise in your environment. Measure on your own task.
Where Can I Read Chapter 7 for Free?
The authors host the full second edition on the book’s official page at incompleteideas.net, linked above. Chapter 7 is “n-step Bootstrapping”, and section 7.1 covers the prediction method and random walk example used in this guide.




