The dynamic programming chapters solved Bellman equations by storing one number per state, or per grid state. That works for the reservoir, the antibiotic regimen and a river of eight reaches, and it fails soon after. This part of the book replaces the table by a function with a fixed number of parameters, and it builds up to the algorithms used in practice: fitted Q-iteration with trees or neural networks, its online form DQN, and its continuous-action form NFQCA. This chapter starts with why the replacement is needed and what it must provide. It then asks the first question that the replacement raises. A function with finitely many parameters cannot satisfy the Bellman equation at every state, so which equations should determine its parameters? Numerical analysis answers this question for operator equations in general with the method of weighted residuals, a template of five steps. We present the template directly on the Bellman equation. One problem, a fishery near a tipping point, motivates it and then follows it through every step, in boxes that the method does not depend on.
Limits of Tabular Dynamic Programming¶
The tables of the previous chapters cannot simply be made larger, for three reasons, each already visible in an example we have solved.
The first is that the number of states grows exponentially with the number of state variables. The tamarisk river of Example: Controlling an Invasive Plant in a River Network has one site per reach and three conditions per site, so a river of reaches has states. Value iteration needed about 150 sweeps whatever the size of the river, but each sweep touches every state, and a dense transition table for a seven-reach river without the treatment budget would take 84 GB. The rivers that land managers face have hundreds of reaches. Continuous states hit the same wall through the grid. The reservoir of the finite-horizon chapter stored its value on 181 storage levels; five reservoirs in one valley, managed jointly on the same grid, would need grid states, each with its own one-step optimization at every stage. A grid with nodes per axis in dimensions has nodes. This is the curse of dimensionality that Bellman named, and it belongs to the representation rather than to the problem: the value function of a large system often has structure, such as smoothness or a dependence on a few aggregate quantities, that a grid cannot exploit and a more flexible representation can.
The second is that successors fall between the stored states. Even in one dimension, the finite-horizon chapter had to decide which value to use for a successor that lands between two grid states. Its answer, a family of cardinal functions, turned the table into a function defined everywhere, and its analysis of how the reconstruction error propagates through the recursion was a first instance of what this part of the book studies in general.
The third is that learning from data visits only some states. In the chapters ahead the model is replaced by a simulator or by recorded transitions . A batch of transitions covers a vanishing fraction of a large state space, and each Bellman target needs a value at a successor that may never have been visited. A table has nothing to say there. A function fitted to the visited states does: it generalizes from them, and how well it generalizes decides how well the method works.
The replacement for the table is therefore a function with a parameter vector of fixed size. It must be cheap to evaluate at any state. It must be possible to fit it to a finite set of pairs (state, target value), which is a supervised learning problem. And it must extrapolate sensibly between and beyond those states. Grid interpolation is cheap and easy to fit, but it extrapolates only to the cells of its grid and its size grows as . A polynomial or another fixed basis is linear in , which gives closed-form fits and a complete theory, but its features must be chosen in advance. Tree ensembles and neural networks choose their features from the data. The fitted Q-iteration methods used in practice, from the tree-based FQI of Ernst et al. (2005) to NFQ Riedmiller (2005) and NFQCA Hafner & Riedmiller (2011), use these.
Replacing by raises two questions. The Bellman equation imposes one condition per state, infinitely many when the state space is continuous, while has finitely many components. Which finite set of conditions should determine ? This chapter answers it with the weighted-residual template of numerical analysis Chakraverty et al. (2019)Atkinson & Potra (1987), using linear bases, for which the conditions can be written out and solved in closed form. Once the conditions are fixed, which algorithm finds , and does the contraction that made value iteration converge survive the approximation? The next chapter answers the second question, and the chapter on fitted value methods extends the iteration to any regressor, neural networks included, and to sampled data.
A Motivating Example: Harvesting a Fishery Near a Tipping Point¶
This example shows what goes wrong when a value function on a continuum is stored in a few numbers, and how the choice of representation changes the decisions that the stored function produces. A regulator sets the annual quota for a fish stock. Before the season, a survey gives the stock , measured as a fraction of the carrying capacity of the habitat. The regulator chooses the escapement , the part of the stock left in the water to spawn. The escapement is the action, which is why we write it . The rest, , is caught and sold at a unit price. Over the following year the escaped stock grows to
where is a log-normal shock with mean one that stands for the environment: how many young fish survive varies a lot from year to year. This growth law, which Boettiger et al. (2015) use to study tipping points in fisheries, has an Allee effect. Below the threshold , the fish are too sparse to replace themselves, and the stock shrinks even when nobody fishes it (panel (a) of Figure 1). We take , , , a shock whose logarithm has standard deviation 0.15, and . These are teaching values, not the assessment of a real stock. The Bellman optimality equation is
Three things separate it from the finite MDPs of the earlier chapters. The state is a real number, so is a function on an interval and no table holds it. The action is a real number too, so the maximization runs over an interval. And the expectation is an integral over , which we compute with 21-point Gauss–Hermite quadrature. The successor stock almost never falls on a point where a value was stored, which is the difficulty that interpolation handled in the finite-horizon chapter.
This problem has one state variable, so we can still afford a reference solution: value iteration on 4,001 grid points, with linear interpolation between them and escapements restricted to the grid. Because the harvest value is linear in , the maximization over reduces to a running maximum along the grid, and one backup costs a single pass. Halving the number of grid points changes the solution by less than 0.001.
Figure 1:The fishery. (a) Expected stock next year against the escapement, with the band that holds 80% of the years. Below the tipping point the curve lies under the diagonal: the stock shrinks even without fishing. (b) The optimal value , computed on a fine grid. (c) The optimal escapement. The shading marks the three regions of the policy.
The optimal policy has three regions. Above , the regulator harvests down to the constant escapement , the policy that Reed (1979) proved optimal for this class of models. Reed’s optimality condition, , gives . The small gap comes from bad years, which leave the stock below , where a fish left to spawn is worth more than its price. Between and , the fishery is closed and the stock rebuilds. Below , the policy fishes the stock out: a stock this far below the tipping point will most likely decline anyway, and its catch today is worth more than its small chance of recovery. Clark (1973) showed that maximizing the value of the harvest can make extinction optimal in this way. Fisheries law adds conservation limits for that reason, and this model leaves them out. For the methods of this chapter, what matters is the shape of . It is linear on , has a kink at , rises more than tenfold across the tipping point, and is smooth elsewhere.
Now suppose we may store only numbers. Two choices are natural.
A Chebyshev polynomial, with . The basis is smooth and global: every coefficient changes the value at every stock.
Piecewise-linear interpolation on uniform nodes, with the hat functions of the finite-horizon chapter. Each coefficient is the value at one node, and it changes the value only between the two neighboring nodes.
Neither can satisfy the Bellman equation at every stock. Write for the whole function. The residual
measures by how much it fails at . Both terms depend on : the operator is applied to the function , and the result is evaluated at . Collocation picks points and asks the residual to vanish at them:
We use the Chebyshev nodes for the polynomial and the interpolation nodes for the hat functions, and we solve the nonlinear equations by function iteration. Each iteration computes the Bellman backup at the nodes with the current , then chooses the that reproduces those targets at the nodes. Figure 2 shows both approximations with .
Figure 2:Collocation with coefficients. (a) The two approximations against the exact value, with their collocation nodes. (b) The Bellman residual , which vanishes at the nodes. (c) The escapement chosen by the greedy policy of each approximation, against the optimal escapement.
The residuals in panel (b) vanish at the nodes, as collocation requires, and both peak at about 0.2 between them. The approximations themselves differ much more. A polynomial of degree 11 cannot bend sharply enough to follow the cliff, so it oscillates around it. Near the left end, its value at an empty stock is 1.6 instead of zero. The greedy policy inherits these oscillations (panel (c)). It fishes out every stock below 0.31, past the tipping point, where the optimal policy closes the fishery and lets the stock rebuild. A stock at 0.31 is worth 1.49 under the optimal policy and 0.31, its immediate catch, under this one. Between 0.53 and 0.67 the policy also harvests stocks that should be left to grow. The piecewise-linear approximation is coarse between its nodes, but it follows the cliff, and its greedy policy loses at most 0.064 anywhere. That worst case is near , where the policy closes the fishery a little too early.
The example leaves three questions open, and the rest of the chapter takes them in order. Collocation asked for a zero residual at twelve points; where else could the residual be made small, and what does that choice decide? The twelve coefficients were found by repeating a backup and a fit; when does that repetition converge, and what else could find them? And the polynomial had the smaller residual of the two approximations and a policy loss eighteen times larger; which quantity should judge an approximation?
From One Equation per State to Equations¶
The Bellman optimality equation holds at every state. For the fishery, that is one equation for every stock in , and the unknown is the whole function . Replacing by leaves unknowns, so only conditions can be imposed, and the choice of those conditions is the method.
The earlier chapters made the same move for trajectories. A continuous-time trajectory cannot be chosen one instant at a time, so direct collocation represented the state and the control by polynomial pieces with finitely many coefficients, enforced the differential equation at selected points of each interval, and replaced the integrals of the cost by quadrature. The value function is treated in the same way: a basis for the unknown function, finitely many conditions in place of the equation, and quadrature for the expectations. The method of weighted residuals Chakraverty et al. (2019)Atkinson & Potra (1987) organizes these choices into five steps. Each step below is stated for a general Bellman equation and names the alternatives at that fork. The fishery took one path through the steps, and a box after each step picks the example up where it went through that step; the steps themselves need nothing from the boxes.
Step 1: Choose a Parametric Value Function¶
The unknown value function is replaced by a family indexed by a parameter vector . Nothing in the five steps requires to enter linearly: a neural network with weights is such a family, and every condition below applies to it. Linearity matters for solving. When the family is a linear combination of basis functions,
each condition reduces to linear algebra and can be written out, so this chapter uses linear families to make the steps explicit. The chapter on fitted value methods shows that the solver that carries over to neural networks needs nothing from the representation beyond the ability to fit it to data.
Two kinds of basis are in common use. A global basis, such as Chebyshev polynomials or Fourier modes, gives every coefficient influence over the whole state space, and its error decreases exponentially in when the function is smooth. A local basis, such as the hat functions of piecewise-linear interpolation, splines with small support, or radial basis functions, lets each coefficient act near one node, and its error decreases at a rate set by the node spacing, whatever the smoothness of the function. Tile coding, the linear representation that Sutton (1996) and much of early reinforcement learning relied on, is a local basis of this kind: several overlapping grids partition the state space, each cell is a binary feature, and is the sum of the weights of the cells that contain . Linear representations were the norm in reinforcement learning until neural networks took over in the 2010s, and they remain the setting where the theory is complete. To match a deep network, though, a linear model may need a very large number of features.
Step 2: Define the Bellman Residual¶
Substituting the approximation into the Bellman equation leaves a function of the state,
the Bellman residual, where abbreviates . It measures by how much the approximation fails the equation at , and it is the zero function if and only if is a fixed point of . The Newton–Kantorovich section of the infinite-horizon chapter wrote the Bellman equation as the root-finding problem with . The residual is that operator applied to and then evaluated at the state , . What changes is the argument: takes any function, while takes only the coefficients that describe . Read in the same way, as the operator applied to the function , which returns a new function; it is not a product of a matrix and a vector. One evaluation of it costs one evaluation of the Bellman operator, a maximization over the actions and an expectation over the successor, with the current coefficients inside both. The coefficients enter twice, directly through and again through the expectation inside the maximum, and the maximum makes nonlinear in even though is linear in it.
Step 3: Impose Conditions on the Residual¶
The residual is a function of the state, and has only components. The equation asks for one condition at every state, so it has to be replaced by scalar conditions. To choose them, we first ask how one checks that an object is zero, starting with a vector.
Take . The inner product with the coordinate vector reads off one coordinate, , so the three tests against all return zero only when . Other test vectors work as well, as long as together they reach every direction. In general, is zero if and only if for every , and the single test settles the question, because it returns . Now keep only the two tests and . The vector passes both of them and is not zero. Two tests check in two directions, those of the plane spanned by and , and they say nothing about the component of orthogonal to that plane. Passing both tests means that the component of in the plane is zero.
Each test is therefore a direction. For a unit vector , the inner product is the signed length of the shadow that casts on the line of : it is large when is aligned with and zero when the two are perpendicular. A set of tests passes if and only if is perpendicular to every test direction, which is the same as being perpendicular to the subspace that they span. The tests need not be orthogonal to each other or of unit length; only that subspace matters. The first tab of Figure 3 draws this picture in for one, two or three test directions, including two oblique ones.
A function of the state behaves like a vector with one coordinate for each state, and the sum in the inner product becomes an integral. With a weight over the states, the weighted inner product of two functions is
The argument for vectors carries over: is the zero function if and only if for every test function , and the test returns . Each test function is a direction in the space of functions, and measures how far reaches along it. The coordinate vectors have a counterpart as well. A point mass at a state reads off the value , as reads off . A function has infinitely many directions, and no finite set of tests can check them all. Testing against chosen test functions gives exactly the equations that this step needs,
and the price is the one paid with two tests in . The equations make the residual vanish in the directions of the tests and leave it free in every other direction. The residual of the solution is in general not the zero function. It is a function in which the tests detect nothing.
The second tab of Figure 3 runs these tests on functions. There, each bar is the inner product of a residual with one test function, and selecting a bar shades the product , whose area is the value of that bar. The button that hides the residual from the tests subtracts a function that returns the same test values as the residual: the orthogonal projection onto the span of the tests for hat functions and polynomials, and the piecewise-linear interpolant through the nodes for point masses. After it is pressed, every bar is zero and the residual is still visibly nonzero, like against and . With polynomial tests, hide the residual and predict which bars change when increases by one.
Figure 3:Testing a residual with inner products. First tab: a vector in and one, two or three test directions; each bar is the length of the shadow of on one direction, and the tests detect only the component of in the span of their directions. Second tab: a residual , taken from the presets or drawn with the pointer, is tested against point masses, hat functions or polynomials. Each bar is one test, and the shaded area under the product equals the selected bar. Third tab: one policy-evaluation equation is solved by collocation, Galerkin and least squares with the same basis. Each solution makes its own tests return zero, and the tests of the other two methods do not.
Since the equations control the residual only in the directions of the tests, the approximation that they produce depends on the choice of test functions, and a method is defined by that choice. Three choices cover almost every method in use.
| Method | Test functions | Conditions ( equations) |
|---|---|---|
| Collocation | Point masses at chosen states | |
| Galerkin | The basis functions | |
| Least squares | The derivatives of the residual |
Collocation: a Zero Residual at Chosen States¶
Collocation is the method of the continuous-time collocation chapter, applied to a different equation. There, each piece of a trajectory was stored by its values at nodes, in a Lagrange basis whose cardinal functions equal one at their own node and zero at the others, and the differential equation was imposed only at the collocation points: at each one, the slope of the interpolating polynomial had to match the slope prescribed by the dynamics. Between the points, nothing was imposed. Here the unknown is the value function instead of a trajectory, and the equation is the Bellman equation instead of . Collocation picks states and asks the residual to vanish there,
With a nodal basis, Lagrange polynomials through the collocation points or the hat functions of piecewise-linear interpolation, the coefficient is the value at , and the condition reads . The value stored at each node must equal the Bellman backup computed from the interpolated function, as the slope stored at each node had to equal the slope given by the dynamics. The interpolated backward recursion (16) of the finite-horizon chapter imposed the same condition, one stage at a time.
In the language of test functions, a point mass at picks out the value , so collocation is (9) with point masses as test functions, as the dual-pairing formulation of Legrand & Junca (2025) makes precise. No integral over states appears, so each condition costs one evaluation of the Bellman operator. The conditions make the residual vanish at the nodes and leave it unconstrained between them, as the residual of the differential equation is unconstrained between the collocation points of a trajectory. The name of the method describes this. To collocate, from the Latin collocare, is to place together, and in the definition of Frazer et al. (1937) that the collocation chapter recalled, it is “the act of assigning the error at given points or stations”. The approximation and the exact equation are placed together at a finite set of points: times for a trajectory, states for a value function.
Where to collocate is a choice of its own. For a polynomial of degree , the standard choice is the zeros of the -th Chebyshev polynomial, the Chebyshev nodes, and the combination is called orthogonal collocation. The same nodes serve as the nodes of Gauss–Chebyshev quadrature, the interpolation matrix built on them is well conditioned, and the polynomial through them is within a small factor of the best polynomial approximation of a smooth function, so a residual that vanishes at them stays small between them. Equally spaced nodes have none of these properties once the degree is high. For a nodal basis the collocation points are the nodes of the basis itself, where one cardinal function equals one and the others vanish, so that the interpolation matrix is the identity and the coefficients are the values at the nodes.
The collocation conditions can be rewritten as a fixed-point equation for the function , and the derivation takes three steps. Write for the vector of basis functions at , so that , and for any function of the state write for the vector of its values at the collocation points. The rows of the interpolation matrix are the vectors , so the values of the approximation at the nodes are . Assume that is invertible, which holds for a polynomial basis with distinct nodes and for hat functions collocated at their own nodes.
The first step writes the conditions as one vector equation. The condition at is , and stacking the of them gives
This is already a fixed-point equation, in the coefficients: appears on the right through .
The second step gives a name to the map on the right. The interpolant of a function through the nodes is the element of the span that has the same values as at the nodes. Its coefficients solve , so
Three properties of this map are used below. It is linear in , because enters only through the vector . It reproduces at the nodes, since . And it leaves the elements of the span unchanged: if , then and . Applying twice therefore gives the same result as applying it once, . A linear map with this property is a projection: it sends every function into the span and leaves the span fixed.
The third step multiplies (11) on the left by . For every state ,
where the last equality is (12) with . As an equation between functions,
The steps also run backward. If , then evaluating both sides at the nodes and using that reproduces there gives for every , which are the collocation conditions. The collocation solutions are therefore exactly the fixed points of : the Bellman operator followed by a projection, which is the form that Step 4 exploits.
The derivation used two assumptions. The family is linear in , so that its values at the nodes are and the interpolant of any function is again a member of the family. And is invertible. Nothing was assumed about beyond the fact that it returns a function that can be evaluated at the nodes. The operator may contain a maximum and be nonlinear in ; the projection is linear whatever is, and the nonlinearity stays inside . With a nodal basis, is the identity and (12) becomes , a combination of the values at the nodes weighted by the cardinal functions. The next chapter uses this form to decide when is a contraction.
Read the right-hand side as a composition of maps on functions, not as a product of matrices. is the operator applied to the function , which gives a new function, and is that function passed through the interpolation procedure, which gives an element of the span. With parentheses, . In code, is a call such as an interpolation routine: it receives the values of at the nodes and returns the coefficients of the interpolant. The composed map is a new operator, and (14) is a new Bellman-type equation whose solution is the approximation. Texts on approximate dynamic programming, following Bertsekas & Tsitsiklis (1996), often write the projection ; it is not a policy.
Galerkin: a Residual Orthogonal to the Basis¶
Galerkin takes the basis functions themselves as test functions, for . By linearity the residual is then orthogonal to every function in the approximation space ,
so that is orthogonal to . The vector example at the start of this step has the same structure. To approximate a vector of by a vector in the plane spanned by and , one keeps , and the error is orthogonal to the plane, so the tests and detect nothing in it. Keeping is the orthogonal projection onto the plane, and the Galerkin conditions say that is the orthogonal projection of onto .
The same three steps as for collocation make this precise. Collect the inner products among the basis functions in the mass matrix , with entries , and for a function write for the vector of its inner products with the basis, . Assume that the basis functions are linearly independent under : no combination with has zero -norm. Since , this says that is positive definite, hence invertible.
The first step writes the conditions as one vector equation. Since , the inner product of with is . Condition , , therefore reads , and stacking the conditions gives
a fixed-point equation in the coefficients, as for collocation, with in place of and inner products in place of values at the nodes.
The second step identifies the map on the right. The -orthogonal projection of a function onto is the element of closest to in the norm , the function whose coefficients minimize . Expanding the square,
a quadratic function of whose Hessian is positive definite. Its unique minimizer is the zero of the gradient , which is , so
This map has the properties of the interpolation operator. It is linear in , because is. It leaves the elements of unchanged: if , then and , so . In place of reproducing at the nodes, it leaves an error that is orthogonal to every basis function, . That is the picture: the part of that the projection discards is invisible to the tests.
The third step multiplies (16) on the left by :
for every , which is , the projected Bellman equation (14) with now the -orthogonal projection onto . Conversely, if , the residual is orthogonal to every by the last property, which is the set of Galerkin conditions. As for collocation, the derivation needs the family to be linear in and to be invertible, and it allows to be nonlinear. Orthogonality here is with respect to the weighted inner product . When is not uniform, the same map seen in the unweighted Euclidean geometry is an oblique projection; it is orthogonal only after rescaling each state by . In reinforcement learning is the distribution of the states in the data, and the next chapter shows that this choice decides whether the iteration converges.
The conditions are integrals over the state space, so Galerkin needs a quadrature rule for them on top of the quadrature inside . With an orthogonal polynomial basis and its matching weight, the inner products among basis functions are known in closed form and the systems are well conditioned. When the states are instead sampled from , the integrals become sample averages and the Galerkin conditions become the normal equations of a least-squares regression: is the least-squares fit of the basis to the backups at the sampled states. The targets of that regression depend on its own solution, and Step 4 breaks the circularity.
One Formula for Any Fixed Tests¶
Collocation and Galerkin are two instances of one construction. For test functions fixed in advance, form the matrix with entries and the vector with entries . The conditions (9) read , and when is invertible the map is a projection onto whose error passes all tests. The argument of the two previous subsections goes through unchanged and gives . Collocation has point masses as tests, so and . Galerkin has the basis functions as tests, so and . When the tests differ from the basis, the error of is orthogonal to the tests and not to , and is an oblique projection: it moves onto along the directions that the tests cannot see. The interpolation operator is of this kind.
On a finite state space with states, these maps are matrices. Stack the rows for all states into an matrix , let , so that , and let be the matrix whose row selects the state , so that and . Put the values of the tests at the states in the columns of an matrix . Then , , and the projection is the matrix
It is idempotent, , because is the identity. A point mass at is the test whose weighted inner product with returns , so for collocation ; for Galerkin, . The two projections are
The Galerkin matrix is the one that the next chapter uses, where is written and is written .
The code below checks the derivations on the policy-evaluation problem of Figure 3, with six hat functions and with six Legendre polynomials collocated at the Chebyshev nodes. It solves the collocation and the Galerkin conditions directly, builds the two projections from (12) and (18), and measures how far each solution is from being a fixed point of each projected operator.
Source
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path.cwd() / "code"))
from test_functions_demo import GAMMA, GRID, PROBS, QW, basis, reward, solve, successors
def backup(phi, n, theta, s):
# (L_pi v_theta)(s) = r(s) + gamma E[v_theta(s')]
return reward(s) + GAMMA * (phi(successors(s), n) @ theta) @ PROBS
for kind in ("hat", "legendre"):
n = 6
phi, nodes = basis(kind, n)
Phi = phi(nodes, n) # interpolation matrix, Phi_ij = phi_j(s_i)
F = phi(GRID, n) # basis on a fine grid
M = F.T @ (QW[:, None] * F) # mass matrix, uniform weight
def P_col(g): # coefficients of the interpolant
return np.linalg.solve(Phi, g(nodes))
def P_gal(g): # coefficients of the w-orthogonal projection
return np.linalg.solve(M, F.T @ (QW * g(GRID)))
print(f"{kind} basis, n = {n}: sup over states of |v_theta - P L v_theta|")
print(f"{'solution':<13}{'P = interpolation':>20}{'P = orthogonal':>17}")
for method in ("collocation", "galerkin"):
theta = solve(kind, n, method)
Lv = lambda s: backup(phi, n, theta, s)
gaps = [np.max(np.abs(F @ theta - F @ P(Lv))) for P in (P_col, P_gal)]
print(f"{method:<13}{gaps[0]:>20.1e}{gaps[1]:>17.1e}")
# P leaves the span fixed, and the Galerkin error is orthogonal to the basis
c = np.random.default_rng(0).normal(size=n)
g = lambda s: phi(s, n) @ c
Lv = lambda s: backup(phi, n, solve(kind, n, "galerkin"), s)
err = Lv(GRID) - F @ P_gal(Lv)
print(f" span fixed: {np.max(np.abs(P_col(g) - c)):.1e} (interpolation), "
f"{np.max(np.abs(P_gal(g) - c)):.1e} (orthogonal)")
print(f" max |<g - P g, phi_i>_w| for the orthogonal projection: "
f"{np.max(np.abs(F.T @ (QW * err))):.1e}\n")hat basis, n = 6: sup over states of |v_theta - P L v_theta|
solution P = interpolation P = orthogonal
collocation 3.6e-15 4.5e-01
galerkin 2.9e-01 1.1e-14
span fixed: 0.0e+00 (interpolation), 4.4e-16 (orthogonal)
max |<g - P g, phi_i>_w| for the orthogonal projection: 1.1e-15
legendre basis, n = 6: sup over states of |v_theta - P L v_theta|
solution P = interpolation P = orthogonal
collocation 3.6e-15 1.5e-01
galerkin 1.5e-01 1.3e-13
span fixed: 2.2e-16 (interpolation), 2.0e-15 (orthogonal)
max |<g - P g, phi_i>_w| for the orthogonal projection: 1.2e-13
Each solution is a fixed point of its own projected operator, to rounding error, and is not a fixed point of the other one. The two methods solve the same kind of equation, , with two different projections, and that is the only difference between them.
Least Squares: the Smallest Residual¶
The most direct choice minimizes the weighted norm of the residual,
whose first-order conditions are (9) with test functions . For the Bellman residual this is Bellman residual minimization. Its test functions,
contain the derivative of the Bellman operator with respect to the coefficients, which Galerkin and collocation never need. Computing it means differentiating through the maximum, which Step 4 does with the envelope theorem. The solution also differs from the Galerkin solution, because the residual is made orthogonal to a different set of functions. It is not a projected Bellman equation with a projection fixed in advance: the tests contain the derivative of , so they change with the operator and, through the maximum, with . The chapter on fitted value methods returns to the difference between fitting a backup and minimizing the residual, which separates the algorithms used in practice from this one.
That difference is often blurred. DQN and the other fitted value methods are frequently described as minimizing the Bellman error, and they do not: they fit to targets computed from the previous iterate and held fixed (a stop-gradient on the target), which is Galerkin or collocation solved by iteration, not least squares on the residual. Bellman residual minimization is the residual-gradient algorithm of Baird (1995), which mainstream reinforcement learning did not adopt, in part because an unbiased gradient of the squared residual needs two independent samples of the successor state from the same state, which a single online trajectory does not provide. The best known method of this kind today is path consistency learning Nachum et al. (2017). It minimizes the squared residual of the smooth Bellman equation of the entropy-regularized chapter, written along a path of several steps, and it assumes deterministic dynamics, which removes the double-sampling problem. The trajectory balance objective used to train generative flow networks is a consistency condition of the same kind Malkin et al. (2022)Tiapkin et al. (2024).
The three methods compute three different approximations from the same basis, because each one makes the residual vanish in different directions. The third tab of Figure 3 shows this on a small policy-evaluation problem on . The next state is , where equals 0, or 1 with probabilities , and . The reward rises smoothly from 0 to 1 around , and . The policy is fixed, so the operator is and contains no maximum. The residual is then affine in , and each set of conditions is a linear system in . The code below solves the three systems with six hat functions and a uniform weight , and then tests each solution against all three families of test functions.
Source
import sys
from pathlib import Path
sys.path.insert(0, str(Path.cwd() / "code"))
from test_functions_demo import table
rows = table(kind="hat", n=6)
families = ("collocation", "galerkin", "least squares")
print("Largest |test value| of each solution, against each family of tests")
print(f"{'solution':<15}" + "".join(f"{f:>15}" for f in families) + f"{'sup |v - v_pi|':>16}")
for method, row in rows.items():
print(f"{method:<15}" + "".join(f"{row[f]:>15.4f}" for f in families) + f"{row['value error (sup)']:>16.3f}")Largest |test value| of each solution, against each family of tests
solution collocation galerkin least squares sup |v - v_pi|
collocation 0.0000 0.1202 0.1232 0.668
galerkin 0.2853 0.0000 0.0027 0.351
least squares 0.2871 0.0022 0.0000 0.335
Each row has a zero in its own column, as the conditions of that method require, and no row has a zero anywhere else. The Galerkin and least-squares solutions are close to each other on this problem. Both leave a residual of about 0.29 at one of the collocation points, which is what the collocation conditions rule out. None of the three solutions satisfies the Bellman equation, and none satisfies the conditions of the other two methods. The choice between them is a choice of the directions in which the residual must vanish. In reinforcement learning, the Galerkin conditions with the states weighted by the data are the equations that TD(0) and LSTD solve, as the next chapter shows.
Why testing against functions is enough
The constructive argument above, choosing , needs to be a function with a finite norm. The general statement, that a nonzero element of a normed space is detected by some continuous linear functional, is a consequence of the Hahn–Banach theorem, often phrased as “the dual space separates points”. It is also what makes Galerkin a minimization in its own right. The dual norm of with respect to ,
measures the residual by its largest inner product with the approximation space, and the Galerkin conditions make it zero. Point masses are not functions but distributions, and the dual-pairing formulation of Legrand & Junca (2025) treats collocation and Galerkin uniformly: test objects act on the residual through a pairing, and the induced norm measures a residual by its worst case over the test objects. The same view motivates adversarial formulations Zang et al. (2020) in which both the approximation and the test functions are learned.
Step 4: Solve the Equations¶
The conditions of Step 3 are equations in the unknowns, with , or for collocation. They are nonlinear, because the maximum in the Bellman operator is. The infinite-horizon chapter solved the exact Bellman equation with two general methods for operator equations, successive approximation, which gave value iteration, and the Newton–Kantorovich method, which gave policy iteration. Each has a counterpart for the equations.
Function Iteration¶
For collocation and Galerkin, the conditions have the fixed-point form of (14), and the natural solver repeats the map,
value iteration with a projection after each application of the operator. The functions are never stored: each one is the function described by its coefficients , and what the iteration updates is the coefficient vector, from to . One iteration of the collocation version has two steps. The first evaluates the operator at the nodes with the current function, for . The second chooses the coefficients that reproduce those targets, which is the linear system with the interpolation matrix . With hat functions collocated at their own nodes the solve is trivial, because is the identity. The Galerkin version replaces the second step by the orthogonal projection of the target function, which is the weighted least-squares fit
Its first-order conditions are the linear system with the mass matrix and . The system is linear whatever the operator is, because the target is computed from and held fixed while is chosen. With sampled states, the fit is an ordinary regression of the backups on the basis. This fit is not the least-squares method of Step 3. Least squares minimizes once, with on both sides of the residual. The fit above solves a new minimization at every iteration, with only on the side of the approximation; in an implementation by gradient descent, the target is wrapped in a stop-gradient. The circularity of Step 3 is gone: the targets come from the previous iterate. Fitting a parametric function to Bellman backups, then recomputing the backups, is the algorithm that the chapter on fitted value methods calls fitted value iteration and generalizes to any regressor.
Whether the iteration converges is a separate question. Being a contraction is a property of an operator with respect to a norm: an operator that contracts in the sup norm need not contract in a weighted norm, and conversely. The composed operator therefore inherits the contraction of when is a nonexpansion in the same norm, that is, when
The Bellman operator is a -contraction in the sup norm, so value iteration converges from any start (Proposition 2). If is a nonexpansion in the sup norm, then , so is a -contraction, and (25) converges to the unique solution of the projected Bellman equation, with the sup-norm error multiplied by at most per iteration. For a linear , being a sup-norm nonexpansion means that its sup-norm operator norm, which for interpolation is the Lebesgue constant , is at most one, and this depends on the sign of the weights. An interpolation operator with nonnegative cardinal functions returns a convex combination of the targets, so , the condition of Proposition 1, and is a nonexpansion. Polynomial interpolation through Chebyshev nodes has cardinal functions that dip below zero between the nodes, so : for some pairs of target vectors, . The composition need not be a contraction, and the iteration can diverge although every iteration reproduces its targets exactly. The next chapter proves that the first kind of fit always preserves the contraction and shows what happens with the second. Even when it converges, function iteration is slow when is near one: the error bound decreases by a factor per iteration, so reducing it by 10-10 with takes about 450 iterations.
Newton’s Method¶
The alternative treats as a rootfinding problem and linearizes it,
where is the Jacobian of . For collocation, , and the Jacobian entries are
The first term is a basis function at a node. The second is the derivative of the Bellman operator with respect to a coefficient, the quantity that the least-squares conditions of Step 3 also needed, and it contains a maximum. The maximum is not differentiable where two actions tie, but wherever the maximizer is unique its derivative is given by the envelope theorem.
Before reading on, differentiate with the chain rule, writing for the maximizer. Which term involves , and why does it vanish?
For the Bellman operator, , the objective is linear in with coefficients , so
where is the greedy action at for the current coefficients. The derivative is the expected value of the basis function at the successor under the greedy action, and computing it costs one more quadrature per node and basis function. The same formula holds for the discrete-action case, and on a finite set of actions the maximizer is unique except at ties.
Substituting (31) into the Newton step gives it a familiar form. Let be the greedy policy for , let collect its rewards at the nodes, and let be the matrix with entries . Then and , and the Newton update simplifies to
This is the policy evaluation equation of , imposed at the collocation nodes and solved within the span of the basis. Newton’s method on the collocation equations alternates a greedy improvement with an approximate evaluation, exactly as Newton’s method on the exact Bellman equation is policy iteration (Newton-Kantorovich and Policy Iteration). With the smooth Bellman operator of the regularized chapter, the maximum is replaced by a log-sum-exp, the operator is differentiable everywhere, and the same step holds with the softmax policy in place of the greedy one (Smooth Policy Iteration Is Newton’s Method).
Newton’s method converges quadratically near the solution, a few iterations instead of the hundreds of function iteration, and it does not need to be a contraction, since it never iterates that map. It pays for this in two ways. Each iteration forms and solves the Jacobian system, whose entries need the expectations of every basis function at every node. And it depends on the starting point: started far from the solution it can diverge, or converge to a fixed point that the equations have and the Bellman equation does not.
| Method | Convergence | Per-iteration cost | Needs |
|---|---|---|---|
| Function iteration | Linear, factor | backups and one linear solve with a fixed matrix | to be a contraction |
| Newton’s method | Quadratic near the solution | backups, expectations and a fresh linear solve | A good starting point |
The two solvers complement each other. When the fit is monotone and is moderate, function iteration is simple and robust. When is near one or the basis is a high-order polynomial, a hybrid works well: a few function iterations with a coarse, monotone approximation to reach the basin of attraction, then Newton’s method with the accurate basis. This is how Rust solved his bus-engine model (Rust’s Bus Engines and Inverse Reinforcement Learning), and the next chapter develops the Newton side as approximate policy iteration.
Step 5: Check the Solution¶
The conditions of Step 3 control the residual only where they were imposed, at the collocation nodes or against the chosen test functions. The first check is therefore to evaluate the residual where it was not controlled: at many states between the nodes, with a finer quadrature inside the operator than the one used in the fit, and against higher-order basis functions in the Galerkin case.
A small residual everywhere does bound the value error. Since and is a -contraction,
where the norm of is taken over all states, not over the nodes. The bound is loose in general, and neither the residual nor the value error is what is used. The greedy policy is, and its loss is the difference between the optimal value and the value of acting on the approximation. The three quantities answer different questions. The residual is what the method controls. The value error is what the residual bounds, through . The policy loss is what matters, and it depends on the value error only through the differences between actions, which an approximation can get wrong while its values are accurate and right while they are not. The chapter on fitted value methods bounds the policy loss by the value error and tests both bounds on a problem that a government agency solves every year.
Exercises¶
The exercises use the notation of the five steps. The first ones are short checks of the definitions; most of the others can be done by hand, and Exercise 7 needs the fishery module that produced the figures.
Solution to Exercise 1
Against the basis functions themselves: for every . The residual is then orthogonal to the whole span, so the -orthogonal projection of onto the span is itself.
Solution to Exercise 2
Collocation forces the residual to vanish at selected states. Least squares minimizes the weighted squared residual over the state space. Least squares needs the envelope theorem, because its first-order conditions contain the derivative of the Bellman operator with respect to the coefficients; collocation needs it only if the collocation equations are solved by Newton’s method.
Solution to Exercise 3
Collocation controls the residual at the nodes only. The sup norm of the residual over all states bounds the value error through , and the value error bounds the policy loss (next chapter). Both bounds are loose, and the policy depends on differences between the values of actions rather than on the values themselves, so an approximation with a smaller residual can place a decision boundary in the wrong region, as the polynomial does across the tipping point.
Solution to Exercise 4
.
.
gives , and gives .
The conditions and give and .
Collocation: largest residual 0.25, largest value error 0.389 (near ). Galerkin: largest residual 0.1875, largest value error 0.375 (at ). Galerkin is slightly better by both measures here. Both are poor, because a parabola cannot follow a line through the origin and the ends: no choice of conditions repairs a basis that cannot represent the solution. Least squares happens to give the Galerkin answer in this problem, because the residual is linear in and its derivatives are and , which span the same space as the basis.
Solution to Exercise 5
and .
Both lie in on and sum to one, so is a convex combination of and at every and . The composition is then a -contraction for any -contraction , and function iteration converges from any start. On this problem it converges to the collocation solution of Exercise 4.
The cardinal functions are , and . The first and last are negative on parts of , so . The sup-norm operator norm of is 1.25, so is not a nonexpansion: some pair of target vectors has . The bound on the modulus of then exceeds one for , and the argument fails.
Solution to Exercise 6
Everywhere except . The envelope theorem gives the derivative of the active action: 1 for and -1 for .
The maximizer is not unique. The one-sided derivatives are -1 and 1, and every slope with is a subgradient: it is the derivative of the value of the randomized choice that takes the first action with probability .
A tie means two actions have the same value at that node, so evaluating either one gives a valid Newton step: the step solves the evaluation equation of some greedy policy, and policy iteration converges whichever greedy action it picks. The smooth Bellman operator replaces the maximum by a log-sum-exp, which is differentiable everywhere; its Jacobian uses the softmax policy, which splits the probability between tied actions, and no tie-breaking rule is needed.
Solution to Exercise 7
import numpy as np
from fishery_tipping_point import Bellman, HatBasis, growth, X_MAX
bellman, basis = Bellman(), HatBasis(12)
nodes, gamma = basis.nodes, bellman.gamma
def hats(points): # phi_j(points), one column per node
return np.stack([np.interp(points, nodes, np.eye(basis.n)[j]) for j in range(basis.n)], axis=-1)
theta = np.zeros(basis.n)
for k in range(30):
escapement = bellman.greedy(basis.function(theta))
index = np.clip(np.searchsorted(bellman.x, nodes, side="right") - 1, 0, bellman.x.size - 1)
a = escapement[index] # greedy escapement at each node
successors = np.clip(np.outer(growth(a), bellman.z), 0, X_MAX)
P_Phi = np.einsum("q,iqj->ij", bellman.w, hats(successors))
new = np.linalg.solve(np.eye(basis.n) - gamma * P_Phi, nodes - a)
step, theta = np.abs(new - theta).max(), new
if step < 1e-10:
break
print(k + 1, "Newton iterations")The steps are 1.6, 2.9, 0.86, and then zero: five iterations, against about 410 for function iteration, and the coefficients agree with the fixed point of function iteration to 10-14. They must agree, because both methods solve the same collocation equations , which have a unique solution here since is a contraction; Newton’s method only finds it faster.
Solution to Exercise 8
This exercise is open-ended. A least-squares fit to more nodes than coefficients is no longer an averager, so it carries no guarantee either, although oversampling reduces the size of the weights. Newton’s method does not iterate and needs no contraction; started from the piecewise-linear solution, which is close, it is the hybrid strategy of the chapter. Whatever converges, judge it by the policy loss, as in Step 5: a polynomial that converges can still place the decision boundary on the wrong side of the tipping point.
Summary and Outlook¶
Replacing the value function by turns the Bellman equation into a residual that no choice of makes zero everywhere. The method of weighted residuals imposes conditions on it instead: collocation makes it vanish at chosen states, Galerkin makes it orthogonal to the basis, and least squares minimizes its norm. The first two are projected Bellman equations , and their solvers are the two solvers of the exact equation with a projection inserted: function iteration, which is value iteration with a fit after each sweep, and Newton’s method, which is policy iteration with each evaluation done within the span of the basis. The fishery showed that the fit decides both the accuracy of the solution and whether function iteration converges, and that a smaller residual does not mean a better policy.
Nothing in the five steps is specific to the Bellman equation. Any operator equation for an unknown function is treated the same way, with a basis for , a residual , test functions, and one of the two solvers, and the collocation chapter did exactly this for differential equations, with polynomial pieces for the trajectory and the equation of motion enforced at the collocation points. What the Bellman equation adds is the maximum, which makes the equations nonlinear and the Jacobian a matter for the envelope theorem, and the contraction, which is what makes function iteration an option at all.
Step 4 left two things open. Function iteration converged for one basis and not the other, and the explanation, that the fit must be a nonexpansion in the sup norm, was asserted and not proved. Newton’s method was shown to be policy iteration in coefficient space for collocation, without saying how accurate each evaluation must be for the policies to improve. The next chapter takes up both. It shows when the fit makes function iteration diverge and which fits cannot, and turns Newton’s method into approximate policy iteration. The chapter after it then lets the fit be any regressor, which turns function iteration into fitted value iteration, a sequence of regression problems with Bellman targets, bounds its error when every fit is accurate, and replaces the exact expectations by samples, which leads to fitted Q-iteration.
- Ernst, D., Geurts, P., & Wehenkel, L. (2005). Tree-Based Batch Mode Reinforcement Learning. Journal of Machine Learning Research, 6, 503–556.
- Riedmiller, M. (2005). Neural Fitted Q Iteration – First Experiences with a Data Efficient Neural Reinforcement Learning Method. Proceedings of the 16th European Conference on Machine Learning (ECML), 317–328.
- Hafner, R., & Riedmiller, M. (2011). Reinforcement learning in feedback control: Challenges and benchmarks from technical process control. Machine Learning, 84(1–2), 137–169. 10.1007/s10994-011-5235-x
- Chakraverty, S., Mahato, N. R., Karunakar, P., & Rao, T. D. (2019). Weighted Residual Methods. In Advanced Numerical and Semi-Analytical Methods for Differential Equations (pp. 25–44). John Wiley & Sons, Inc. 10.1002/9781119423461.ch3
- Atkinson, K. E., & Potra, F. A. (1987). Projection and Iterated Projection Methods for Nonlinear Integral Equations. SIAM Journal on Numerical Analysis, 24(6), 1352–1373. 10.1137/0724087
- Boettiger, C., Mangel, M., & Munch, S. (2015). Avoiding tipping points in fisheries management through Gaussian process dynamic programming. Proceedings of the Royal Society B: Biological Sciences, 282(1801), 20141631. 10.1098/rspb.2014.1631
- Reed, W. J. (1979). Optimal escapement levels in stochastic and deterministic harvesting models. Journal of Environmental Economics and Management, 6(4), 350–363. 10.1016/0095-0696(79)90014-7
- Clark, C. W. (1973). Profit maximization and the extinction of animal species. Journal of Political Economy, 81(4), 950–961. 10.1086/260090
- Sutton, R. S. (1996). Generalization in Reinforcement Learning: Successful Examples Using Sparse Coarse Coding. Advances in Neural Information Processing Systems, 8, 1038–1044.
- Legrand, M., & Junca, S. (2025). Weighted Residual Solution Methods.
- Frazer, R. A., Jones, W. P., & Skan, S. W. (1937). Approximations to Functions and to the Solutions of Differential Equations (Reports and Memoranda No. 1799). Aeronautical Research Committee.
- Bertsekas, D. P., & Tsitsiklis, J. N. (1996). Neuro-Dynamic Programming. Athena Scientific.
- Baird, L. (1995). Residual algorithms: Reinforcement learning with function approximation. Proceedings of the Twelfth International Conference on Machine Learning, 30–37.
- Nachum, O., Norouzi, M., Xu, K., & Schuurmans, D. (2017). Bridging the Gap Between Value and Policy Based Reinforcement Learning. Advances in Neural Information Processing Systems, 30, 2775–2785.
- Malkin, N., Jain, M., Bengio, E., Sun, C., & Bengio, Y. (2022). Trajectory Balance: Improved Credit Assignment in GFlowNets. Advances in Neural Information Processing Systems, 35.