---
title: Recursive least squares
heading: Exponentially weighted least squares, the RLS recursion, forgetting, tracking and cost
eyebrow: S7 · Lesson 38 · Recursive least squares
xp: 50
---

::: hook
LMS (lesson 37) takes one cheap gradient step per sample, and with a strongly colored input its slow eigenmodes take thousands of samples to settle. Recursive least squares instead solves the full least-squares problem for all the data so far, updating the solution with each new sample at a cost of order P² instead of P. It converges in about twice the filter length whatever the input's spectrum, and a forgetting factor lets it track a changing system. Echo cancellers, channel equalizers and adaptive arrays that must converge fast use it or its fast variants.
:::

::: play
- The curve is RLS's steady-state misadjustment against the forgetting factor λ, for P taps: about $\frac{P(1 - \lambda)}{1 + \lambda}$.
- λ close to 1 means a long memory, $1/(1 - \lambda)$ samples, and little excess error; smaller λ forgets faster, tracks changes faster, and is noisier.
- With 10 taps and λ = 0.99 the misadjustment is 5%, from a memory of 100 samples.
:::

```sim plot
view: graph
x: l = 0.9..0.9999 log
y: M = 0.001..100 % log
slider: P = 2..64 = 10 step 1
plot: 100*P*(1 - l)/(1 + l) | label: misadjustment
```

::: predict
## A 4-tap system is identified from 200 samples of a strongly colored input (white noise through a pole at 0.9), with no measurement noise. How do LMS (μ = 0.01) and RLS compare?

- [ ] Both find the taps to 1%
- [x] RLS finds them to about one part in a million; LMS is still off by about 0.18 in coefficient error
- [ ] LMS converges faster because it's simpler
- [ ] Neither converges in 200 samples

::: reveal
The colored input spreads the correlation matrix's eigenvalues over a ratio of hundreds, so LMS's slowest mode has barely moved in 200 samples. RLS solves the normal equations exactly at each step, so once it has more than a handful of samples beyond the four taps its error is set only by the initialization, here about 10⁻⁶.
:::
:::

::: nameit
## The cost and its solution

RLS minimizes the exponentially weighted error
$$J[n] = \sum_{i=0}^{n}\lambda^{n-i}\left(d[i] - \mathbf{w}^T\mathbf{x}[i]\right)^2$$
with forgetting factor 0 < λ ≤ 1 (memory about $1/(1 - \lambda)$ samples). Its solution is $\mathbf{w} = \Phi^{-1}\mathbf{z}$ with $\Phi = \sum\lambda^{n-i}\mathbf{x}\mathbf{x}^T$ and $\mathbf{z} = \sum\lambda^{n-i}d\,\mathbf{x}$.

## The recursion

Keeping $\mathbf{P} = \Phi^{-1}$ and updating it by the matrix inversion lemma, each sample costs O(P²):
$$\mathbf{k} = \frac{\mathbf{P}\mathbf{x}}{\lambda + \mathbf{x}^T\mathbf{P}\mathbf{x}}, \quad e = d - \mathbf{w}^T\mathbf{x}, \quad \mathbf{w} \leftarrow \mathbf{w} + \mathbf{k}e, \quad \mathbf{P} \leftarrow \frac{\mathbf{P} - \mathbf{k}\mathbf{x}^T\mathbf{P}}{\lambda}$$
started from w = 0 and $\mathbf{P} = \delta^{-1}I$ with δ small.

## Behavior

- **Convergence** in about 2P samples, independent of the eigenvalue spread.
- **Misadjustment** for a fixed system, $M \approx \frac{P(1 - \lambda)}{1 + \lambda}$; with λ = 1 it goes to zero as the data accumulate (it becomes ordinary least squares).
- **Tracking**: smaller λ follows a changing system faster at the cost of more misadjustment, the same trade as LMS's step size.
- **Cost and numerics**: O(P²) per sample against LMS's O(P); in finite precision P can lose symmetry and positive definiteness, so robust versions use square-root (QR) forms, and fast transversal or lattice versions bring the cost to O(P) for tapped-delay-line inputs.
:::

::: example
## An RLS filter has 10 taps and λ = 0.99. What memory and misadjustment does it have? What λ gives a memory of 1000 samples?

::: solution
1. **Memory.**
   $$\begin{aligned} L &= \frac{1}{1 - 0.99} \\ &= 100\ \text{samples} \end{aligned}$$
2. **Misadjustment.**
   $$\begin{aligned} M &= \frac{10 \times 0.01}{1.99} \\ &= 5.0\% \end{aligned}$$
