Monte Carlo Prediction

Imagine teaching an agent to play blackjack purely by watching thousands of hands play out. No rulebook of transition probabilities exists in the agent's head. Only the raw experience of cards dealt, decisions made, and chips won or lost at the end. Monte Carlo prediction turns this raw experience into estimates of how good each situation actually is. It does this simply by averaging what happened afterward. This matters because most real-world sequential decision problems do not come with a known Markov Decision Process model. A robot does not know its exact friction coefficients. A trading agent does not know tomorrow's price distribution. Whenever an agent can only sample trajectories — by acting or by observing — rather than query a transition model, Monte Carlo methods provide a direct, model-free route to evaluating a policy. This is the foundational move. It separates dynamic-programming style reasoning, which assumes perfect knowledge of the environment, from learning purely from interaction. The big picture is simple and powerful. The value of a state under a policy is defined as an expected return. An expectation can be estimated by an average of samples. Monte Carlo prediction is exactly this idea applied to full episodes. It requires no model of the environment's dynamics. It requires no bootstrapping from other estimates. Its correctness rests entirely on the law of large numbers. This article builds Monte Carlo prediction from first principles. It covers the precise problem definition, the first-visit and every-visit algorithms with full pseudocode. It also includes a rigorous complexity and convergence discussion, a hand-traced numerical example, and common implementation traps. Finally, it traces the historical lineage connecting this method to the broader development of reinforcement learning. It sets up the natural next steps — Monte Carlo control and temporal-difference learning — without requiring them yet.

Key takeaways
  • Monte Carlo (MC) prediction estimates vπ(s)v_\pi(s) by averaging observed returns following visits to ss across sampled episodes.
  • It requires only episodic experience — no model of transition probabilities or rewards is needed.
  • Two variants exist: first-visit MC (average return after the first visit per episode) and every-visit MC (average return after every visit).
  • Estimates are unbiased (first-visit) or asymptotically unbiased (every-visit), and both converge almost surely by the law of large numbers.
  • MC prediction only updates values at episode end, unlike bootstrapping methods, so it needs complete episodes and has higher variance but no bias from initial estimates.
  • It is the natural precursor to Monte Carlo control and stands in direct contrast to temporal-difference methods like TD(0).
The core insight

Estimate a state's value by literally averaging the total return that followed every time the agent visited that state, across many sampled episodes.

The idea

Recall that the value of state ss under policy π\pi is defined as the expected return starting from ss and following π\pi thereafter:

vπ(s)=Eπ[Gt∣St=s]v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s]

where Gt=Rt+1+γRt+2+γ2Rt+3+⋯G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots is the Return — the discounted sum of future rewards from time tt to the end of the episode. Monte Carlo prediction estimates this expectation directly from data: run the policy π\pi to generate complete episodes, record the return that follows each visit to ss, and average those returns. As more episodes are collected, this sample average converges to the true expectation by the law of large numbers — no model of the environment's transition or reward dynamics is ever consulted. This is fundamentally different from dynamic programming approaches to the same problem, which compute vπv_\pi by solving the Bellman Equation using a known model p(s′,r∣s,a)p(s', r \mid s, a). Monte Carlo prediction instead treats the environment as a black box that can only be sampled, one episode at a time. It is also different from bootstrapping methods, which we have not yet introduced, in that Monte Carlo never uses one value estimate to update another — it only uses actual, realized returns. This makes each Monte Carlo estimate for a given state independent of the estimates of all other states, a property that will matter later when comparing bias and variance against TD methods. Two bookkeeping conventions exist because a single episode may visit the same state multiple times (in problems with cycles). First-visit MC counts, for each episode, only the return following the first time ss is entered, and averages these across episodes. Every-visit MC counts the return following every occurrence of ss within an episode. Both converge to vπ(s)v_\pi(s), but they have different statistical properties: first-visit returns from different episodes are independent and identically distributed samples of Gt∣St=sG_t \mid S_t=s, giving a classical unbiased estimator; every-visit returns within the same episode are correlated, so the every-visit estimator is only asymptotically unbiased, though in practice it usually has lower variance because it uses more data per episode.

How it works

