Simple Algorithm
Reinforcement Learning · Bootstrapping · 24 min

Optimal Control & Model Predictive Control

LQR, trajectory optimization and replanning at every step.

Long before deep reinforcement learning, engineers steered aircraft, rockets and refineries with models and a simple principle: plan, act, measure, plan again. This lesson builds the two workhorses of optimal control. The linear–quadratic regulator's optimal policy is a matrix computed by a backward recursion; solved by hand for a one-dimensional system, it produces the golden ratio. Model predictive control re-solves a planning problem at every step. You'll see why short horizons are myopic, why replanning survives a wrong model, and why sampling planners struggle as plans get longer.

What you’ll learn

  • Translate between RL and control vocabulary, and set up a discrete-time control problem with dynamics, stage cost and horizon.
  • Derive the finite-horizon LQR solution, a quadratic cost-to-go with linear feedback given by the Riccati recursion, and compute it for a scalar system.
  • Write the MPC loop, and explain why replanning from measured states tolerates model errors and why short horizons without a terminal cost are myopic.
  • Implement shooting planners, random shooting and the cross-entropy method, and explain why random shooting degrades as the horizon grows.
  • Describe where MPC is used in practice and what changes when the model is learned.

Control in the language of RL

Optimal control studies the problem RL studies, from the other side: the model is usually known, costs replace rewards, and the state is a vector of real numbers. In discrete time, a state xt∈Rn\mathbf x_t\in\R^n and a control ut∈Rm\mathbf u_t\in\R^m produce the next state xt+1=f(xt,ut)\mathbf x_{t+1}=f(\mathbf x_t,\mathbf u_t), and the controller minimizes J=∑t=0H−1c(xt,ut)+cH(xH)J=\sum_{t=0}^{H-1}c(\mathbf x_t,\mathbf u_t)+c_H(\mathbf x_H) over a horizon HH, or the infinite sum.

The optimal cost-to-go satisfies the dynamic-programming recursion Vt(x)=min⁡u[c(x,u)+Vt+1(f(x,u))]V_t(\mathbf x)=\min_{\mathbf u}\big[c(\mathbf x,\mathbf u)+V_{t+1}(f(\mathbf x,\mathbf u))\big]: the Bellman optimality equation for a deterministic model, with min⁡\min in place of max⁡\max.

