State-Value and Action-Value Functions
Imagine a robot navigating a warehouse, choosing among many possible paths to a loading dock. Some paths look short but pass through congested aisles. Others look long but stay clear. To choose well, the robot needs a number for each situation. It needs a forecast of how much total reward it can expect from here onward. This is exactly the problem that state-value and action-value functions solve. They compress an uncertain, multi-step future into a single predictive quantity. That quantity attaches to a state, or to a state-action pair. These functions are the computational backbone of almost every Reinforcement Learning algorithm. Whether an agent is playing chess, trading stocks, or controlling a robot arm, it needs a way to compare situations. It must judge "how good is this situation" against "how good is that one." Without value functions, an agent would have to simulate every possible future exhaustively. It would need to do this before making a single decision. This strategy is computationally hopeless in any environment with more than a handful of states. Value functions let the agent cache long-range consequences into short, reusable numbers. The big picture is this: given a fixed policy — a rule for choosing actions — we can ask two closely related questions. First, "how good is it to be in state while following this policy?" That is the state-value function, written . Second, "how good is it to take a specific action in state , and only then follow the policy?" That is the action-value function, written . These two functions are not independent inventions. They are algebraically linked, and that link is a seed. From it, the Bellman Equations and eventually the Bellman Optimality Equation will grow. This article builds both functions from first principles. It starts from the definition of expected return. It shows precisely how and relate to each other. It gives working pseudocode for estimating them by simulation. It also works a full numerical trace on a small grid. This way, every number can be checked by hand.
- is the expected total discounted reward from state , given that the agent follows policy forever after.
- is the expected total discounted reward from taking action in state , then following afterward.
- is an action-probability-weighted average of over all actions the policy might take in .
- can be written in terms of evaluated at the next state, averaged over the environment's transition dynamics.
- Both functions can be estimated empirically by Monte Carlo averaging of sampled returns, without knowing the environment's model.
- These definitions are exactly the objects that the Bellman equations turn into solvable recursive equations.
State-value and action-value functions are expectations of future discounted reward, and they determine each other exactly through the policy's action probabilities and the environment's transition probabilities.
The idea
A <span class="wiki-link-missing">Markov decision process</span> (MDP) consists of states , actions , a transition function giving , and a discount factor . A policy is a mapping from states to probabilities over actions: is the probability of choosing action while in state . Given a trajectory that starts at time , the return is the discounted sum of future rewards,
The return is a random variable: it depends on the random sequence of states, actions, and rewards that unfold after time , which in turn depend on both the policy's randomness and the environment's randomness. The state-value function for policy is the expected return starting from state and following thereafter:
The action-value function (also called the Q-function) is the expected return starting from state , taking action immediately, and then following :
The subtlety that separates the two definitions is the fate of the first action. In , the first action is chosen by the policy according to . In , the first action is pinned to regardless of what the policy would normally do, and only the actions afterward obey . This is why is strictly more informative: it tells you the consequence of every possible first move, not just the moves the policy happens to favor. Because averages over the policy's own choice of first action, and is the value conditional on that first action, the two are related by a simple expectation:
This identity is not an approximation or a modeling choice — it follows directly from the law of total expectation applied to the random variable , conditioned on . Symmetrically, can be expressed using evaluated one step into the future, by conditioning on the immediate reward and next state produced by the environment's dynamics :
Together these two identities form a tight loop: is built from by averaging over the policy, and is built from by averaging over the environment's transition dynamics. Substituting one into the other produces the recursive self-referential equation known as the Bellman equation for , which is the natural next object of study, along with its action-value counterpart and, eventually, the optimality equations that characterize the best possible policy.
How it works
Since and are defined as expectations over an infinite (or long) random trajectory, computing them exactly requires either (a) an explicit model of the environment's dynamics, solved analytically or by dynamic programming, or (b) empirical estimation by sampling many trajectories and averaging observed returns — the Monte Carlo approach. Because this article's prerequisite level assumes only the definitions of policies and value functions (not yet the Bellman machinery), the cleanest way to compute — rather than merely define — these quantities without a model is direct Monte Carlo estimation. This also builds the right intuition: and are just averages of empirical returns, and dynamic-programming methods later on will simply find faster ways to compute the same averages using the recursive identities above.
Step-by-step mechanism for Monte Carlo estimation of and : 1. Fix the policy to be evaluated. It does not change during this process — we are only measuring it, not improving it. 2. Generate an episode: starting from some state, repeatedly sample an action from , let the environment produce and , and continue until a terminal state (or a fixed horizon). 3. For each time step visited in the episode, compute the realized return by summing forward from that point to the end of the episode. 4. Attribute that sampled return as one observation of , and also as one observation of (since the true action taken at was ). 5. Maintain running averages, per state (for ) and per state-action pair (for ), across many episodes. 6. As the number of episodes grows, the law of large numbers guarantees these running averages converge to the true and . ``` function MONTE_CARLO_EVALUATE(policy π, environment env, num_episodes N, discount γ):
# Running sums and counts for state-value and action-value estimates V_sum = dictionary(default 0.0) # state -> cumulative return V_count = dictionary(default 0) # state -> number of visits Q_sum = dictionary(default 0.0) # (state, action) -> cumulative return Q_count = dictionary(default 0) # (state, action) -> number of visits for episode in 1..N: states, actions, rewards = [], [], [] s = env.reset() while not env.is_terminal(s): a = sample_action(π, s) # a ~ π(· | s) s_next, r = env.step(s, a) states.append(s) actions.append(a) rewards.append(r) s = s_next T = length(rewards) G = 0.0
# Walk backward through the episode to build returns cheaply:
# G_t = R_{t+1} + γ G_{t+1}, computed from the end of the episode. for t in (T-1) down to 0: G = rewards[t] + γ * G # this G is now G_t s_t, a_t = states[t], actions[t] V_sum[s_t] += G V_count[s_t] += 1 Q_sum[(s_t, a_t)] += G Q_count[(s_t, a_t)] += 1
# Final estimates: sample averages of observed returns v_hat = { s: V_sum[s] / V_count[s] for s in V_sum } q_hat = { (s,a): Q_sum[(s,a)] / Q_count[(s,a)] for (s,a) in Q_sum } return v_hat, q_hat ``` Two implementation notes matter for correctness. First, computing by walking backward through the episode (as shown) costs work per time step via the recursion , rather than work per time step from a naive forward sum — this is a standard trick, not a shortcut that changes the answer. Second, if a state is visited multiple times within one episode, one may choose first-visit Monte Carlo (only the first occurrence contributes) or every-visit Monte Carlo (every occurrence contributes); both converge to and under mild conditions, though their variance and bias properties in finite samples differ slightly. The diagram below shows how and interlock in a single decision step: the state-value at is a -weighted blend over actions of the action-values, and each action-value is a probability-weighted blend over the environment's stochastic outcomes of "reward plus discounted next-state value."
Complexity & correctness
Space complexity. Storing requires numbers, one per state. Storing requires numbers, one per state-action pair. This is the fundamental storage tradeoff: is a strictly larger table but carries strictly more decision-relevant information, since it separates out the consequence of each candidate action instead of blending them under the current policy.
Time complexity of Monte Carlo estimation. For one episode of length , generating the trajectory costs environment interactions. Computing all returns for via the backward recursion costs total (each is given ), not as a naive forward summation would cost. Updating running averages for and costs per visited state or state-action pair. So one episode costs overall, and episodes cost , where is the average episode length. This is efficient — linear in the total amount of simulated experience — but the statistical efficiency (how many episodes are needed for accurate estimates) is separate from this computational cost, and is governed by the variance of returns, discussed below.
Correctness of the Monte Carlo estimator. The estimator's correctness rests on the definition of and as expectations, combined with the law of large numbers. Fix a state . Every episode that visits at some time contributes an independent (or, for every-visit, weakly dependent) sample of the random variable , whose expectation is by definition. As the number of such samples ,
by the strong law of large numbers, provided the returns have finite variance (guaranteed when rewards are bounded and , or when episodes terminate with probability 1 under ). The identical argument, replacing the conditioning event with the joint event , establishes convergence of the running average to .
Correctness of the identities. These are not estimated quantities but exact algebraic consequences of the definitions, provable by the law of total expectation. For the first identity:
where the middle step is exactly the tower property of conditional expectation, conditioning first on and then averaging over its distribution . For the second identity, split the return as , and condition on :
and the inner expectation is exactly by definition, using the Markov property to note that the future beyond depends only on , not on the earlier history. This step is the one place the Markov assumption is doing real work — without it, could differ depending on how the process arrived at .
Honest tradeoffs. Monte Carlo estimation is unbiased and model-free, but it has two costs. First, it requires episodes to terminate (or a very long finite horizon), so it converges slowly in environments with long or highly variable episode lengths — the variance of compounds over every step, since each reward is itself random. Second, it wastes information: an episode that visits a state only once contributes only one sample, ignoring the rich structure the Bellman identities exploit — namely that for a nearby state can be reused to estimate without waiting for whole episodes to finish. This inefficiency is precisely the gap that dynamic-programming and bootstrapping methods, built directly on the Bellman equations, are designed to close.
Worked example
Consider a tiny two-state MDP: states , with terminal (reward-then-done). From , two actions are available: stay (loop back to ) and go (move to terminal ). Rewards: staying yields reward and looping back to ; going yields reward and terminates at . Discount factor . The policy chooses stay with probability and go with probability in state .
Exact computation using the identities (ground truth). First compute . Taking "go" yields reward and transitions to terminal state , where since no further reward is possible:
Next compute . Taking "stay" yields reward and transitions back to , so it depends on itself:
Now use the other identity to write in terms of both -values:
This is a single linear equation in :
Substituting back gives , and we already have . Sanity check with the identity:
| Quantity | Value |
|---|---|
Monte Carlo estimate, for comparison. Simulate 4 short episodes starting at under (stay 0.3 / go 0.7), truncated once terminal is reached:
| Episode | Action sequence | Rewards | Return from |
|---|---|---|---|
| 1 | go | 5 | |
| 2 | stay, go | 2, 5 | |
| 3 | go | 5 | |
| 4 | stay, stay, go | 2, 2, 5 |
Averaging these four sampled returns for state : . This is close to the exact value , and with only 4 episodes some estimation error is expected — the gap would shrink toward zero as more episodes are averaged, exactly as the law of large numbers predicts. Note episode 1 and 3 also contribute directly to the running average for (both sampled a return of starting with action "go"), while episodes 2 and 4 contribute to .
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Confusing with | averages over the policy's action distribution, not the best action | Remember ; only for an optimal greedy policy does this equal the max |
| Forgetting the discount factor when computing returns | Off-by-one errors treating or as the weight on the first reward | Return is ; the first reward after time has weight |
| Assuming ignores the policy entirely | The first action is fixed at , but every subsequent action still follows | pins only the first action; it is not the value of always taking forever |
| Using forward summation for returns in Monte Carlo code | Naively re-summing from each to the episode end costs | Use the backward recursion , costing total |
| Treating in the identity as depending on history | Forgetting the Markov property | The identity is valid only because future return depends solely on , not on how the process arrived there |
| Averaging returns across different policies | Value functions are policy-specific: in general | Always fix and label the policy being evaluated; re-evaluate from scratch after any policy change |
Pioneers & history
The state-value and action-value functions arose from the marriage of two independent lines of work: Richard Bellman's theory of dynamic programming for sequential decision problems under uncertainty, and the later formalization of trial-and-error learning as an approximation to that theory.
Origins · 1 minRichard E. Bellman and how this was discovered
Bellman formulated the principle of optimality and the recursive equations that bear his name while working on multistage decision processes at RAND in the 1950s. His formulation of value as an expected future return, defined recursively in terms of immediate reward plus discounted future value, is the direct mathematical ancestor of and as used in reinforcement learning today.
Where this matters
Every reinforcement learning algorithm that improves a policy needs some way to judge how good the current policy is, and and are exactly that judgment mechanism. Policy iteration and value iteration, the classical dynamic-programming algorithms for solving MDPs, alternate between evaluating (or ) and improving the policy based on those values — this is the direct ancestor of modern actor-critic methods. Q-learning and Deep Q-Networks (DQN), used in landmark results such as Atari-playing agents, learn an approximation of the optimal action-value function directly, using a neural network to represent over enormous state spaces such as raw pixel frames. Actor-critic methods, including A3C, PPO, and modern robotics controllers, maintain an explicit "critic" network estimating to reduce the variance of policy-gradient updates. In recommendation systems, -style estimates are used to score candidate recommendations against a user's simulated future engagement. In finance and operations research, dynamic-programming solutions to inventory and portfolio problems rest on value functions defined exactly as they are here, decades before "reinforcement learning" was a common term. Any system that must trade off immediate reward against long-term consequence — game-playing agents, autonomous vehicles, dialogue systems — ultimately relies on some computational stand-in for or .
:::quiz[Why does the identity rely on the Markov property?]
- It doesn't; the identity holds for any stochastic process
- Because it assumes depends only on , not on the path taken to reach it ✓
- Because Markov chains never terminate
- Because the discount factor must be state-dependent
Ask the tutor: How does substituting the -to- identity into the -to- identity produce the full Bellman equation for ?
Are and the same thing, just written differently?
No — they answer different questions and carry different amounts of information. tells you the expected return if you let the policy choose the very first action too, so it is a single blended number per state. tells you the expected return for each specific candidate first action, holding it fixed, and only lets the policy resume afterward. Because of this, contains strictly more information: knowing for every action lets you recover exactly via the weighted average , but knowing only does not let you recover the individual values, since the averaging step discards per-action detail. This is why algorithms that need to choose actions, like Q-learning, prefer to learn or its optimal counterpart directly.
Why do we need the policy at all — can't we just define "the" value of a state?
"The" value of a state is not well-defined without specifying a policy, because different policies produce different expected returns from the same state. A cautious policy that avoids risky shortcuts and a reckless policy that takes them will generally assign very different expected returns to the same starting state, even though the environment's dynamics are identical. This is why value functions are always written with a policy subscript, or , and why comparing two policies means comparing their entire value functions, state by state. Only when we ask for the best possible value, over all policies simultaneously, do we get a policy-independent object — the optimal value functions and — which is the subject the Bellman optimality equation addresses.
Does the Monte Carlo estimator described here require knowing the environment's transition probabilities ?
No, and this is one of its most attractive properties. Monte Carlo estimation only requires the ability to sample from the environment — to actually take actions and observe the resulting rewards and next states — not to know or compute with the underlying probability distribution in closed form. This makes it a model-free method, in contrast to dynamic-programming approaches that require an explicit, known model to compute the same expectations analytically. The tradeoff is statistical efficiency: Monte Carlo needs many sampled episodes to average away randomness, whereas a known model lets you compute exact expectations in one pass, using exactly the recursive identities derived in this article.
What happens to and if the discount factor equals 1?
With , the return becomes an undiscounted sum of all future rewards, which is only guaranteed to be finite if episodes terminate with probability 1 (an "episodic" task) or if rewards eventually become exactly zero. In infinite-horizon tasks without guaranteed termination, an undiscounted sum of nonzero rewards can diverge to infinity, making and undefined or infinite. This is precisely why most continuing (non-episodic) tasks use : it guarantees the geometric-series-like sum converges whenever rewards are bounded, since is a convergent geometric series for . Episodic tasks with guaranteed termination can safely use , since the sum is automatically finite.
Can be negative, or larger than for every action?
Both are possible and neither indicates an error. can be negative whenever the expected discounted future rewards following action are net negative, which is perfectly normal in environments with penalty or cost signals. It is also entirely possible for for every action that the policy assigns positive probability to — this simply means the policy is choosing suboptimally at , favoring some mixture of actions whose weighted average falls short of what any single action alone would achieve. This exact gap, between what the policy currently does and what greedily following the largest would achieve, is the quantity that policy improvement algorithms are built to close.
How does this relate to the Bellman equations mentioned as "leading to" this topic?
The two identities derived here — and — are the two halves of a puzzle. Substituting the second identity into the first produces a single equation expressing entirely in terms of evaluated at other states, one step into the future. That self-referential equation is exactly the Bellman equation for , and an analogous substitution in the other direction produces the Bellman equation for . Rather than being estimated only by simulation, as in this article's Monte Carlo pseudocode, these recursive equations can be solved directly — by linear algebra for small problems, or by dynamic-programming iteration for larger ones — which is the natural next step in the theory.
Why does the article emphasize that returns are random variables, not fixed numbers?
Because misunderstanding this point is one of the most common sources of confusion for newcomers to the field. A single played-out trajectory produces one concrete numerical return, but and are defined as expectations over the entire distribution of possible trajectories, not as the return of any one particular trajectory. This distinction matters practically: in a stochastic environment, or with a stochastic policy, two agents starting in the exact same state and following the exact same policy can experience wildly different realized returns, yet both are legitimate samples of the same underlying random variable whose mean defines . Monte Carlo estimation works precisely because averaging many such samples converges to that mean, per the law of large numbers.