The mechanism has three moving parts: a way to generate episodes under the policy being evaluated, a per-state return accumulator, and an averaging step. Concretely: 1. Generate an episode. Starting from some initial state, follow policy π\pi (which may be stochastic) until a terminal state is reached, recording the sequence S0,A0,R1,S1,A1,R2,…,ST−1,AT−1,RT,STS_0, A_0, R_1, S_1, A_1, R_2, \ldots, S_{T-1}, A_{T-1}, R_T, S_T. 2. Compute returns backward. Walk the episode from the end to the start, maintaining a running return G←Rt+1+γGG \leftarrow R_{t+1} + \gamma G. This computes all GtG_t values in a single backward pass in O(T)O(T) time instead of recomputing each sum from scratch. 3. Update the average for each visited state, either only on first visit or on every visit, using an incremental mean update so no growing list of past returns needs to be stored. Here is the full first-visit Monte Carlo prediction algorithm, followed by the small modification needed for every-visit. ``` Algorithm: First-Visit Monte Carlo Prediction Input: policy π to be evaluated, discount factor γ ∈ (0,1] Initialize: V(s) ← arbitrary, for all states s # value estimate N(s) ← 0, for all states s # visit counter Returns_sum(s) ← 0, for all states s # running sum of returns Repeat for each episode: Generate an episode following π: S0, A0, R1, S1, A1, R2, ..., S_{T-1}, A_{T-1}, R_T (terminal at time T) G ← 0 visited_in_this_episode ← empty set for t = T-1 downto 0: G ← γ G + R_{t+1} if S_t is NOT in visited_in_this_episode: add S_t to visited_in_this_episode N(S_t) ← N(S_t) + 1 Returns_sum(S_t) ← Returns_sum(S_t) + G V(S_t) ← Returns_sum(S_t) / N(S_t) Output: V ≈ v_π ``` ``` Algorithm: Every-Visit Monte Carlo Prediction (identical, but remove the "if S_t is NOT in visited_in_this_episode" guard — update N(S_t) and Returns_sum(S_t) on every occurrence of S_t in the episode) ``` An equivalent and more memory-friendly formulation avoids storing `Returns_sum` explicitly and instead uses the incremental sample-mean update: ``` N(S_t) ← N(S_t) + 1 V(S_t) ← V(S_t) + (1 / N(S_t)) (G - V(S_t)) ``` This is mathematically identical to recomputing the mean of all returns seen so far, but it only requires O(1)O(1) extra memory per state rather than storing every past return. It also generalizes naturally to a constant step-size variant, `V(S_t) ← V(S_t) + α (G - V(S_t))`, which trades the guarantee of exact averaging for the ability to track a slowly changing (non-stationary) policy or environment — a preview of ideas used heavily in Monte Carlo control and TD learning.

Figure
Monte Carlo prediction: one episode's backward return pass over a state trajectory
S₀ S₁=s S₂ S₃=s S₄=T R₁ R₂ R₃ R₄ backward pass: G ← γG + R, computed from S₄ down to S₀ first visit to s 2nd visit to s (every-visit only) First-visit MC: only the S₁ occurrence of s updates V(s) this episode

Complexity & correctness

Time complexity. Generating one episode of length TT under policy π\pi costs O(T)O(T) environment steps (this cost is intrinsic to sampling, not to the algorithm). Computing all returns via the backward pass is O(T)O(T), since each step does O(1)O(1) work (`G ← γG + R`) and there are TT steps. Updating the value table with the incremental-mean formula is O(1)O(1) per visited state, so first-visit MC costs O(T)O(T) total per episode (each state contributes at most once), and every-visit MC also costs O(T)O(T) total per episode (each of the TT time steps contributes exactly one update). Over NN episodes, total time is O(NTˉ)O(N \bar{T}) where Tˉ\bar{T} is average episode length — linear in the total amount of experience generated, which is optimal since every reward must be read at least once.

Space complexity. The algorithm needs one counter N(s)N(s) and one value V(s)V(s) per state, so space is O(∣S∣)O(|\mathcal{S}|), independent of the number of episodes — this is the payoff of the incremental-mean update over naively storing every observed return. If the state space is continuous or function-approximated, this becomes O(d)O(d) where dd is the number of parameters, but that extension belongs to later material.

Correctness argument. Fix a state ss that has nonzero probability of being visited under π\pi. Under first-visit MC, each episode in which ss occurs contributes exactly one return sample G(i)G^{(i)}, and these samples across episodes i=1,2,…i = 1, 2, \ldots are independent and identically distributed draws from the conditional distribution of Gt∣St=sG_t \mid S_t = s (independence follows because episodes are generated independently of one another, assuming the policy and environment are fixed and memoryless given the state). By definition,

