TExcelTAD
Home › Numerical Methods › The QR Algorithm

The QR Algorithm

How does np.linalg.eig actually compute all eigenvalues of a matrix? The answer is the QR algorithm, named one of the top ten algorithms of the 20th century. Its basic form is surprisingly simple: factor A=QRA = QR, multiply the factors in reverse order, repeat. The matrix converges to triangular form with the eigenvalues on the diagonal.

The basic iteration

A0=A,Ak=QkRk,Ak+1=RkQk.A_0 = A, \qquad A_k = Q_kR_k, \qquad A_{k+1} = R_kQ_k.

Since Ak+1=QkTAkQkA_{k+1} = Q_k^TA_kQ_k, every AkA_k is orthogonally similar to AA and has the same eigenvalues. Under mild conditions AkA_k approaches an upper triangular matrix (the Schur form), with the subdiagonal entries decaying like ∣λi+1λi∣k\left\lvert\frac{\lambda_{i+1}}{\lambda_i}\right\rvert^k.

python · try it yourself
import numpy as np

A = np.array([[4.0, 1, 2], [1, 3, 0], [2, 0, 1]])
Ak = A.copy()
for k in range(1, 61):
    Q, R = np.linalg.qr(Ak)
    Ak = R @ Q
    if k in (5, 20, 60):
        print(f"k = {k}: diagonal {np.round(np.diag(Ak), 8)}, largest below-diagonal entry {np.max(np.abs(np.tril(Ak, -1))):.1e}")
print("np.linalg.eigvalsh:", np.round(np.linalg.eigvalsh(A)[::-1], 8))
k = 5: diagonal [ 5.34618253  2.72252529 -0.06870782], largest below-diagonal entry 2.7e-02
k = 20: diagonal [ 5.34646219  2.72224563 -0.06870782], largest below-diagonal entry 1.1e-06
k = 60: diagonal [ 5.34646219  2.72224563 -0.06870782], largest below-diagonal entry 2.0e-18
np.linalg.eigvalsh: [ 5.34646219  2.72224563 -0.06870782]

The basic QR algorithm is power iteration and inverse iteration in disguise, applied to a whole orthonormal basis at once.

What the practical algorithm adds

  1. Reduction to Hessenberg form (tridiagonal for symmetric matrices) by Householder reflections, costing O(n3)O(n^3) once. QR steps on a Hessenberg matrix then cost only O(n2)O(n^2).
  2. Shifts: factor Ak−μkIA_k - \mu_kI with μk\mu_k near an eigenvalue (Wilkinson shift), giving quadratic or even cubic convergence of the last row.
  3. Deflation: when a subdiagonal entry is negligible, split the problem into two smaller ones.
  4. Implicit double shifts (Francis) for real matrices with complex eigenvalues.

With these, all eigenvalues of an n×nn \times n matrix take about 10n310n^3 flops, needing only about 2 iterations per eigenvalue.

python · try it yourself
import numpy as np
from scipy.linalg import hessenberg

def shifted_qr(A, tol=1e-12):
    """Eigenvalues of a symmetric matrix by QR with Wilkinson shifts and deflation."""
    H = hessenberg(A)                        # tridiagonal for symmetric A
    n = H.shape[0]
    eigs, iters = [], 0
    while n > 1:
        a, b, c = H[n - 2, n - 2], H[n - 1, n - 2], H[n - 1, n - 1]
        d = (a - c) / 2
        mu = c - np.sign(d or 1.0) * b * b / (abs(d) + np.hypot(d, b))   # Wilkinson shift
        Q, R = np.linalg.qr(H[:n, :n] - mu * np.eye(n))
        H[:n, :n] = R @ Q + mu * np.eye(n)
        iters += 1
        if abs(H[n - 1, n - 2]) < tol * (abs(H[n - 1, n - 1]) + abs(H[n - 2, n - 2])):
            eigs.append(H[n - 1, n - 1]); n -= 1          # deflate
    eigs.append(H[0, 0])
    return np.sort(eigs), iters

rng = np.random.default_rng(71)
B = rng.normal(size=(30, 30)); A = B + B.T
vals, iters = shifted_qr(A)
print(f"{iters} QR steps for 30 eigenvalues; max error vs eigvalsh {np.max(np.abs(vals - np.linalg.eigvalsh(A))):.1e}")
59 QR steps for 30 eigenvalues; max error vs eigvalsh 3.2e-14

Polynomial roots

np.roots builds the companion matrix of the polynomial and runs the QR algorithm on it (Rootfinding in Practice). This is backward stable for the matrix, which is the best one can hope for given the conditioning of polynomial roots.

In software

  • LAPACK geev (general), syevd/syevr (symmetric, using divide-and-conquer or MRRR on the tridiagonal matrix) are behind np.linalg.eig and eigh.
  • scipy.linalg.schur(A) returns the Schur form A=ZTZTA = ZTZ^T that the QR algorithm computes; scipy.linalg.hessenberg the first stage.

Exercises

Exercise 1: Similarity

Show that Ak+1=RkQkA_{k+1} = R_kQ_k has the same eigenvalues as Ak=QkRkA_k = Q_kR_k.

Answer

RkQk=QkT(QkRk)Qk=QkTAkQkR_kQ_k = Q_k^T(Q_kR_k)Q_k = Q_k^TA_kQ_k.

Solution

Rk=QkTAkR_k = Q_k^TA_k, so RkQk=QkTAkQkR_kQ_k = Q_k^TA_kQ_k, a similarity transformation with an orthogonal matrix.

Exercise 2: Convergence rate

For eigenvalues 5,4,15, 4, 1, which subdiagonal entry of the basic QR iteration decays slowest?

Answer

The (2,1)(2, 1) entry, with rate 45\frac{4}{5}.

Solution

Entry (i+1,i)(i+1, i) decays like ∣λi+1λi∣k\left\lvert\frac{\lambda_{i+1}}{\lambda_i}\right\rvert^k: 45=0.8\frac{4}{5} = 0.8 for the first, 14=0.25\frac{1}{4} = 0.25 for the second.

Exercise 3: Hessenberg structure is preserved (code)

Check that one QR step on an upper Hessenberg matrix gives an upper Hessenberg matrix again.

Answer

Entries below the first subdiagonal stay at rounding level.

Solution
python · try it yourself
import numpy as np
from scipy.linalg import hessenberg
rng = np.random.default_rng(72)
H = hessenberg(rng.normal(size=(8, 8)))
Q, R = np.linalg.qr(H)
H2 = R @ Q
print(f"{np.max(np.abs(np.tril(H2, -2))):.1e}")
0.0e+00

Test yourself

One step of the basic QR algorithm computes…

  1. Ak+1=QkRkA_{k+1} = Q_kR_k
  2. Ak+1=RkQkA_{k+1} = R_kQ_k where Ak=QkRkA_k = Q_kR_k
  3. Ak+1=Ak−1A_{k+1} = A_k^{-1}
  4. Ak+1=Ak2A_{k+1} = A_k^2

Why reduce to Hessenberg form first?

  1. It changes the eigenvalues
  2. Each QR step then costs O(n2)O(n^2) instead of O(n3)O(n^3)
  3. It makes the matrix symmetric
  4. It is required for real matrices only

Shifts in the QR algorithm…

  1. change the eigenvalues
  2. accelerate convergence to quadratic or cubic
  3. are only for complex matrices
  4. slow it down