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 , multiply the factors in reverse order, repeat. The matrix converges to triangular form with the eigenvalues on the diagonal.
The basic iteration
Since , every is orthogonally similar to and has the same eigenvalues. Under mild conditions approaches an upper triangular matrix (the Schur form), with the subdiagonal entries decaying like .
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
- Reduction to Hessenberg form (tridiagonal for symmetric matrices) by Householder reflections, costing once. QR steps on a Hessenberg matrix then cost only .
- Shifts: factor with near an eigenvalue (Wilkinson shift), giving quadratic or even cubic convergence of the last row.
- Deflation: when a subdiagonal entry is negligible, split the problem into two smaller ones.
- Implicit double shifts (Francis) for real matrices with complex eigenvalues.
With these, all eigenvalues of an matrix take about flops, needing only about 2 iterations per eigenvalue.
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 behindnp.linalg.eigandeigh. scipy.linalg.schur(A)returns the Schur form that the QR algorithm computes;scipy.linalg.hessenbergthe first stage.
Exercises
Exercise 1: Similarity
Show that has the same eigenvalues as .
Answer
.
Solution
, so , a similarity transformation with an orthogonal matrix.
Exercise 2: Convergence rate
For eigenvalues , which subdiagonal entry of the basic QR iteration decays slowest?
Answer
The entry, with rate .
Solution
Entry decays like : for the first, 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
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…
- where
Why reduce to Hessenberg form first?
- It changes the eigenvalues
- Each QR step then costs instead of
- It makes the matrix symmetric
- It is required for real matrices only
Shifts in the QR algorithm…
- change the eigenvalues
- accelerate convergence to quadratic or cubic
- are only for complex matrices
- slow it down