E[G(i)]=vπ(s).\mathbb{E}[G^{(i)}] = v_\pi(s).

The sample mean after nn visits is

Vn(s)=1n∑i=1nG(i).V_n(s) = \frac{1}{n}\sum_{i=1}^n G^{(i)}.

By the strong law of large numbers, Vn(s)→vπ(s)V_n(s) \to v_\pi(s) almost surely as n→∞n \to \infty, provided the returns have finite variance (guaranteed when rewards are bounded and γ<1\gamma < 1, or when γ=1\gamma = 1 but the episode is guaranteed to terminate in finite expected time). Moreover Vn(s)V_n(s) is an unbiased estimator of vπ(s)v_\pi(s) for every finite nn, since E[Vn(s)]=vπ(s)\mathbb{E}[V_n(s)] = v_\pi(s) exactly — this is the classical unbiasedness of a sample mean of i.i.d. draws. For every-visit MC the argument is subtler: within a single episode, multiple returns following repeated visits to ss are not independent (they share tail rewards and later states). The estimator is therefore biased for small nn, but it remains consistent: as the number of episodes grows, the bias vanishes and Vn(s)→vπ(s)V_n(s) \to v_\pi(s) almost surely, a result that follows from a law of large numbers for suitably mixing/martingale sequences rather than the plain i.i.d. case. In practice both estimators are used, and the every-visit version is often preferred with function approximation because it makes more efficient use of each episode's data.

Key tradeoff versus dynamic programming and TD. Monte Carlo prediction needs no model, unlike DP. It has zero bias (first-visit) because it never bootstraps off a possibly-wrong current estimate, unlike TD(0), which we build toward next. But it pays for this with two costs: it needs the episode to actually terminate before any update can happen, so it cannot be used in continuing (non-episodic) tasks without modification, and its variance can be large because a single return accumulates noise from an entire trajectory of random rewards and transitions, whereas TD updates use only one step of real reward plus a bootstrapped estimate.

Worked example

Consider a tiny episodic gridworld-like problem simplified to a single Markov chain with states {A,B,C,terminal}\{A, B, C, \text{terminal}\}, a fixed policy π\pi (deterministic transitions given here for concreteness), discount factor γ=1\gamma = 1, and the following three sampled episodes (state sequence with rewards received on each transition):

EpisodeTrajectory (state → reward → state ...)
1A → +2 → B → +1 → A → +0 → C → +3 → terminal
2B → −1 → C → +4 → terminal
3A → +2 → C → +1 → B → +0 → C → +2 → terminal

We compute first-visit MC estimates for V(A)V(A), V(B)V(B), V(C)V(C).

Episode 1: sequence A,B,A,C,termA,B,A,C,\text{term} with rewards 2,1,0,32,1,0,3. Backward pass (γ=1\gamma=1, so G←G+RG \leftarrow G + R):

t (backward)stateRG after update
3C33
2A (2nd visit)03
1B14
0A (1st visit)26

First-visit rule: A's first visit is at t=0t=0 with G=6G=6; the later revisit of A at t=2t=2 (giving G=3G=3) is ignored. B's only visit gives G=4G=4. C's only visit gives G=3G=3. Contributions from episode 1: A→6A \to 6, B→4B \to 4, C→3C \to 3.

Episode 2: sequence B,C,termB, C, \text{term} with rewards −1,4-1, 4.

t (backward)stateRG
1C44
0B−13

Contributions: B→3B \to 3, C→4C \to 4.

Episode 3: sequence A,C,B,C,termA, C, B, C, \text{term} with rewards 2,1,0,22,1,0,2.

t (backward)stateRG
3C (2nd visit)22
2B02
1C (1st visit)13
0A25

First-visit C is at t=1t=1 with G=3G=3 (the later occurrence at t=3t=3, G=2G=2, is discarded). B's only visit gives G=2G=2. A's only visit gives G=5G=5. Contributions: A→5A \to 5, B→2B \to 2, C→3C \to 3.

Averaging across episodes (first-visit):

StateReturns collectedN(s)N(s)V(s)V(s)
A6, 525.5
B4, 3, 233.0
C3, 4, 333.33