Reinforcement learningControl
State ssState x\mathbf x
Action aaControl, or input, u\mathbf u
Reward rrCost c=−rc=-r
Transition probabilities P(s′∣s,a)P(s'\mid s,a)Dynamics x′=f(x,u)\mathbf x'=f(\mathbf x,\mathbf u), often plus noise w\mathbf w
Policy π\piController, or feedback law u=κ(x)\mathbf u=\kappa(\mathbf x)
Optimal value V⋆V^\starOptimal cost-to-go (with the sign flipped)
Planning with a modelTrajectory optimization; model predictive control
xt+1=(xt+1vt+1)=(10.101)⏟A(xtvt)+(00.1)⏟But,c(x,u)=x2+v2+R u2\mathbf x_{t+1}=\begin{pmatrix}x_{t+1}\\v_{t+1}\end{pmatrix}=\underbrace{\begin{pmatrix}1&0.1\\0&1\end{pmatrix}}_{A}\begin{pmatrix}x_t\\v_t\end{pmatrix}+\underbrace{\begin{pmatrix}0\\0.1\end{pmatrix}}_{B}u_t,\qquad c(\mathbf x,u)=x^2+v^2+R\,u^2
The cart of this lesson's widgets: a 1 kg mass on a frictionless track, with position xx, velocity vv and force uu, simulated in steps of 0.1 s. Runs last 200 steps (20 s) and start at rest 2 m from the target, (x,v)=(2,0)(x,v)=(2,0).
Check your understanding

In the cart above, a force applied at step tt first changes which state variable, and when?

  1. The position, at step t+1t+1
  2. The velocity at step t+1t+1; the position only from step t+2t+2
  3. Both, at step t+1t+1
  4. Neither, until the force is removed
Show the answer

B. The velocity at step t+1t+1; the position only from step t+2t+2

vt+1=vt+0.1 utv_{t+1}=v_t+0.1\,u_t and xt+1=xt+0.1 vtx_{t+1}=x_t+0.1\,v_t: the force enters the velocity first, and the position responds one step later, through the velocity. This lag will matter when we plan only a step or two ahead.

LQR: quadratic costs stay quadratic

When the dynamics are linear, xt+1=Axt+But\mathbf x_{t+1}=A\mathbf x_t+B\mathbf u_t, and the cost is quadratic, ∑t<H(xt⊤Qxt+ut⊤Rut)+xH⊤QfxH\sum_{t<H}(\mathbf x_t^\top Q\mathbf x_t+\mathbf u_t^\top R\mathbf u_t)+\mathbf x_H^\top Q_f\mathbf x_H with Q,Qf⪰0Q,Q_f\succeq0 and R≻0R\succ0, dynamic programming can be carried out exactly. The linear–quadratic regulator (LQR) rests on one fact: if the cost-to-go one step later is a quadratic form, so is the cost-to-go now.

DerivationOne step of the Riccati recursion
  1. Vt(x)=min⁡u[x⊤Qx+u⊤Ru+(Ax+Bu)⊤Pt+1(Ax+Bu)]V_t(\mathbf x)=\min_{\mathbf u}\Big[\mathbf x^\top Q\mathbf x+\mathbf u^\top R\mathbf u+(A\mathbf x+B\mathbf u)^\top P_{t+1}(A\mathbf x+B\mathbf u)\Big]

    Suppose Vt+1(x)=x⊤Pt+1xV_{t+1}(\mathbf x)=\mathbf x^\top P_{t+1}\mathbf x with Pt+1⪰0P_{t+1}\succeq0, which holds at t+1=Ht+1=H with PH=QfP_H=Q_f. The cost of applying u\mathbf u in state x\mathbf x is a quadratic function of u\mathbf u:

  2. ut⋆=−Ktx,Kt=(R+B⊤Pt+1B)−1B⊤Pt+1A\mathbf u_t^\star=-K_t\mathbf x,\qquad K_t=\big(R+B^\top P_{t+1}B\big)^{-1}B^\top P_{t+1}A

    Its gradient in u\mathbf u is 2Ru+2B⊤Pt+1(Ax+Bu)2R\mathbf u+2B^\top P_{t+1}(A\mathbf x+B\mathbf u), and R+B⊤Pt+1B≻0R+B^\top P_{t+1}B\succ0, so the unique minimizer is a linear function of the state:

  3. Pt=Q+A⊤Pt+1A−A⊤Pt+1B(R+B⊤Pt+1B)−1B⊤Pt+1AP_t=Q+A^\top P_{t+1}A-A^\top P_{t+1}B\big(R+B^\top P_{t+1}B\big)^{-1}B^\top P_{t+1}A

    Substitute it back. The terms in KtK_t combine, and the cost-to-go is again quadratic, with the matrix given by the Riccati recursion:

  4. Run it backward from PH=QfP_H=Q_f. The optimal controller is linear feedback with time-varying gains KtK_t, and the gains do not depend on the initial state, so they are computed before the first step. For long horizons PtP_t settles to a fixed point PP, the solution of the algebraic Riccati equation, and the controller becomes a constant gain KK. When that happens, and the proof, are in The Linear–Quadratic Regulator.

Predict before you look

Iterate the scalar recursion p←(1+2p)/(1+p)p\leftarrow(1+2p)/(1+p) from p=0p=0. What is pp after three iterations?

Show the answer

1.6

0→1→1.5→1.60\to1\to1.5\to1.6, and the fourth iterate is 21/13≈1.61521/13\approx1.615: the iterates approach φ≈1.618\varphi\approx1.618 fast. Each iteration adds one step of horizon, so this is value iteration on quadratic cost-to-go functions.

python
import numpy as np

def lqr_gains(A, B, Q, R, Qf, H):
    """Finite-horizon LQR by the Riccati recursion: gains K_0..K_{H-1}, cost-to-go matrices P_0..P_H."""
    P = [None] * (H + 1)
    K = [None] * H
    P[H] = Qf
    for t in reversed(range(H)):
        M = R + B.T @ P[t + 1] @ B
        K[t] = np.linalg.solve(M, B.T @ P[t + 1] @ A)       # K_t = M^{-1} B^T P_{t+1} A
        P[t] = Q + A.T @ P[t + 1] @ A - A.T @ P[t + 1] @ B @ K[t]
    return K, P

dt = 0.1
A = np.array([[1.0, dt], [0.0, 1.0]])
B = np.array([[0.0], [dt]])
K, P = lqr_gains(A, B, Q=np.eye(2), R=np.array([[1.0]]), Qf=np.zeros((2, 2)), H=600)
x0 = np.array([2.0, 0.0])
print(K[0], x0 @ P[0] @ x0)   # first-step gain and optimal cost of a 600-step problem

The recursion for the cart with R=1R=1. Six hundred steps are enough for the first gain to equal, to three decimals, the infinite-horizon gain K=(0.917, 1.682)K=(0.917,\,1.682), and for the optimal cost from (2,0)(2,0) to be x0⊤Px0≈73.4\mathbf x_0^\top P\mathbf x_0\approx73.4: the numbers the widget below shows.

LQR on the cart

The control cost RR sets the price of force against the price of being away from the target. The widget computes LQR's gain for the cart from the Riccati equation and simulates the result. Before you run it, use the cost-to-go matrix.

Predict before you look

For R=1R=1 the cost-to-go matrix is P=(18.3410.9010.9018.91)P=\begin{pmatrix}18.34&10.90\\10.90&18.91\end{pmatrix}. What is the optimal total cost x0⊤Px0\mathbf x_0^\top P\mathbf x_0 from the start (x,v)=(2,−1)(x,v)=(2,-1), 2 m out and already moving toward the target at 1 m/s?

Show the answer

48.7

18.34⋅4+2⋅10.90⋅2⋅(−1)+18.91⋅1=73.36−43.60+18.91=48.6718.34\cdot4+2\cdot10.90\cdot2\cdot(-1)+18.91\cdot1=73.36-43.60+18.91=48.67. The negative cross term rewards already moving the right way: from rest at (2,0)(2,0) the cost is 73.4. Drag the start to (2,−1)(2,-1) in the widget and check.

MPC: plan, apply the first control, replan

Most problems are not linear–quadratic: the dynamics are nonlinear, the controls are limited, the model is learned. Model predictive control (MPC) handles them by solving a finite-horizon problem online, from the current measured state, at every step:

text
MPC(model f̂, stage cost c, terminal cost c_H, horizon H):
    at every time step t:
        x ← measure the current state
        plan u_0 … u_{H−1} minimizing  Σ_k c(x_k, u_k) + c_H(x_H)
             subject to  x_0 = x,  x_{k+1} = f̂(x_k, u_k)  (and any limits on x and u)
        apply u_0 only; keep u_1 … u_{H−1} to warm-start the next plan

The receding horizon: the plan always looks HH steps ahead of the present, and only its first control is ever executed.

Two consequences follow. Myopia. With cH=0c_H=0 the planner sees only HH steps of cost. In the scalar example the first gain of an HH-step plan is k=p/(1+p)k=p/(1+p), with pp from H−1H-1 Riccati steps: 00 for H=1H=1, 12\tfrac12 for H=2H=2, 35\tfrac35 for H=3H=3, approaching 0.6180.618. With H=1H=1 the controller never acts, since the only cost it can see is the control's own. On the cart it is worse: a force moves the position only two steps later, so a plan of two steps or fewer sees no benefit in moving a cart at rest. For linear dynamics and quadratic cost, MPC with cH=0c_H=0 is simply the first gain of an HH-step Riccati recursion, a fixed linear feedback that approaches LQR as HH grows.

Robustness. Every plan starts from a measured state, so whatever the model got wrong shows up in the next measurement and is taken into account by the next plan.

Planning by sampling: random shooting and CEM

For nonlinear or learned models the HH-step problem is solved numerically. Shooting methods treat the control sequence as the only unknown and obtain the states by simulating the model. Gradient-based shooting differentiates the simulated cost; the Fixed Point lesson derives the backward passes of iLQR and DDP. Sampling-based shooting needs only the ability to simulate. Random shooting samples NN control sequences at random, simulates each, and executes the first control of the cheapest. The cross-entropy method (CEM) does better by learning where to sample: it draws sequences from a Gaussian, keeps the cheapest few (the elites), refits the Gaussian to them, and repeats.

python
import numpy as np

def cem_plan(model, cost, x0, mu, sigma0=1.0, n=64, n_elite=8, iters=5, rng=None):
    """Plan H controls from state x0. model(x, u) -> next state; cost(x, u) -> float; mu: (H, m)."""
    rng = rng or np.random.default_rng()
    sigma = np.full(mu.shape, sigma0)
    for _ in range(iters):
        U = mu + sigma * rng.standard_normal((n, *mu.shape))   # n candidate plans
        U[0] = mu                                              # always keep the current mean
        J = np.zeros(n)
        for i in range(n):                                     # simulate every plan in the model
            x = x0
            for t in range(mu.shape[0]):
                J[i] += cost(x, U[i, t])
                x = model(x, U[i, t])
        elite = U[np.argsort(J)[:n_elite]]                     # the cheapest plans
        mu, sigma = elite.mean(axis=0), elite.std(axis=0) + 1e-3
    return mu   # apply mu[0]; at the next step, warm-start with mu shifted by one

A minimal CEM planner. The widget's CEM uses the same sizes, 5 rounds of 64 plans with 8 elites (320 model rollouts per real step), warm-started from the previous plan, with forces limited to a fixed range and the spread kept above a floor; without a floor the spread can collapse before the plan is good.

Check your understanding

Why does random shooting with a fixed budget of 1,000 plans get worse on the cart as the horizon grows from 10 to 60, even though its model is exact?

  1. The model's predictions compound errors over long horizons
  2. Longer horizons make the planner more myopic
  3. The planning problem stops being convex at long horizons
  4. A plan is a point in an HH-dimensional space, and a fixed number of random points covers a 60-dimensional space far more thinly than a 10-dimensional one
Show the answer

D. A plan is a point in an HH-dimensional space, and a fixed number of random points covers a 60-dimensional space far more thinly than a 10-dimensional one

If each of the HH controls must land within a fraction δ\delta of its range around the best value, a uniform random plan succeeds with probability of roughly δH\delta^H: 10−1010^{-10} for δ=0.1\delta=0.1 and H=10H=10, and far less for H=60H=60. CEM escapes by moving its sampling distribution toward good plans, round by round.

MPC in practice, and the Fixed Point lessons

MPC's main practical advantage over a fixed feedback law is that constraints enter the plan directly: actuator limits, safety margins, temperatures that must stay in range. With a linear model and quadratic cost, each step solves a convex quadratic program. That is why MPC, which grew up in refineries and chemical plants from the late 1970s, became the standard advanced control method of the process industries (Qin & Badgwell, 2003). Legged robots use it: the MIT Cheetah 3 ran dynamic gaits with convex MPC on a simplified model (Di Carlo et al., 2018). So do vehicles: sampling-based MPPI drove a scale car aggressively around a dirt track (Williams et al., 2016). In model-based RL the model is learned: PETS plans with CEM through an ensemble of networks (Uncertainty-Aware Models: PILCO & PETS), and TD-MPC plans in a learned latent space with a learned value at the horizon.

PlannerNeedsStrengthWeakness
LQRLinear model, quadratic costExact; computed once, offlineOnly linear–quadratic problems; no constraints
MPC with an exact solverA tractable (for example convex) HH-step problemConstraints; feedback from every measurementAn optimization at every step; myopic without a terminal cost
iLQR, DDPDerivatives of the model and costFast local convergenceLocal minima; needs smooth dynamics
CEM, MPPIOnly the ability to simulateDerivative-free; parallelSamples needed grow with H⋅mH\cdot m
Random shootingOnly the ability to simulateTrivial to implementFails at long horizons

Key takeaways

  • Control is RL with costs, continuous states and usually known models: the cost-to-go satisfies the same dynamic-programming recursion as the value function.
  • For linear dynamics and quadratic cost the cost-to-go stays quadratic; the Riccati recursion computes it backward, and the optimal policy is linear feedback u=−Ktx\mathbf u=-K_t\mathbf x, computed in advance. For xt+1=xt+utx_{t+1}=x_t+u_t with unit costs the gain tends to 1/φ≈0.6181/\varphi\approx0.618.
  • MPC re-solves an HH-step problem from every measured state and applies only the first control. Replanning turns a model error into a slower correction instead of a permanent offset, but without a terminal cost short horizons are myopic: on the cart, H≤2H\le2 never moves it.
  • Sampling planners need only a simulator. Random shooting degrades as HH grows because plans live in an H⋅mH\cdot m-dimensional space, while CEM refits its sampling distribution to elite plans and stays near the exact optimum.
  • MPC's practical strength is constraints, which is why it runs refineries and legged robots; with learned models it powers agents such as PETS and TD-MPC.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What form does the optimal controller of a finite-horizon LQR problem take?

  1. A nonlinear function of the state that must be optimized online
  2. A fixed control sequence chosen from the initial state
  3. Linear state feedback ut=−Ktxt\mathbf u_t=-K_t\mathbf x_t, with gains computed backward in advance and independent of the initial state
  4. Bang-bang control at the force limits
Show the answer

C. Linear state feedback ut=−Ktxt\mathbf u_t=-K_t\mathbf x_t, with gains computed backward in advance and independent of the initial state

Dynamic programming keeps the cost-to-go quadratic, and minimizing a quadratic in u\mathbf u gives a linear function of x\mathbf x. The Riccati recursion computes every KtK_t offline; linearity is a theorem, not an assumption.

Question 2

MPC with horizon H=1H=1 and zero terminal cost controls xt+1=xt+utx_{t+1}=x_t+u_t with cost x2+u2x^2+u^2. What does it do?

  1. Applies u=0u=0 forever: in a one-step problem a control can only add cost
  2. Applies the LQR gain 0.618
  3. Applies u=−xu=-x and reaches the target in one step
  4. Oscillates around the target
Show the answer

A. Applies u=0u=0 forever: in a one-step problem a control can only add cost

The one-step problem minimizes x02+u02x_0^2+u_0^2; x0x_0 is given and the next state's cost is not counted, so u0=0u_0=0. Each extra step of horizon raises the gain: 12\tfrac12 for H=2H=2, 35\tfrac35 for H=3H=3, toward 0.6180.618.

Question 3

A model believes control is twice as effective as it really is (b^=2b\hat b=2b). Starting from x0=1x_0=1, compare executing its one-step plan open loop with replanning it every step.

  1. Both reach the target; open loop is faster
  2. Open loop stops halfway and stays there; replanning halves the error every step and converges
  3. Both diverge
  4. Replanning overshoots and oscillates forever
Show the answer

B. Open loop stops halfway and stays there; replanning halves the error every step and converges

The plan u0=−x0/b^u_0=-x_0/\hat b achieves only half the intended correction. Open loop, nothing corrects that: the system rests at 12\tfrac12. Replanned, each step measures the remaining error and repeats the half correction, so xt=2−tx_t=2^{-t}. Feedback turns a model error into a slower convergence instead of a permanent offset.

Question 4

What does the cross-entropy method do that random shooting does not?

  1. It uses gradients of the model
  2. It plans over a longer horizon
  3. It needs no model
  4. It refits its sampling distribution to the best plans and samples again, concentrating the search where good plans are
Show the answer

D. It refits its sampling distribution to the best plans and samples again, concentrating the search where good plans are

Both methods only simulate candidate plans. Random shooting samples once, uniformly; CEM refits a Gaussian to the elite plans over several rounds, so later samples land near good plans, which is why it stays close to the exact optimum where random shooting fails.

Question 5

A reactor's temperature must stay within strict limits, and its model is nonlinear. Why do engineers use MPC rather than a fixed LQR gain?

  1. MPC can enforce the limits inside every plan and re-optimize as conditions change, while a fixed gain handles neither constraints nor nonlinearity
  2. MPC needs no model
  3. LQR cannot be computed for chemical processes
  4. MPC needs less computation
Show the answer

A. MPC can enforce the limits inside every plan and re-optimize as conditions change, while a fixed gain handles neither constraints nor nonlinearity

Constraints are MPC's main practical advantage: they enter each finite-horizon optimization directly. A fixed gain is optimal only for an unconstrained linear–quadratic problem.

Go deeper

Further reading

  • D. P. Bertsekas, Dynamic Programming and Optimal Control, Vol. I (Athena Scientific, 4th ed., 2017).
  • J. B. Rawlings, D. Q. Mayne & M. M. Diehl, Model Predictive Control: Theory, Computation, and Design (Nob Hill Publishing, 2nd ed., 2017).
  • S. J. Qin & T. A. Badgwell, "A survey of industrial model predictive control technology," Control Engineering Practice 11, 733–764 (2003).
  • P.-T. de Boer, D. P. Kroese, S. Mannor & R. Y. Rubinstein, "A tutorial on the cross-entropy method," Annals of Operations Research 134, 19–67 (2005).