3. **For a 1000-sample memory.**
   $$\begin{aligned} \lambda &= 1 - 1/1000 \\ &= 0.999 \end{aligned}$$
   with misadjustment 0.5%.
4. **The trade.** Tenfold memory gives tenfold lower excess error and tenfold slower tracking.

**Answer:** a memory of 100 samples and 5.0% misadjustment; λ = 0.999 gives a memory of 1000 samples.
:::
:::

::: example
## A one-tap RLS filter with x = 1 every sample, λ = 1 and a huge initial P sees d = 2, 4, 3. What does its weight become?

::: solution
1. **What the weight is.** With x = 1 the least-squares weight is just the average of the d values so far.
2. **Step by step.** That's 2 after one sample, 3 after two and 3 after three.
3. **Why.** RLS with λ = 1 reproduces ordinary least squares exactly at every step; with λ < 1 it would be an exponentially weighted average instead.

**Answer:** the weight goes 2, 3, 3, ending at 3.
:::
:::

::: example
## A 64-tap echo canceller could use LMS or RLS. Roughly how do their costs per sample compare, and what does RLS buy?

::: solution
1. **LMS cost.** About 2P = 128 multiplications per sample.
2. **RLS cost.** Standard RLS costs on the order of $P^2$, here a few thousand.
3. **What RLS buys.** It converges in about 2P = 128 samples regardless of the speech's spectrum, where LMS on colored speech may take tens of thousands.
4. **Fast RLS.** Fast RLS variants exploit the delay-line structure to get RLS's convergence at roughly ten times LMS's cost.

**Answer:** LMS costs about 128 multiplications per sample and RLS a few thousand; RLS buys convergence in about 128 samples whatever the input's spectrum.
:::
:::

::: check
kind: parts
given: P = 4 | 16 | 64; l = 0.95 | 0.99 | 0.999

## An RLS filter has {P} taps and forgetting factor {l}.

::: part
answer: 1/(1 - l)
unit: samples
tolerance: 0.5%

### What is its memory?

::: misses
- [any] $1/(1 - \lambda)$.
:::
:::

::: part
answer: P*(1 - l)/(1 + l)*100
unit: %
tolerance: 0.5%

### What misadjustment does it have?

::: misses
- [P*(1 - l)*100] Divide by 1 + λ.
- [any] $P(1 - \lambda)/(1 + \lambda)$.
:::
:::
:::

::: check
kind: parts
given: L = 50 | 200 | 5000; P = 8 | 32

## A {P}-tap RLS filter should remember about {L} samples.

::: part
answer: 1 - 1/L
tolerance: 0.01%

### What forgetting factor does it use?

::: misses
- [any] $\lambda = 1 - 1/L$.
:::
:::

::: part
answer: P*(1/L)/(2 - 1/L)*100
unit: %
tolerance: 0.5%

### What misadjustment results?

::: misses
- [any] $P(1 - \lambda)/(1 + \lambda)$.
:::
:::
:::

::: check
kind: parts
given: a = 2 | 5; b = 4 | 9; c = 1 | 10

## A one-tap RLS filter with x = 1, λ = 1 and a huge initial P receives d = {a}, {b}, {c}.

::: part
answer: (a + b)/2
tolerance: 0.5%

### What is its weight after two samples?

::: misses
- [any] The mean of the first two.
:::
:::

::: part
answer: (a + b + c)/3
tolerance: 0.5%

### After three?

::: misses
- [c] RLS with λ = 1 averages all the data, not just the latest.
- [any] The mean of all three.
:::
:::
:::

::: check
kind: parts
given: P = 16 | 32 | 128; f = 8 | 16

## A {P}-tap adaptive filter runs at {f} kHz.

::: part
answer: 2*P/(f*1000)*1000
unit: ms
tolerance: 0.5%

### Roughly how long does RLS take to converge?

::: misses
- [any] About 2P samples.
:::
:::

::: part
answer: P
tolerance: 0.5%

### By roughly what factor does RLS's per-sample cost exceed LMS's (P² against P)?

::: misses
- [any] $P^2/P$.
:::
:::
:::

::: check
kind: choice

## A channel equalizer must converge within a short training sequence, and the channel's frequency response has deep notches. Why does RLS suit it better than LMS?

