Eigenvalue algorithms: power iteration, Jacobi and the QR algorithm
| Problem | Compute eigenvalues and eigenvectors with , one at a time (power and inverse iteration) or all at once (Jacobi, QR algorithm) |
| Devised by | Carl Gustav Jacobi (1846), the rotation method; Richard von Mises (1929), power iteration; Helmut Wielandt (1944), inverse iteration; Lord Rayleigh, the quotient, with cubic convergence of the iteration shown by Alexander Ostrowski (1958); Heinz Rutishauser (1958), the LR algorithm; John Francis (1961) and Vera Kublanovskaya (1961), the QR algorithm |
| Accuracy | For symmetric matrices: absolute errors of about in the eigenvalues; Jacobi also gives small eigenvalues to high relative accuracy |
| Cost | Power iteration: per step, steps. Jacobi: per sweep, 6–10 sweeps. QR algorithm on a full matrix: per step, about two steps per eigenvalue with shifts |
| Read first | Gaussian elimination and LU factorisation, QR factorisation |
| API | Reference: power_iteration, jacobi_eigenvalue, qr_algorithm |
Overview
Eigenvalues describe the natural behaviour of linear systems: the frequencies of vibration of a structure, the growth rates of a population model, the energy levels of a quantum system, the stability of an equilibrium, the principal axes of a dataset. Unlike linear systems, eigenvalue problems cannot be solved in a finite number of steps for : the eigenvalues are the roots of the characteristic polynomial, and by the Abel-Ruffini theorem there is no formula. Every eigenvalue algorithm is therefore iterative.
This entry describes the three classical ideas, as implemented in the reference crate: power iteration and its shifted variants, which find one eigenpair; Jacobi’s method, which annihilates off-diagonal entries by rotations; and the QR algorithm, the basis of all modern eigensolvers. The next entry describes how production codes make the QR algorithm fast.
Where it is used
Eigenvalues describe the natural behaviour of a system.
- Vibrations. Natural frequencies and mode shapes of a bridge, aircraft wing or engine are eigenvalues and eigenvectors of its stiffness and mass matrices.
- PageRank and networks. Power iteration on the web’s link matrix ranks pages by importance.
- Stability. A linear system is stable if the eigenvalues of its matrix are in the left half-plane (or inside the unit circle for discrete time).
- Data analysis. Principal components are eigenvectors of a covariance matrix.
History
Carl Gustav Jacobi (1846) diagonalised symmetric matrices by plane rotations, to compute the secular perturbations of the planets; his method was forgotten and rediscovered for computers by Herman Goldstine, Francis Murray and John von Neumann in the 1950s. Richard von Mises (1929) described power iteration; Helmut Wielandt (1944) introduced inverse iteration with shifts. Heinz Rutishauser (1958) discovered that factoring and multiplying in reverse order converges to a triangular matrix, and in 1961 John Francis in England and Vera Kublanovskaya in the Soviet Union independently replaced by the stable factorisation. Francis also introduced the Hessenberg reduction, shifts and the implicit double-shift step that made the method practical; it was later named one of the ten most important algorithms of the twentieth century.
The idea
Power iteration, inverse iteration and the Rayleigh quotient
An eigenvector of is a nonzero vector that merely stretches, ; the factor is its eigenvalue. For matrices larger than there is no formula for the eigenvalues (they are roots of a polynomial of degree ), so every eigenvalue algorithm is an iteration. The simplest one shows the principle behind all the others.
Power iteration. Suppose has eigenvectors with eigenvalues ordered by magnitude, . Any starting vector is a combination of the eigenvectors, . Each multiplication by multiplies the -th component by , so after multiplications
Every ratio tends to zero, so the direction of tends to that of : repeated multiplication amplifies the dominant eigenvector relative to all the others. To stop the vector overflowing or underflowing, it is rescaled to unit length at each step:
The unwanted components shrink by the factor per step. This is linear convergence, and it is slow when the two largest eigenvalues are close in magnitude.
The Rayleigh quotient. Given an approximate eigenvector , the best estimate of the corresponding eigenvalue is
If is an exact eigenvector this equals . For symmetric it has a valuable property: if differs from an eigenvector by an error of size , then differs from the eigenvalue by only about . An eigenvector known to three digits gives an eigenvalue good to six.
Inverse iteration. Power iteration finds only the largest eigenvalue. To find others, apply it to a different matrix with the same eigenvectors. If , then for any number ,
The matrix has the same eigenvectors as , with eigenvalues . The largest of these belongs to the closest to . So power iteration on converges to the eigenvector whose eigenvalue is nearest the shift , and the rate is . If is a good estimate of an eigenvalue, the numerator is tiny and convergence takes a step or two. The inverse is never formed: each step solves the linear system using one LU factorisation computed at the start.
Rayleigh quotient iteration combines the last two ideas: after every step, replace the shift by the Rayleigh quotient of the current vector. A better vector gives a better shift, which gives a much better vector. For symmetric matrices the convergence is cubic, tripling the number of correct digits per step, at the cost of a new factorisation at each step because the shift changes.
Table 7.6. Power, inverse and Rayleigh quotient iteration on one spectrum.
| spectrum of the matrix | power iteration | inverse iteration, shift 10.2 | Rayleigh quotient iteration |
|---|---|---|---|
| (ratio 0.5) | 36 (λ = 10.0000000000) | 8 (λ = 10.0000000000) | 5 (λ = 0.3703703704) |
| (ratio 0.9) | 217 (λ = 10.0000000000) | 13 (λ = 10.0000000000) | 4 (λ = 0.3703703704) |
| (ratio 0.99) | 2044 (λ = 10.0000000000) | 51 (λ = 10.0000000000) | 3 (λ = 0.3703703704) |
Power iteration slows in proportion to ; inverse iteration with a shift near 10 is fast in every case. Rayleigh quotient iteration needs three to five steps, but it converges to an eigenvalue, the one its starting vector leads it to (here 0.37, in the middle of the spectrum), not necessarily the one wanted.
The Jacobi method
The methods above find one eigenpair. To find all of them for a symmetric matrix, the goal is an orthogonal matrix with diagonal: the diagonal of then holds the eigenvalues and the columns of the eigenvectors. Jacobi’s method builds from the simplest orthogonal matrices, rotations in a coordinate plane.
For a symmetric matrix a single rotation does the job exactly. In an matrix, a plane rotation acts only on coordinates and , and the angle can be chosen so that has a zero in positions and . The angle satisfies , and the smaller of its two solutions is taken, which keeps .
The rotation changes all of rows and columns and , so a zero created by one rotation is generally filled in again by later ones. Progress is nevertheless guaranteed. An orthogonal similarity preserves the sum of squares of all the entries, and the rotation moves of that sum from the off-diagonal part onto the diagonal. The off-diagonal sum of squares therefore falls by exactly at each rotation and never increases. Sweeping repeatedly over all pairs drives to a diagonal matrix of eigenvalues, and the product of all the rotations is .
Convergence is quadratic once the off-diagonal part is small, and 6 to 10 sweeps suffice whatever the order (table below). Jacobi’s method is slower than the QR algorithm, but simple, naturally parallel, and accurate: it determines small eigenvalues of graded matrices to high relative accuracy (Demmel and Veselić, 1992), which is why its one-sided form is used for the SVD.
The QR algorithm
The standard method for all the eigenvalues of a matrix looks, at first sight, like a trick. Factor the current matrix as by a QR factorisation, and multiply the factors back together in the opposite order:
It preserves the eigenvalues. Since , the new matrix is . This is a similarity transformation by an orthogonal matrix, so has the same eigenvalues as , and by induction the same as . Symmetry is preserved too.
It converges, because it is power iteration in disguise. Apply power iteration to vectors at once, re-orthonormalising them after each multiplication so that they do not all collapse onto the dominant eigenvector. This is subspace iteration: the first vector converges to the dominant eigenvector, the first two span the dominant two-dimensional invariant subspace, and so on. The accumulated product of the QR algorithm is exactly the orthonormal basis that subspace iteration produces from the identity matrix. To see this, write one step as , . By induction, , and : this is for , and if it holds for then , where the first formula (with steps) gives . So is the orthonormal factor of the QR factorisation of , which is what orthonormalising the columns of (subspace iteration) gives. Consequently converges to a diagonal matrix (for symmetric ) or an upper triangular one (in general), with the eigenvalues on the diagonal in order of decreasing magnitude. The entry in position below the diagonal decays like .
This unshifted algorithm inherits the weakness of power iteration: it converges slowly when eigenvalues are close in magnitude, and not at all for eigenvalues of equal magnitude.
Shifts make it fast. The remedy is the same as before. The shifted QR algorithm factors and sets , which is still a similarity transformation. The last row of the iteration behaves like inverse iteration with shift . To see why, note that gives , and the last row of the upper triangular is , so the last row of is : one step of inverse iteration with shift , started from . With a shift close to an eigenvalue, the off-diagonal entries of the last row fall to zero in a few steps, leaving that eigenvalue isolated in the bottom corner. It is then deflated: set aside as converged, while the iteration continues on the leading block.
A good shift is available from the matrix itself. Wilkinson’s shift is the eigenvalue of the trailing block that is nearer to its bottom right entry. With it the algorithm is guaranteed (Wilkinson, 1968) to converge for every symmetric tridiagonal matrix. A general symmetric matrix is first reduced to tridiagonal form, so the result covers it as well. The convergence is cubic in general:
Table 7.7. Iterations of Jacobi and of unshifted and shifted QR against order.
| order | Jacobi sweeps | unshifted QR steps | Wilkinson-shifted QR steps | steps per eigenvalue (shifted) |
|---|---|---|---|---|
| 10 | 6 | 2497 | 21 | 2.10 |
| 20 | 7 | 5114 | 41 | 2.05 |
| 40 | 8 | 2166 | 77 | 1.93 |
| 80 | 8 | > 20 000 | 152 | 1.90 |
The shifted algorithm needs about two steps per eigenvalue, independently of the spectrum. But each step on a full matrix costs , for in all; production codes first reduce the matrix to tridiagonal or Hessenberg form, which makes each step or (next entry).
Algorithm
Power iteration. Input: , a starting vector , normalised to unit length, and a tolerance. Repeat, up to an iteration limit:
- multiply: ;
- normalise: ;
- estimate the eigenvalue by the Rayleigh quotient of the new vector, ;
- if the residual is below the tolerance, return and .
Each iteration costs two matrix-vector products as written (one would do, if from step 3 were reused as the next ).
Inverse iteration with shift : factor once; then run the same loop with step 1 replaced by “solve ”.
Rayleigh quotient iteration: as inverse iteration, but with the shift replaced by the current at every step, so that the matrix must be factorised again each time. As the shift converges to an eigenvalue the matrix becomes nearly singular. That does no harm: the solution is then huge, but its direction is the eigenvector, and only the direction is kept. If the factorisation finds the matrix exactly singular, the shift is an eigenvalue to rounding error, and the iteration stops with the current vector.
Cyclic Jacobi. Input: a symmetric . Set . Repeat:
- if the off-diagonal norm is below the tolerance times the Frobenius norm of the original matrix, stop;
- for every pair in turn (one sweep): compute the rotation angle from , and ; apply the rotation to rows and columns and of , which sets to zero; apply it to columns and of .
The diagonal of then holds the eigenvalues and the columns of the eigenvectors. A sweep costs .
Shifted QR. Input: a symmetric . The active block is the leading part of the matrix not yet deflated; it starts as the whole matrix. While its order exceeds 1:
- if the norm of the off-diagonal entries of its last row is below the tolerance times the Frobenius norm of the original matrix, set them to zero, record the last diagonal entry as an eigenvalue, and shrink the active block by one (deflation);
- otherwise compute Wilkinson’s shift from the trailing block, factor on the active block, and replace the block by .
Implementation
Rayleigh quotient iteration:
/// Rayleigh quotient iteration: `v ← (A − σ_k I)⁻¹ v` with `σ_k = vᵀAv`, refactorising each step.
pub fn rayleigh_quotient_iteration(
a: &Array2<f64>,
start: &Array1<f64>,
tolerance: f64,
max_iterations: usize,
) -> Result<EigenEstimate, Error> {
let n = a.nrows();
iterate(a, start, tolerance, max_iterations, |v, shift| {
match crate::lu::lu(&(a - &(crate::identity(n) * shift))) {
Ok(factors) => factors.solve(v).map(Some),
Err(_) => Ok(None),
}
})
}
Cyclic Jacobi:
/// Cyclic Jacobi: sweeps over all pairs `p < q` until the off-diagonal norm is below
/// `tolerance × ‖A‖_F`.
pub fn jacobi_eigen(a: &Array2<f64>, tolerance: f64) -> Result<JacobiEigen, Error> {
let n = a.nrows();
let mut a = a.clone();
let mut v = crate::identity(n);
let scale = a.iter().map(|x| x * x).sum::<f64>().sqrt();
let mut sweeps = 0;
while crate::off_diagonal_norm(&a) > tolerance * scale {
if sweeps == 100 {
return Err("the Jacobi method did not converge");
}
for p in 0..n {
for q in p + 1..n {
if a[[p, q]] == 0.0 {
continue;
}
// tan θ is the smaller root of t² + 2 t cot 2θ − 1 = 0, keeping |θ| ≤ π/4.
let cot = (a[[q, q]] - a[[p, p]]) / (2.0 * a[[p, q]]);
let t = cot.signum() / (cot.abs() + (cot * cot + 1.0).sqrt());
let c = 1.0 / (t * t + 1.0).sqrt();
let s = t * c;
rotate_columns(&mut a, p, q, c, s);
rotate_rows(&mut a, p, q, c, s);
rotate_columns(&mut v, p, q, c, s);
}
}
sweeps += 1;
}
let mut order: Vec<usize> = (0..n).collect();
order.sort_by(|&i, &j| a[[i, i]].total_cmp(&a[[j, j]]));
Ok(JacobiEigen {
values: order.iter().map(|&i| a[[i, i]]).collect(),
vectors: Array2::from_shape_fn((n, n), |(i, j)| v[[i, order[j]]]),
sweeps,
})
}
The shifted QR algorithm with deflation:
/// QR iteration with Wilkinson shifts and deflation.
pub fn shifted_qr(a: &Array2<f64>, tolerance: f64, max_iterations: usize) -> Result<QrEigenvalues, Error> {
let scale = frobenius(a);
let mut a = a.clone();
let mut m = a.nrows();
let mut iterations = 0;
while m > 1 {
let last_row = a.slice(s![m - 1, ..m - 1]);
if last_row.dot(&last_row).sqrt() <= tolerance * scale {
m -= 1; // a[m−1, m−1] is an eigenvalue; continue on the leading block.
continue;
}
if iterations == max_iterations {
return Err("shifted QR did not converge");
}
let mu = wilkinson_shift(a[[m - 2, m - 2]], a[[m - 1, m - 2]], a[[m - 1, m - 1]]);
let shift = crate::identity(m) * mu;
let (q, r) = householder(&(&a.slice(s![..m, ..m]) - &shift));
a.slice_mut(s![..m, ..m]).assign(&(r.dot(&q) + shift));
iterations += 1;
}
Ok(QrEigenvalues { values: sorted_diagonal(&a), iterations })
}
- The reference routines are for real symmetric matrices, written for clarity; the production solvers handle general and complex matrices.
In practice
//! Textbook eigenvalue algorithms: power iteration, Jacobi rotations and the QR algorithm.
//!
//! Run with `cargo run -p lib_jsl_linalg_reference --example linalg_eigen_iterations`.
use lib_jsl_linalg_reference::jacobi_eigenvalue::jacobi_eigen;
use lib_jsl_linalg_reference::power_iteration::{inverse_iteration, power_iteration, rayleigh_quotient_iteration};
use lib_jsl_linalg_reference::qr_algorithm::{shifted_qr, unshifted_qr};
use ndarray::{Array1, Array2};
fn main() {
// The second-difference matrix of a vibrating string with 8 interior points: eigenvalues
// 2 − 2 cos(kπ/9), k = 1..8, the squared frequencies of its modes.
let n = 8;
let a = Array2::from_shape_fn((n, n), |(i, j)| if i == j { 2.0 } else if i.abs_diff(j) == 1 { -1.0 } else { 0.0 });
let exact: Vec<f64> = (1..=n).map(|k| 2.0 - 2.0 * (k as f64 * std::f64::consts::PI / 9.0).cos()).collect();
println!("exact eigenvalues: {exact:.6?}");
let start = Array1::from_elem(n, 1.0) + Array1::from_shape_fn(n, |i| 0.01 * i as f64);
let p = power_iteration(&a, &start, 1e-10, 10_000).unwrap();
println!("power iteration: largest λ = {:.10} in {} steps", p.value, p.iterations);
let i = inverse_iteration(&a, 0.1, &start, 1e-10, 1000).unwrap();
println!("inverse iteration (shift 0.1): smallest λ = {:.10} in {} steps", i.value, i.iterations);
let r = rayleigh_quotient_iteration(&a, &start, 1e-12, 100).unwrap();
println!("Rayleigh quotient iteration: λ = {:.12} in {} steps", r.value, r.iterations);
let j = jacobi_eigen(&a, 1e-14).unwrap();
println!("Jacobi: {:.6} in {} sweeps", j.values, j.sweeps);
let u = unshifted_qr(&a, 1e-12, 100_000).unwrap();
let s = shifted_qr(&a, 1e-14, 1000).unwrap();
println!("QR algorithm: {} unshifted steps, {} shifted steps; {:.6}", u.iterations, s.iterations, s.values);
}
Strengths
- Power and inverse iteration need only matrix-vector products or one factorisation, and suit large sparse matrices when a few eigenvalues are wanted (the basis of Lanczos and Arnoldi methods).
- Jacobi is simple, parallel and accurate; the shifted QR algorithm converges reliably and fast.
Weaknesses
- Power iteration is slow for close eigenvalues; Rayleigh quotient iteration may converge to an unwanted eigenvalue.
- On full matrices, Jacobi and QR cost per sweep or step: they are practical only after reduction, or for small .
Exercises
- Show that the Rayleigh quotient of a vector with error in the eigenvector direction has error for symmetric .
- Show that a Jacobi rotation reduces the off-diagonal sum of squares by exactly .
- Show that is orthogonally similar to , and that .
- Run unshifted QR on a matrix with eigenvalues and . Why does it never converge, and how does a shift fix it?
- Use inverse iteration with the eigenvalues computed by
eigvalshas shifts to compute the eigenvectors, and compare witheigh.
Hints and answers
- Write with . Then , because the cross term vanishes, since is symmetric and .
- A rotation changes only rows and columns and preserves the Frobenius norm. It sets to 0 and leaves unchanged, so the off-diagonal sum of squares drops by exactly (counting both and ).
- . For the product, induct: and .
- For , and , so : a fixed point that is not diagonal. Convergence needs eigenvalues of different moduli; a shift makes .
- With the exact eigenvalue as shift, inverse iteration converges in one or two steps. For clustered eigenvalues the computed vectors are not orthogonal and need reorthogonalisation, which
eighdoes implicitly.
Further reading
- B. N. Parlett, The Symmetric Eigenvalue Problem, Prentice-Hall, 1980 (SIAM reprint, 1998).
- J. G. F. Francis, “The QR transformation: a unitary analogue to the LR transformation”, The Computer Journal 4 (1961) 265–271 and 332–345.
- J. Demmel and K. Veselić, “Jacobi’s method is more accurate than QR”, SIAM Journal on Matrix Analysis and Applications 13 (1992) 1204–1245.
- D. S. Watkins, “Francis’s algorithm”, American Mathematical Monthly 118 (2011) 387–403.
- L. N. Trefethen and D. Bau, Numerical Linear Algebra, SIAM, 1997, lectures 24–31.