LQR: how does a quadratic cost become a feedback gain?
线性二次调节器
The linear quadratic regulator from a quadratic cost-to-go: Riccati equations in continuous and discrete time, existence conditions, choosing Q and R, finite versus infinite horizon, and local stabilisation of a nonlinear cart-pole, checked on synthetic numpy examples.
lqrChoosing gains by stating what you care about
The linear quadratic regulator (LQR) designs a feedback controller from a statement of what you care about, instead of from hand-tuned gains. You write a cost that adds up squared state errors and squared inputs, and the method returns the gains that minimise it. For example, given a linear model of a pole balanced on a cart, it returns the four gains that keep the pole upright near its balance point.
That example shows why this helps. A pole balanced on a cart has four states: cart position, pole angle and their two velocities. A single force on the cart must keep all four near zero. One could instead place the four closed-loop eigenvalues by hand; these are the numbers that set how fast and how smoothly the controlled system settles. That is possible, but it leaves the main engineering question unanswered: how hard is the motor allowed to push? Åström and Murray motivate LQR this way. Instead of setting eigenvalues, you choose a cost that weighs state errors against input size, and the gains follow from minimising it. Why optimise instead of placing poles
The solution takes a simple form. For linear dynamics and a quadratic cost over an unlimited time horizon, the best possible input at every moment is a fixed linear function of the state, u = −Kx. The gain matrix K comes from a matrix equation named after Riccati. Tedrake calls LQR likely the most important and influential result in optimal control theory so far. His assessment is plausible for a practical reason: the same few lines of linear algebra stabilise an acrobot, a cart-pole or a quadrotor near an equilibrium. Chapter introduction
This article derives the gain, states when it exists, shows how the weights shape the response, and tests the design on a nonlinear cart-pole. All examples are original, synthetic numpy computations; no physical hardware or real data are involved. The general theory of optimal control, including the maximum principle and the Hamilton–Jacobi–Bellman (HJB) equation used below, is in optimal control.
From a quadratic cost-to-go to the Riccati equation
This section derives the LQR gain, states when it exists, shows how the weights shape it and extends it to nonlinear systems near an equilibrium.
The problem. The plant is linear, ẋ = Ax + Bu, with state x ∈ ℝⁿ and input u ∈ ℝᵐ. The cost penalises the state with a weight Q, the input with a weight R, and the final state with a weight Q_f: Cost (7.29)
In words, J adds up weighted squared state errors and weighted squared inputs over time, plus a weighted squared final state. All three weights are symmetric; ⪰ means positive semidefinite and ≻ positive definite. The sources disagree on notation: Åström and Murray write Qₓ, Qᵤ and Q_f, Murray’s optimisation-based control notes add a factor ½ and call the terminal weight P₁, and Tedrake writes Q, R and Q_f. This article uses Tedrake’s letters without the ½ throughout; the factor only rescales S and does not change K.
Guess a quadratic cost-to-go. Tedrake’s derivation starts from the infinite-horizon HJB equation and guesses that the optimal cost-to-go is quadratic, J*(x) = xᵀSx with S symmetric positive semidefinite. Its gradient is 2xᵀS, so HJB reads Basic derivation
Because R ≻ 0, the bracket is a convex quadratic in u, and setting its gradient 2Ru + 2BᵀSx to zero gives the minimiser on the right. It is linear in x: that is the whole reason LQR yields a constant gain matrix. Substituting u* back and symmetrising the term 2xᵀSAx as xᵀ(AᵀS + SA)x leaves a quadratic form in x that must vanish for every x, so its matrix must be zero. That is the algebraic Riccati equation (ARE):
Here S is the matrix of the quadratic cost-to-go, so x₀ᵀSx₀ is the optimal cost from the initial state x₀. The equation is quadratic in S, so it can have several solutions; the one wanted is the positive-definite one. Murray reaches the same equations through the maximum principle by looking for a costate that is linear in the state, λ = Px. Maximum-principle derivation Tedrake reads the gain geometrically: −Sx is the steepest-descent direction of the cost-to-go, −BᵀSx is its projection onto the directions the inputs can actually push, and R⁻¹ re-weights those directions by how expensive each input is. Interpretation
Finite horizon. Over a finite interval the cost-to-go depends on time, J*(x, t) = xᵀS(t)x, and the same steps give a Riccati differential equation integrated backwards from the terminal weight: Equations (7.30)–(7.32)
In words, S(t) is computed backwards from the final weight Q_f, and the gain at each time uses the current S(t). The optimal cost from x(0) is x(0)ᵀS(0)x(0). Nothing in this derivation needs A, B, Q or R to be constant; with time-varying matrices the same equations give time-varying LQR. Time-varying matrices Tedrake adds two practical points. For stabilizable systems the backward Riccati solution converges to the infinite-horizon S as the horizon grows. And numerically integrating the Riccati equation can lose symmetry or positive definiteness on weakly stabilizable systems; integrating a square-root factor S = PPᵀ avoids that. Finite-horizon LQR
Discrete time. For x[n+1] = Ax[n] + Bu[n] with stage cost xᵀQx + uᵀRu, the cost-to-go from step n is xᵀSₙx and the recursion runs backwards from S_N = Q_f. Tedrake writes the gain with the cost-to-go matrix of the same step index; with his backward recursion, the gain applied at step n uses the cost-to-go of step n + 1, and we index it that way: Discrete-time Riccati equations
In words, the gain for step n uses the cost-to-go matrix of step n + 1, and that matrix is then updated one step further back. The infinite-horizon solution is the positive-definite fixed point of this recursion, the discrete algebraic Riccati equation (DARE). Running the recursion is value iteration with a value function restricted to quadratics. Tedrake shows that the non-positive-definite solutions of the Riccati equation also have zero Bellman residual but give unstable controllers, and only the positive-definite one is a stable fixed point of that iteration. LQR via fitted value iteration The discounted form popular in reinforcement learning, with factor γ, can be solved as an ordinary DARE using √γ·A and R/γ. Discounted LQR Åström and Murray’s discrete-time example, a web server model, shows that nothing here is specific to mechanics. Example 7.10
When does a solution exist? The three sources state the conditions differently, and the differences matter.
- Åström and Murray assume Q ≻ 0 and state that if the system is reachable, the ARE has a unique positive-definite solution that makes the closed loop stable; they also mention conditions on Q of an observability type. Existence in Feedback Systems
- Tedrake states that the ARE has a single positive-definite solution if and only if the system is stabilizable, so unstable modes that the input cannot affect are the obstruction, not stable ones. Stabilizability
- Murray requires R ≻ 0, because R⁻¹ appears, and treats a semidefinite state weight written as Q = HᵀH. His text calls detectability of (A, H) a technical condition for the optimum to exist (observability implies it); his Theorem 3.2 states the result assuming (A, B) reachable and (A, H) observable. Otherwise some nonzero initial states may incur zero cost, and he calls the problem ill-conditioned. Detectability, Theorem 3.2
The usual working summary is therefore: R ≻ 0, (A, B) stabilizable, and (A, H) detectable for Q = HᵀH. When Q ≻ 0, Murray adds a simple stability argument: a finite cost forces the state to converge to zero, so the infinite-horizon law is stabilising. Finite cost implies convergence
Choosing Q and R. Both books recommend starting with diagonal weights, each entry saying how much that squared state or input should count; states that must stay small get larger weights, and an actuator to be spared gets a larger input weight. Diagonal weights Murray reports Bryson and Ho’s rule of thumb: set each weight to the inverse square of the largest acceptable value of that state or input, then adjust by trial for response time, damping and effort. Bryson’s rule With R = ρI, the scalar ρ trades state error against input energy; Åström and Murray’s vectored-thrust example compares ρ = 1, 10² and 10⁴ and shows that a larger input weight gives a more sluggish response. Example 7.9
A closed-form case shows how far the weights reach. For the double integrator with Q = I and R = 1, Tedrake gives K = [1, √3] and S with √3 on the diagonal and 1 off it. Double integrator Murray instead penalises only the position, Q = diag(q², 0) with R = 1, and finds K = [q, √(2q)]. The closed loop then has natural frequency √q and damping ratio 1/√2 ≈ 0.707 for every q: the weight sets the speed, while the damping is fixed by the structure of the problem. Example 3.4
Nonlinear systems, locally. LQR also stabilises a nonlinear system ẋ = f(x, u) near an equilibrium (x₀, u₀): linearise, design K for the linear model, and apply the gain to the deviation: Local stabilisation
In words: apply the linear gain to the deviation from the equilibrium, where A and B are the slopes of f at that equilibrium. Tedrake notes that this recipe stabilises acrobots, cart-poles and quadrotors. Acrobots, cart-poles and quadrotors Along a nominal trajectory (x₀(t), u₀(t)), for example one produced by trajectory optimization, the time-varying version gives u = u₀(t) − K(t)(x − x₀(t)); if the trajectory ends at a fixed point, the Riccati equation can be initialised with the infinite-horizon S there. Trajectory stabilisation Åström and Murray discuss the same idea under gain scheduling. Time-varying and scheduled gains
Robustness and output feedback. For exact state feedback, Åström and Murray pose as an exercise the proof of Kalman’s inequality, a matrix inequality for the LQR loop transfer function. For a single-input system it reduces to:
In words, the Nyquist curve of L never comes closer than distance 1 to the point −1, so it stays outside the unit disc centred there. The exercise concludes that the LQR phase margin is always greater than 60°; strictly, the inequality guarantees a phase margin of at least 60°, which is the wording used below. Exercise 10.9 This guarantee is for full-state feedback only. When the state must be estimated from outputs, the linear quadratic Gaussian (LQG) controller applies the LQR gain to a Kalman filter estimate, by the separation principle LQG, and the margin above no longer follows. Integral action can be added by augmenting the state with the integral of the output error, which gives PI-like behaviour on top of the state feedback. Integral action
Four numerical checks
This section tests the theory on four small numerical problems, from closed-form cases to a nonlinear cart-pole. The program uses numpy only, without SciPy, and runs in about one and a half seconds. The continuous ARE is solved through the Hamiltonian matrix
where the columns of the stacked matrix with blocks V₁ (top) and V₂ (bottom) span the eigenvectors of 𝓗 with negative real part. This is a standard numerical method, used here as our own implementation; it is not taken from the sources read. The discrete ARE is obtained by running the Riccati recursion for 500 steps. Part A checks closed forms; Part B sweeps R and simulates with forward Euler (step 10⁻³ s, 20 s); Part C studies the discrete horizon and compares the Riccati policy with a batch least-squares solution; Part D designs LQR for a linearised cart-pole and tests it on the nonlinear model with fourth-order Runge–Kutta (step 5 × 10⁻³ s, 10 s).
The cart-pole model is ours: a point-mass pole of mass 0.1 kg on a massless rod of length 0.5 m, a 1 kg cart, g = 9.81 m/s², no friction, and the angle φ measured from upright. Linearising at φ = 0 gives ẍ = (f + m_p g φ)/m_c and φ̈ = ((m_c + m_p) g φ + f)/(m_c l); this derivation was written for this article, not taken from a source.
# Synthetic, deterministic LQR study (numpy only, no SciPy).
import numpy as np
np.set_printoptions(precision=4, suppress=True)
def care(A, B, Q, R):
"""Continuous algebraic Riccati equation via the stable invariant
subspace of the Hamiltonian matrix."""
n = A.shape[0]
Ri = np.linalg.inv(R)
H = np.block([[A, -B @ Ri @ B.T], [-Q, -A.T]])
w, V = np.linalg.eig(H)
Vs = V[:, w.real < 0]
S = np.real(Vs[n:, :] @ np.linalg.inv(Vs[:n, :]))
S = 0.5 * (S + S.T)
K = Ri @ B.T @ S
return K, S
def care_residual(A, B, Q, R, S):
M = A.T @ S + S @ A - S @ B @ np.linalg.solve(R, B.T) @ S + Q
return np.abs(M).max()
def riccati_step(A, B, Q, R, S):
K = np.linalg.solve(R + B.T @ S @ B, B.T @ S @ A)
S_prev = Q + A.T @ S @ A - A.T @ S @ B @ K
return 0.5 * (S_prev + S_prev.T), K
A = np.array([[0.0, 1.0], [0.0, 0.0]])
B = np.array([[0.0], [1.0]])
print("A. Continuous-time double integrator, Q = I, R = 1")
K, S = care(A, B, np.eye(2), np.eye(1))
print(" K =", K.ravel(), " (analytic [1, sqrt(3)] =", np.array([1, np.sqrt(3)]), ")")
print(" S =", S.ravel(), " residual =", f"{care_residual(A, B, np.eye(2), np.eye(1), S):.1e}")
print(" closed-loop eigenvalues:", np.linalg.eigvals(A - B @ K))
for q in (1.0, 4.0):
Qx = np.diag([q * q, 0.0])
K, S = care(A, B, Qx, np.eye(1))
lam = np.linalg.eigvals(A - B @ K)
wn = abs(lam[0])
zeta = -lam[0].real / wn
print(f" Qx = diag({q*q:g}, 0): K = {K.ravel()}, wn = {wn:.4f}, zeta = {zeta:.4f}")
print()
print("B. Effect of the input weight R (Q = I), x0 = (1, 0), Euler dt = 1e-3, 20 s")
dt = 1e-3
steps = 20000
w = np.logspace(-3, 3, 4001)
for r in (0.01, 1.0, 100.0):
R = np.array([[r]])
K, S = care(A, B, np.eye(2), R)
x = np.array([1.0, 0.0])
peak_u, xcost, ucost, t_in = 0.0, 0.0, 0.0, 0.0
for k in range(steps):
u = -(K @ x)[0]
peak_u = max(peak_u, abs(u))
xcost += (x @ x) * dt
ucost += r * u * u * dt
if abs(x[0]) >= 0.02:
t_in = (k + 1) * dt
x = x + dt * (A @ x + B[:, 0] * u)
ret = min(abs(1 + (K @ np.linalg.solve(1j * wi * np.eye(2) - A, B))[0, 0]) for wi in w)
lam = np.linalg.eigvals(A - B @ K)
print(f" R = {r:>6g}: K = {K.ravel()}, eig = {np.round(lam, 3)}")
print(f" peak|u| = {peak_u:.3f}, |q|<0.02 after {t_in:.2f} s, "
f"state cost {xcost:.3f}, input cost {ucost:.3f}, total {xcost+ucost:.3f}, "
f"x0'Sx0 = {S[0,0]:.3f}, min|1+L(jw)| = {ret:.4f}")
print()
print("C. Discrete time (exact ZOH, h = 0.1), Q = I, R = 1, S[N] = 0")
h = 0.1
Ad = np.array([[1.0, h], [0.0, 1.0]])
Bd = np.array([[h * h / 2], [h]])
Q, R = np.eye(2), np.eye(1)
S = np.zeros((2, 2))
gains = {}
for N in range(1, 501):
S, K = riccati_step(Ad, Bd, Q, R, S)
gains[N] = (K.copy(), S.copy())
S_inf, K_inf = gains[500][1], gains[500][0]
dare = Q + Ad.T @ S_inf @ Ad - Ad.T @ S_inf @ Bd @ np.linalg.solve(R + Bd.T @ S_inf @ Bd, Bd.T @ S_inf @ Ad) - S_inf
print(" K_inf =", K_inf.ravel(), " DARE residual =", f"{np.abs(dare).max():.1e}",
" spectral radius(A-BK) =", f"{max(abs(np.linalg.eigvals(Ad - Bd @ K_inf))):.4f}")
for N in (1, 2, 5, 10, 20, 50, 100):
K0 = gains[N][0]
print(f" horizon N = {N:>3}: first-step gain K0 = {K0.ravel()}, "
f"|K0 - K_inf| = {np.abs(K0 - K_inf).max():.2e}")
N = 20
x0 = np.array([1.0, 0.0])
G = np.zeros((2 * N, N))
F = np.zeros((2 * N, 2))
Ap = np.eye(2)
for i in range(N):
Ap = Ad @ Ap
F[2 * i:2 * i + 2] = Ap
for j in range(i + 1):
G[2 * i:2 * i + 2, j] = (np.linalg.matrix_power(Ad, i - j) @ Bd)[:, 0]
Gm, Fm = G[:-2], F[:-2]
H_ls = Gm.T @ Gm + np.eye(N)
u_ls = -np.linalg.solve(H_ls, Gm.T @ Fm @ x0)
xs = Fm @ x0 + Gm @ u_ls
J_ls = x0 @ x0 + xs @ xs + u_ls @ u_ls
x = x0.copy()
J_dp = 0.0
u_dp = []
for k in range(N):
Kk = gains[N - k][0]
u = -(Kk @ x)[0]
u_dp.append(u)
J_dp += x @ x + u * u
x = Ad @ x + Bd[:, 0] * u
print(f" N = 20 from x0 = (1, 0): batch least squares J = {J_ls:.6f}, "
f"Riccati policy J = {J_dp:.6f}, x0'S0x0 = {x0 @ gains[N][1] @ x0:.6f}, "
f"max|u diff| = {np.abs(np.array(u_dp) - u_ls).max():.1e}")
print()
print("D. Cart-pole linearised about upright (mc = 1, mp = 0.1, l = 0.5, g = 9.81)")
mc, mp, l, g = 1.0, 0.1, 0.5, 9.81
Ac = np.array([[0, 0, 1, 0], [0, 0, 0, 1],
[0, mp * g / mc, 0, 0], [0, (mc + mp) * g / (mc * l), 0, 0]])
Bc = np.array([[0], [0], [1 / mc], [1 / (mc * l)]])
print(" open-loop eigenvalues:", np.sort(np.linalg.eigvals(Ac).real))
Qc = np.diag([1.0, 10.0, 1.0, 1.0])
Kc, Sc = care(Ac, Bc, Qc, np.eye(1))
print(" K =", Kc.ravel(), " closed-loop eig real parts:",
np.sort(np.linalg.eigvals(Ac - Bc @ Kc).real))
def cartpole_f(s, f):
x, phi, xd, phid = s
th = np.pi + phi
M = np.array([[mc + mp, mp * l * np.cos(th)], [mp * l * np.cos(th), mp * l * l]])
rhs = np.array([f + mp * l * phid ** 2 * np.sin(th), -mp * g * l * np.sin(th)])
xdd, thdd = np.linalg.solve(M, rhs)
return np.array([xd, phid, xdd, thdd])
def run(phi0, fmax):
s = np.array([0.0, phi0, 0.0, 0.0])
dt = 5e-3
for _ in range(int(10 / dt)):
f = float(np.clip(-(Kc @ s)[0], -fmax, fmax))
k1 = cartpole_f(s, f)
k2 = cartpole_f(s + 0.5 * dt * k1, f)
k3 = cartpole_f(s + 0.5 * dt * k2, f)
k4 = cartpole_f(s + dt * k3, f)
s = s + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
if abs(s[1]) > np.pi / 2:
return False, s
return abs(s[1]) < 1e-3 and abs(s[0]) < 1e-2, s
for fmax in (np.inf, 10.0):
ok = [round(p, 1) for p in np.arange(0.1, 1.51, 0.1) if run(p, fmax)[0]]
print(f" nonlinear sim, |f| <= {fmax:g} N: initial angles recovered (of 0.1..1.5 rad): {ok}")
Recorded output
A. Continuous-time double integrator, Q = I, R = 1
K = [1. 1.7321] (analytic [1, sqrt(3)] = [1. 1.7321] )
S = [1.7321 1. 1. 1.7321] residual = 1.3e-15
closed-loop eigenvalues: [-0.866+0.5j -0.866-0.5j]
Qx = diag(1, 0): K = [1. 1.4142], wn = 1.0000, zeta = 0.7071
Qx = diag(16, 0): K = [4. 2.8284], wn = 2.0000, zeta = 0.7071
B. Effect of the input weight R (Q = I), x0 = (1, 0), Euler dt = 1e-3, 20 s
R = 0.01: K = [10. 10.9545], eig = [-1.005 -9.949]
peak|u| = 10.000, |q|<0.02 after 4.00 s, state cost 1.051, input cost 0.046, total 1.096, x0'Sx0 = 1.095, min|1+L(jw)| = 1.0000
R = 1: K = [1. 1.7321], eig = [-0.866+0.5j -0.866-0.5j]
peak|u| = 1.000, |q|<0.02 after 4.34 s, state cost 1.444, input cost 0.289, total 1.733, x0'Sx0 = 1.732, min|1+L(jw)| = 1.0000
R = 100: K = [0.1 0.4583], eig = [-0.229+0.218j -0.229-0.218j]
peak|u| = 0.100, |q|<0.02 after 18.67 s, state cost 3.492, input cost 1.091, total 4.583, x0'Sx0 = 4.583, min|1+L(jw)| = 1.0000
C. Discrete time (exact ZOH, h = 0.1), Q = I, R = 1, S[N] = 0
K_inf = [0.9171 1.6356] DARE residual = 0.0e+00 spectral radius(A-BK) = 0.9171
horizon N = 1: first-step gain K0 = [0. 0.], |K0 - K_inf| = 1.64e+00
horizon N = 2: first-step gain K0 = [0.005 0.0995], |K0 - K_inf| = 1.54e+00
horizon N = 5: first-step gain K0 = [0.0752 0.3945], |K0 - K_inf| = 1.24e+00
horizon N = 10: first-step gain K0 = [0.3159 0.8547], |K0 - K_inf| = 7.81e-01
horizon N = 20: first-step gain K0 = [0.7471 1.4324], |K0 - K_inf| = 2.03e-01
horizon N = 50: first-step gain K0 = [0.916 1.6343], |K0 - K_inf| = 1.26e-03
horizon N = 100: first-step gain K0 = [0.9171 1.6356], |K0 - K_inf| = 2.19e-07
N = 20 from x0 = (1, 0): batch least squares J = 15.717001, Riccati policy J = 15.717001, x0'S0x0 = 15.717001, max|u diff| = 2.8e-16
D. Cart-pole linearised about upright (mc = 1, mp = 0.1, l = 0.5, g = 9.81)
open-loop eigenvalues: [-4.6456 0. 0. 4.6456]
K = [-1. 30.615 -2.2453 6.7231] closed-loop eig real parts: [-5.5636 -4.0555 -0.7909 -0.7909]
nonlinear sim, |f| <= inf N: initial angles recovered (of 0.1..1.5 rad): [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1]
nonlinear sim, |f| <= 10 N: initial angles recovered (of 0.1..1.5 rad): [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]A: closed forms. The solver returns K = [1, 1.7321] and S with 1.7321 on the diagonal and 1 off it, matching [1, √3]. The ARE residual is 1.3e-15 and the closed-loop eigenvalues are −0.866 ± 0.5j. With Murray’s position-only weight, q = 1 gives K = [1, 1.4142] with ωₙ = 1 and ζ = 0.7071, and q = 4, that is Q = diag(16, 0), gives K = [4, 2.8284] with ωₙ = 2 and the same ζ = 0.7071.
B: what R buys. From x₀ = (1, 0) with Q = I:
| R | K | closed-loop eigenvalues | peak abs(u) | abs(q) below 0.02 after | state cost | input cost | total (x₀ᵀSx₀) |
|---|---|---|---|---|---|---|---|
| 0.01 | [10, 10.9545] | −1.005, −9.949 | 10.000 | 4.00 s | 1.051 | 0.046 | 1.096 (1.095) |
| 1 | [1, 1.7321] | −0.866 ± 0.5j | 1.000 | 4.34 s | 1.444 | 0.289 | 1.733 (1.732) |
| 100 | [0.1, 0.4583] | −0.229 ± 0.218j | 0.100 | 18.67 s | 3.492 | 1.091 | 4.583 (4.583) |
A cheaper input gives larger gains and a larger peak input. The speed-up, though, is lopsided: going from R = 1 to 0.01 multiplies the peak input by ten but shortens the time to stay within |q| below 0.02 only from 4.34 s to 4.00 s, because one closed-loop eigenvalue stays near −1. With Q = I the position error costs only one unit, and the optimum does not pay for a faster slow mode. Raising R to 100 slows the response to 18.67 s. In every case the simulated total cost matches x₀ᵀSx₀ to within Euler error, which confirms that S is the cost-to-go matrix. The minimum of |1 + L(iω)| over ω from 10⁻³ to 10³ prints as 1.0000 in all three cases: Kalman’s inequality holds, and its bound is approached at high frequency, so 1.0000 is the expected value rather than a violation.
C: horizon and recursion. With exact zero-order-hold discretisation at h = 0.1 s, Q = I, R = 1 and no terminal cost (S_N = 0), the recursion converges to K_∞ = [0.9171, 1.6356] with DARE residual 0.0e+00. The spectral radius of A − BK_∞ is 0.9171. The closed-loop eigenvalues form a complex pair whose squared modulus is the determinant, 1 − h k₂ + h² k₁/2 = 0.8410 (our own algebra). That the spectral radius equals the first entry of K_∞ is not a one-off: in extra runs made for this article’s check, the equality also held at h = 0.2 and 0.5 with Q = I and R = 1, but not with other weights. We have not derived why, so treat it as an observation. The first-step gain depends strongly on the horizon. With N = 1 it is [0, 0], since the last input has no future cost to reduce. It is [0.005, 0.0995] for N = 2, [0.0752, 0.3945] for N = 5, [0.3159, 0.8547] for N = 10 and [0.7471, 1.4324] for N = 20, still 2.03e-01 away from K_∞; the error falls to 1.26e-03 at N = 50 and 2.19e-07 at N = 100. For N = 20 from (1, 0), optimising all 20 inputs at once by least squares gives J = 15.717001, identical to the cost of the time-varying Riccati policy and to x₀ᵀS₀x₀; the two input sequences differ by at most 2.8e-16. Tedrake notes that finite-horizon discrete LQR can be written as such a least-squares problem, while solving the Riccati equation remains the preferred method for the basic problem. Least-squares formulation
D: a local design on a nonlinear plant. The linearised cart-pole has open-loop eigenvalues −4.6456, 0, 0 and +4.6456, so upright is unstable. With Q = diag(1, 10, 1, 1) and R = 1 the gain is K = [−1, 30.615, −2.2453, 6.7231], and the closed-loop real parts are −5.5636, −4.0555, −0.7909 and −0.7909. On the nonlinear model, starting at rest with initial angles from 0.1 to 1.5 rad in steps of 0.1, success means |φ| below 10⁻³ rad and |x| below 0.01 m after 10 s, and failure means |φ| exceeds π/2. With unlimited force the controller recovers every angle from 0.1 to 1.1 rad and fails at 1.2. With the force clipped to |f| ≤ 10 N it recovers only 0.1 to 0.7 rad. The linear design is identical in both cases; the actuator limit, which the LQR cost knows nothing about, shrinks the set of states from which it works.
Where LQR stops
This section lists what LQR cannot do and what the checks above do not show. LQR has no constraints. Input saturation and state limits are outside the cost, as Part D shows. With inequality constraints there is generally no closed-form policy; Tedrake points to solving a finite-horizon convex problem from the current state at every step, which is model predictive control. Constrained LQR
The guarantee is local for nonlinear plants. The region from which the controller recovers depends on the model, the weights, the limits and the initial velocity. The numbers in Part D cover one toy model on a 0.1 rad grid with zero initial velocity; they are not a region-of-attraction estimate.
LQR needs the full state and a model. With only outputs, an estimator must be added, and the 60° margin argument for exact state feedback does not transfer to the combined controller. Model errors in A and B change the closed loop that is actually achieved.
The existence conditions have to be checked, not assumed. A reachable system with a semidefinite Q can still fail if an unstable mode is invisible to the cost, as in Exercise 3. The weights are a design choice: the optimum is optimal for the stated Q and R, and Part B shows that a cost-optimal design can still be slower than a designer expects. The cart-pole linearisation, the Hamiltonian-matrix solver and the counterexample in Exercise 3 are our own work; Kalman’s 1960 paper is mentioned only as reported by Åström and Murray.
Exercises
The five exercises test understanding, a hand calculation, counterexamples and two design judgements; each answer explains its reasoning.
-
Why does LQR produce a linear feedback law, and what does the matrix S mean?
Answer: With linear dynamics and quadratic cost the cost-to-go is quadratic, J* = xᵀSx. Inside the HJB equation the expression to minimise is a convex quadratic in u, whose minimiser u = −R⁻¹BᵀSx is linear in x. S is the cost-to-go matrix: x₀ᵀSx₀ is the smallest achievable cost from x₀. In Part B, x₀ᵀSx₀ = 1.732 for R = 1, and the simulated cost of the policy is 1.733.
-
For the double integrator with Q = diag(q², 0) and R = 1, write S with entries a, b on the first row and b, c on the second, solve the ARE, and find K, ωₙ and ζ for q = 4.
Answer: The three distinct entries of the ARE give q² − b² = 0, a − bc = 0 and 2b − c² = 0, so b = q, c = √(2q) and a = q√(2q). Then K = BᵀS = [b, c] = [q, √(2q)] = [4, 2.8284]. The closed-loop polynomial is s² + √(2q)s + q, so ωₙ = √q = 2 and ζ = √(2q)/(2√q) = 1/√2 = 0.7071, as in Part A.
-
Give cases where “solve the ARE and apply u = −Kx” fails. (The second example below was constructed for this article.)
Answer: (i) The system is not stabilizable, for example ẋ₁ = x₁, ẋ₂ = u: the unstable mode x₁ cannot be influenced, and no stabilising positive-definite solution exists. Tedrake’s Segway example is not stabilizable in its full coordinates for a related reason. (ii) Q is semidefinite and misses an unstable mode: ẋ₁ = x₁ + u, ẋ₂ = −x₂ + u with Q = diag(0, 1). The pair (A, B) is reachable, yet from any state with x₂ = 0 the input u ≡ 0 costs nothing and is therefore “optimal”, while x₁ grows like eᵗ. Detectability of (A, H) fails, which is exactly Murray’s condition. A solver that returns the stabilising ARE solution, such as the Hamiltonian-matrix method in the program, still gives a stable gain here, but then x₀ᵀSx₀ is not the minimum cost: from such states the minimum is zero, reached only by letting x₁ diverge. (iii) On the real nonlinear plant the guarantee is only local: in Part D the 10 N limit loses the pole from 0.8 rad although the linear design is unchanged.
-
A colleague lowers R from 1 to 0.01 “to make the response 100 times faster”. Judge this with Part B.
Answer: Gains and peak input grow tenfold (peak |u| from 1 to 10), but the time to stay within |q| below 0.02 only falls from 4.34 s to 4.00 s, because the slow eigenvalue stays near −1; it is held there by the state weight. Speed depends on Q as well as R, and on real hardware the tenfold input would likely hit actuator limits. This is one synthetic plant; the conclusion should be checked on the real system.
-
One task runs for exactly 20 sampling steps; another holds a hover indefinitely. Which gains should each use?
Answer: Part C shows that the first-step finite-horizon gain at N = 20 is still well below K_∞ ([0.7471, 1.4324] against [0.9171, 1.6356], a largest difference of 0.203), and with S_N = 0 the gains drop to zero at the end of the horizon. For the indefinite hover, use the constant K_∞ from the DARE. For the task that ends, use the time-varying Kₙ from the backward recursion, or set S_N = S_∞ to remove end effects, as Tedrake does for trajectories that end at a fixed point. If inputs must respect hard limits, neither gain is enough, and model predictive control is the appropriate tool.
History and further reading
This section gives the history as the cited books report it and points to further reading. Åström and Murray report that Kalman’s 1960 paper “Contributions to the theory of optimal control” obtained the state feedback gain by minimising a quadratic loss. Kalman’s paper as reported That paper was not read for this article. Murray reports Bryson and Ho’s weighting rule; their book was not read either.
Åström and Murray’s section 7.5 is a compact introduction with the vectored-thrust and web-server examples, and their chapter 8 connects LQR to estimation and LQG. Feedback Systems Murray’s chapter 3 derives LQR from the maximum principle and gives the detectability conditions and weight-selection advice. Optimization-Based Control, chapter 3 Tedrake’s chapter covers the HJB derivation, finite-horizon and time-varying LQR, tracking, discrete time, the link to fitted value iteration and constrained variants. Underactuated Robotics, chapter 8 Background is in positive definite matrices, eigenvalues, Bellman equations and value iteration. For a model-free alternative see PID control; for the robot models that LQR is applied to see robot dynamics. Related topics are optimal control, model predictive control, trajectory optimization, Kalman filter and state estimation.
Make a prediction, then check
Double integrator ẍ = u with Q = I. If the input weight R is lowered from 1 to 0.01, which statement agrees with LQR theory and the article's example?
Learning objectives
- Derive the LQR gain K = R⁻¹BᵀS and the Riccati equation from a quadratic cost-to-go, and distinguish finite horizon (time-varying gains, backward recursion) from infinite horizon (algebraic Riccati equation, constant gain) together with the existence conditions.
- Explain how the Q and R weights trade response speed against control effort, apply LQR to stabilise a nonlinear system at an equilibrium or along a trajectory via linearisation, and state its limits: local validity, no constraints, full-state need.
Prerequisites & connections
Explore related knowledge →References
- Feedback Systems: An Introduction for Scientists and Engineers, 2nd ed. (electronic v3.1.5) — scoped
Karl Johan Åström; Richard M. Murray · 2020 - Underactuated Robotics, Ch. 8: Linear Quadratic Regulators (2024 working notes, Wayback snapshot 2026-05-14) — scoped
Russ Tedrake · 2024 - Optimization-Based Control, Chapter 3: Optimal Control (v2.3d, 14 Jan 2023) — scoped
Richard M. Murray · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Claude · 2026-12-03 · Independent AI check (Claude subagent, not the author; not a human or expert review). Before this check the main session applied style-only edits suggested by the Gemini app to the opening section, logged in gemini-edits-016a.json; research was done by a separate research subagent (facts.md) and the prose by a writer subagent. All four en and four zh Gemini edits for this topic were compared with their old text; none changed a fact or attribution, but the zh '这是他的个人评价,但确实够实用' asserted more than the en 'plausible for a practical reason' and was realigned, and the zh gloss on eigenvalues was given an en counterpart. I then made readability (D012) edits to the intuition section and section openings in both languages and did the factual check on the edited text. I ran example.py with the pinned numpy 1.26.4 interpreter and diffed it with example.stdout.txt (identical), confirmed the python and output blocks are byte-identical to the files in both languages and the eight display equations match, and matched every number in the prose, table and exercises. I re-derived the ARE from the HJB guess, Example 3.4 (b = q, c = √(2q), a = q√(2q), ζ = 1/√2), the discrete closed-loop determinant 1 − hk₂ + h²k₁/2, the cart-pole linearisation (checked against a numerical Jacobian of the code's nonlinear model: ±4.6456), the discounted-DARE substitution, and phase margins of the three Part B designs (85°, 72°, 66°). I also ran extra checks showing that ρ(A − BK∞) = K∞[0] holds for Q = I, R = 1 at h = 0.2 and 0.5 (so not a coincidence) and that the undetectable-mode example has a stabilising ARE solution whose cost is not the true minimum of zero. I downloaded the sources myself and read them as extracted text: Feedback Systems 2e v3.1.5 §7.5 pp. 7-28–7-32 with Examples 7.9–7.10, §7.6 p. 7-33 and [Kal60], the LQG paragraph at the end of §8.4 p. 8-22 (whose gain typo K = SBQu⁻¹ is not repeated), §8.5 gain scheduling, and Exercise 10.9 pp. 10-29–10-30 (which says the LQR phase margin is 'always greater than 60°'); Tedrake's Underactuated Robotics ch. 8 from the 2026-05-14 Wayback snapshot (introduction, basic derivation, double integrator, local stabilisation, finite-horizon and time-varying LQR, trajectory stabilisation, discrete-time Riccati equations including the S[n] index, discounted LQR, fitted value iteration, constraints, Segway, least squares); and Murray's Optimization-Based Control ch. 3 v2.3d §3.5–3.7 including Theorem 3.2 and Example 3.4. Kalman 1960 and Bryson–Ho are second-hand only; Tedrake's notebooks and the cited papers were not read. Catalogue IDs, anchors, source IDs and the quiz answer were checked, and both files compile as MDX.
- Example re-run with the pinned interpreter matches; the table, K, S, eigenvalues, 15.717001 and the recovered angles 0.1–1.1 and 0.1–0.7 rad agree with the output.
- The three sources' existence conditions are kept separate: Feedback Systems (Q ≻ 0, reachable), Tedrake (iff stabilizable), Murray (detectability in the text, reachability and observability in Theorem 3.2).
- Phase margin: Exercise 10.9 says 'always greater than 60°'; the article now reports this and notes that the inequality strictly guarantees at least 60°, for exact state feedback only.
- The discrete gain is indexed with S_{n+1} and Tedrake's different printed index is noted; Feedback Systems' LQG gain typo is not repeated.
- The cart-pole linearisation, the Hamiltonian-matrix solver and the undetectable-mode counterexample are labelled as the article's own; Kalman 1960 is reported only via Feedback Systems.
Source locations checked:
- Feedback Systems: An Introduction for Scientists and Engineers, 2nd ed. (electronic v3.1.5) — scoped · pdftotext of fbs-public_24Jul2020.pdf (v3.1.5). Checked: §7.5 pp. 7-28–7-29 (motivation vs eigenvalue placement; eq. 7.29 cost with Qx ⪰ 0, Qu ≻ 0, Qf ⪰ 0; eq. 7.30 u = −Kx, K = Qu⁻¹BᵀS; eq. 7.31 Riccati ODE backwards from S(tf) = Qf; eq. 7.32 optimal cost x(0)ᵀS(0)x(0); time-varying matrices allowed; eq. 7.33 ARE; reachable ⇒ unique PD stabilising solution; MATLAB lqr; Qx ≻ 0 assumption and 'observability' conditions; diagonal weights); Example 7.9 pp. 7-29–7-30 and Fig. 7.13 (ρ = 1, 10², 10⁴, larger ρ more sluggish); Example 7.10 pp. 7-30–7-32 (discrete-time dlqr web server, K values skimmed); §7.6 p. 7-33 (Kalman [Kal60] quadratic loss; reachability/observability due to Kalman); Exercise 7.17 (pp. 7-35–7-36, completing-the-square proof outline); ch. 8 epigraph p. 8-1 (Kalman 1960 quote, not used); LQG paragraph at the end of §8.4, p. 8-22 (separation principle; note typo K = SBQu⁻¹), and §8.5 gain-scheduled/time-varying LQR pp. 8-27–8-28; Exercise 10.9 pp. 10-29–10-30 (Kalman's inequality, |1+L(iω)| ≥ 1, phase margin > 60°). NOT read: §7.1–7.4 beyond the last paragraph of 7.4, rest of ch. 8 and ch. 10, Kalman's paper itself.
- Underactuated Robotics, Ch. 8: Linear Quadratic Regulators (2024 working notes, Wayback snapshot 2026-05-14) — scoped · HTML of https://underactuated.mit.edu/lqr.html; cited version = Wayback snapshot 20260514185650 (before cutoff); live page fetched 2026-12-03 differs only in script tags. Checked sections: chapter intro ('likely the most important…' opinion); Basic Derivation (HJB with J* = xᵀSx, u* = −R⁻¹BᵀSx, ARE, PD solution iff stabilizable, steepest-descent interpretation); LQR for the Double Integrator (K = [1, √3], S = [[√3,1],[1,√3]] — reproduced); Local stabilization (u = u0 − K(x − x0)); Acrobots/Cart-Poles/Quadrotors (one sentence; notebook not run); Finite-horizon LQR (Riccati ODE, convergence to infinite horizon for stabilizable systems, square-root form); Time-varying LQR; Local trajectory stabilization (S(t2) = S∞); Linear Quadratic Optimal Tracking; Discrete-time Riccati Equations (gain formula written with S[n]; DARE); discounted LQR; LQR via Fitted Value Iteration (non-PD Riccati solutions, stability of PD fixed point); LQR with input and state constraints (→ MPC); LQR on a manifold and Segway (not stabilizable in full coordinates); implicit form, LMI and least-squares sections skimmed. NOT read: notebooks/code output, exercises, cited papers (Posa15, Mehrmann91, Anderson19, etc.).
- Optimization-Based Control, Chapter 3: Optimal Control (v2.3d, 14 Jan 2023) — scoped · pdftotext of obc-optimal_14Jan2023.pdf v2.3d. Checked for this topic: §3.5 pp. 3-11–3-14 (maximum-principle derivation with ½ factor, λ = P x, Riccati ODE (3.7), ARE (3.9), python-control ct.lqr, Qu > 0 needed, Qx = HᵀH with (A, H) detectable, Theorem 3.2 with reachability and observability, J* = x(0)ᵀPx(0)); Example 3.4 pp. 3-14–3-15 (Qx = diag(q², 0): P, K = [q, √(2q)], ω0 = √q, ζ = 1/√2 — reproduced); §3.6 pp. 3-15–3-16 (diagonal weights, Bryson–Ho inverse-square rule second-hand, Qx = HᵀH, Qu = ρI; Example 3.5 weights skimmed); §3.7 'Integral action' pp. 3-18–3-19. NOT read: exercises, python-control API details, Bryson–Ho.
Related topics