These are the first-visit Monte Carlo estimates after just three episodes. Note how episode 1 contributed only one A-sample (6, from the first visit) even though A was visited twice — this is exactly the first-visit rule in action. An every-visit version would additionally fold in the second A-return (3) from episode 1, giving N(A)=3N(A)=3 and V(A)=(6+3+5)/3=4.67V(A) = (6+3+5)/3 = 4.67 — noticeably different at this small sample size, illustrating why the two estimators can disagree substantially before convergence, even though both converge to the same vπ(A)v_\pi(A) in the limit.

Common pitfalls & traps

PitfallWhy it happensFix
Computing returns forward instead of backwardRecomputing ∑γkR\sum \gamma^k R from scratch for every tt costs O(T2)O(T^2) per episodeAlways accumulate G←γG+Rt+1G \leftarrow \gamma G + R_{t+1} walking from T−1T-1 down to 00
Forgetting the first-visit guard, thinking it's "the same algorithm"First-visit and every-visit give different (though both convergent) estimates, especially early onExplicitly track a per-episode visited-set and only decide once which rule you're using
Applying MC prediction to a non-terminating (continuing) taskNo episode ever ends, so GtG_t is never fully realized and no update ever firesUse TD methods for continuing tasks, or truncate/wrap the task into episodes explicitly
Using γ=1\gamma = 1 with returns that don't provably terminateIf the policy can loop forever with positive probability, GtG_t has infinite variance or is undefinedEnsure the policy-environment pair guarantees termination, or discount with γ<1\gamma < 1
Confusing sample averaging with a fixed learning rateUsing constant α\alpha makes MC track non-stationary targets but loses the exact-mean guaranteeUse 1/N(s)1/N(s) step size for the classical estimator; use constant α\alpha only intentionally
Updating V(s)V(s) mid-episode using an in-progress, incomplete returnBreaks the "complete episode" requirement that makes the sample an honest realization of GtG_tOnly update after the terminal state is reached and the full backward pass is done

Pioneers & history

Monte Carlo estimation as a general numerical technique predates reinforcement learning by decades, but its formal integration into value-function estimation for sequential decision problems was crystallized in the reinforcement learning literature of the late 20th century, building on decades of work in stochastic approximation, statistics, and simulation.

Origins · 1 minStanislaw Ulam and how this was discovered
SU
Stanislaw Ulam
1909–1984 · Los Alamos National Laboratory, 1940s

Ulam, working alongside John von Neumann, conceived the Monte Carlo method while considering the probability of winning at solitaire and later applying the same sampling logic to neutron diffusion problems for nuclear weapons design. The core insight — that a hard-to-compute expectation can be approximated by simulating many random trials and averaging the outcomes — is the direct mathematical ancestor of every Monte Carlo method used in reinforcement learning today, including Monte Carlo prediction.

History
1940
s: Ulam and von Neumann formalize the Monte Carlo method for simulating physical systems at Los Alamos.
1950
s–1980s: Stochastic approximation theory (Robbins–Monro) establishes the mathematical basis for incremental sample-mean and learning-rate-based estimators.
1988
Sutton introduces temporal-difference learning, explicitly contrasting it with Monte Carlo methods for value prediction.
1998
Sutton and Barto's Reinforcement Learning: An Introduction systematizes first-visit and every-visit Monte Carlo prediction as a unified topic within model-free prediction.
2000
s–2010s: Monte Carlo estimation ideas merge with tree search (as in Monte Carlo Tree Search) and later underpin large-scale policy evaluation pipelines in deep reinforcement learning systems.

Where this matters

Monte Carlo prediction is the conceptual seed for Monte Carlo control, where the same return-averaging idea is applied to action-value functions qπ(s,a)q_\pi(s,a) and combined with policy improvement to learn optimal behavior directly from episodes — used historically in classic game-playing agents and still taught as the cleanest bridge from prediction to control. It is also the direct comparison point for temporal-difference learning: TD(0), which replaces the full-episode return with a one-step bootstrapped target, trading some bias for dramatically reduced variance and the ability to learn online without waiting for episode termination; understanding Monte Carlo prediction thoroughly is what makes the tradeoffs of TD learning legible. In applied systems, Monte Carlo estimation of value functions underlies Monte Carlo Tree Search (MCTS), the search technique behind AlphaGo and its successors, where rollouts to the end of a simulated game are averaged to estimate the value of a board position exactly as in Monte Carlo prediction. Return-averaging ideas also appear in off-policy evaluation for recommendation systems and clinical trial analysis, where historical logged episodes (user sessions, treatment courses) are used to estimate the value of a candidate policy before it is ever deployed, precisely because no accurate simulator of user behavior or patient physiology exists. Any setting where an agent or analyst has only logged trajectories, and not a model, is a natural home for Monte Carlo prediction or its variance-reduced cousins.