- [ ] RLS uses less computation
- [x] Deep notches make the input's correlation matrix badly conditioned (a huge eigenvalue spread), which slows LMS's weakest modes enormously; RLS effectively whitens the input by using the inverse correlation matrix, converging in about twice the filter length regardless
- [ ] LMS can't adapt complex weights
- [ ] RLS needs no training sequence

::: misses
- [1] It uses more: order P² per sample.
- [3] Complex LMS is standard.
- [4] Both need training (or a decision-directed mode).
:::
:::

::: check
kind: derivation
vars: l = 0.9..0.99999, P = 1..256

## An RLS filter has P taps and forgetting factor l.

::: step
answer: 1/(1 - l)

### What is its memory in samples?
:::

::: step
answer: P*(1 - l)/(1 + l)

### What is its misadjustment?
:::

::: step
answer: 2*P

### About how many samples does it need to converge?
:::

::: right
Right. Memory and misadjustment trade against each other through λ; convergence depends only on P.
:::
:::

::: check
kind: python

## Write `rls(x, d, P, lam=1.0, delta=1e-4)`: run RLS for a P-tap filter on input x and desired d (lists), starting from w = 0 and P = I/δ, and return the final weights.

```python starter
def rls(x, d, P, lam=1.0, delta=1e-4):
    return [0.0] * P
```

```python solution
def rls(x, d, P, lam=1.0, delta=1e-4):
    w = [0.0] * P
    Pm = [[1 / delta if i == j else 0.0 for j in range(P)] for i in range(P)]
    for n in range(len(x)):
        u = [x[n - k] if n - k >= 0 else 0.0 for k in range(P)]
        Pu = [sum(Pm[i][j] * u[j] for j in range(P)) for i in range(P)]
        den = lam + sum(u[i] * Pu[i] for i in range(P))
        k = [v / den for v in Pu]
        e = d[n] - sum(w[i] * u[i] for i in range(P))
        w = [w[i] + k[i] * e for i in range(P)]
        uP = [sum(u[i] * Pm[i][j] for i in range(P)) for j in range(P)]
        Pm = [[(Pm[i][j] - k[i] * uP[j]) / lam for j in range(P)] for i in range(P)]
    return w
```

```python tests
import math, random
r = random.Random(3)
h = [0.5, -0.3, 0.2, 0.1]
wn = [r.gauss(0, 1) for _ in range(200)]
x = [0.0] * 200
for n in range(200):
    x[n] = wn[n] + (0.9 * x[n - 1] if n else 0)
d = [sum(h[k] * x[n - k] for k in range(4) if n - k >= 0) for n in range(200)]
w = rls(x, d, 4)
assert math.sqrt(sum((a - b) ** 2 for a, b in zip(w, h))) < 1e-5, "Colored input, 200 samples: RLS finds the taps almost exactly."
assert abs(rls([1, 1, 1], [2, 4, 3], 1, delta=1e-9)[0] - 3) < 1e-6, "One tap, λ = 1: the running mean."
```

::: right
Right. The same data leave LMS with μ = 0.01 about 0.18 away from the answer.
:::
:::

::: explain
## Why does RLS converge in about twice the filter length regardless of the input's spectrum, while LMS can take far longer?

::: model
LMS adjusts its weights along the gradient of the error, and with a colored input the error surface is a long, narrow valley: the gradient points mostly across the valley, so progress along it is slow, with a speed set by the smallest eigenvalue of the input's correlation matrix. RLS instead solves the least-squares problem exactly at each step using the inverse of the correlation matrix, which is equivalent to whitening the input before adapting; every direction then converges at the same rate. Once it has seen enough samples to estimate the P × P matrix, about twice the number of taps, the solution is essentially found, at the cost of order P² operations per sample.
:::
:::

::: practice
::: check
given: l = 0.9 | 0.95 | 0.98 | 0.99 | 0.995 | 0.999
answer: 1/(1 - l)
unit: samples
tolerance: 0.5%

## Memory of an RLS filter with λ = {l}?

::: misses
- [any] $1/(1 - \lambda)$.
:::
:::

::: check
given: P = 6 | 24; l = 0.97 | 0.999
answer: P*(1 - l)/(1 + l)*100
unit: %
tolerance: 0.5%

## Misadjustment for P = {P}, λ = {l}?

::: misses
- [any] $P(1 - \lambda)/(1 + \lambda)$.
:::
:::

::: check
given: L = 20 | 50 | 80 | 100 | 200 | 400 | 1000
answer: 1 - 1/L
tolerance: 0.01%

## Forgetting factor for a {L}-sample memory?

::: misses
- [any] $1 - 1/L$.
:::
:::
:::