Ask the tutor: How does the bias–variance tradeoff between Monte Carlo prediction and TD(0) actually play out in a concrete multi-state example?

Does Monte Carlo prediction require knowing the environment's transition probabilities?

No — that is precisely its defining advantage. Monte Carlo prediction only requires the ability to sample episodes by following the policy, either through direct interaction with an environment or through a simulator whose internal dynamics need not be known analytically. Dynamic programming methods, by contrast, need the full transition and reward model p(s′,r∣s,a)p(s', r \mid s, a) to solve the Bellman equations exactly. This makes Monte Carlo prediction applicable to any problem where you can generate experience — games, robotics, logged human behavior — even when writing down exact transition probabilities would be impossible or intractable.

Why does Monte Carlo prediction need complete episodes rather than working step by step?

The return GtG_t is defined as the sum of all discounted future rewards from time tt until the episode ends. Until the terminal state is actually reached, this sum is incomplete and cannot serve as a valid sample of the true expected return. Waiting for termination guarantees that every update uses a genuine, unbiased realization of GtG_t, at the cost of not being able to update value estimates online, mid-episode. This is the central structural difference from temporal-difference methods, which build targets from a single reward plus a bootstrapped estimate and can update after every single step.

Is the Monte Carlo value estimate biased?

The first-visit estimator is exactly unbiased for every finite number of episodes, because each episode contributes one independent sample from the true conditional distribution of the return given that state. The every-visit estimator is biased for small sample sizes because returns from repeated visits within the same episode are statistically correlated, sharing overlapping future rewards, but this bias vanishes asymptotically and the estimator remains consistent. In practice, with enough episodes, both estimators converge to the same true value vπ(s)v_\pi(s).

How does Monte Carlo prediction handle states that are never visited under the policy?

It simply never updates them — their value estimate stays at its arbitrary initialization forever, since no return is ever attributed to a state that never occurs on a sampled trajectory. This is a genuine limitation: Monte Carlo prediction can only learn about states (and, in the control setting, actions) that have nonzero probability of occurring under the behavior generating the episodes. This is exactly why exploration — ensuring enough visitation coverage — becomes a central concern once Monte Carlo ideas are extended from prediction to control.

What is the variance tradeoff of Monte Carlo prediction compared to bootstrapping methods?

Monte Carlo returns accumulate randomness from every reward and every transition across an entire episode, so a single return sample can have high variance, especially in long or highly stochastic episodes. Bootstrapping methods like TD(0) instead build a target from only one real reward plus a current value estimate, which has much lower variance per update but introduces bias whenever that current estimate is inaccurate. This bias-variance tradeoff is the central theoretical comparison point between Monte Carlo prediction and temporal-difference learning, and neither method dominates the other in every setting.

Can Monte Carlo prediction be used with a constant learning rate instead of an exact sample average?

Yes, and this is a common practical variant: instead of `V(s) ← V(s) + (1/N(s))(G − V(s))`, one uses `V(s) ← V(s) + α(G − V(s))` for a fixed step size α. The exact-average version is optimal for a fixed, unchanging policy in a stationary environment, since it weights every past return equally. The constant-α version instead gives more weight to recent returns, letting the value estimate track a policy or environment that changes over time — a property that becomes essential once Monte Carlo methods are combined with policy improvement in Monte Carlo control.

How does Monte Carlo prediction relate to Monte Carlo Tree Search?

Monte Carlo Tree Search uses the same core statistical idea — estimate a value by averaging outcomes of simulated rollouts — but applies it inside a search tree during planning rather than to a fixed dataset of past episodes. Each simulated rollout in MCTS plays out a full trajectory (often to a terminal state or a fixed depth) and the resulting return is averaged into the value estimate of every tree node visited along the way, exactly mirroring first-visit or every-visit Monte Carlo prediction. This shared foundation is why understanding Monte Carlo prediction directly clarifies how modern search-based game-playing agents estimate position values.

Where this leads