Polynomial roots
| Problem | Find all the roots, real and complex, of a polynomial |
| Devised by | Formulas up to degree 4: Tartaglia, Cardano and Ferrari (1545); none beyond: Ruffini (1799) and Abel (1824). Companion matrix eigenvalues: Cleve Moler’s roots in MATLAB (1970s), shown backward stable by Alan Edelman and H. Murakami (1995); balancing: Beresford Parlett and Christian Reinsch (1969). Ill-conditioning: James Wilkinson (1959) |
| Accuracy | Backward stable: the roots of a polynomial with nearby coefficients. The forward error depends on the conditioning of the roots, which for clustered or multiple roots can be very poor |
| Cost | operations and memory for degree |
| Read first | Newton’s method and the secant method, Symmetric and general eigensolvers |
| API | polynomial_roots (real roots), polynomial_roots_complex (all roots) |
Overview
Polynomials are the one class of functions whose roots can all be found at once, reliably, without
starting guesses or brackets. A polynomial of degree has exactly complex roots, counted with
multiplicity (the fundamental theorem of algebra), and they are the eigenvalues of an
matrix built from the coefficients, the companion matrix. Computing them with the
QR algorithm is the method of MATLAB’s and NumPy’s roots.
Polynomial roots are needed throughout science and engineering: the poles and zeros of filters and control systems, the eigenvalues of small matrices from their characteristic polynomials, the nodes of Gaussian quadrature, the intersections of curves in computer graphics. The library’s Prony’s method finds the frequencies of a signal as polynomial roots.
They also carry the most famous warning in numerical analysis: the roots of a polynomial can depend extremely sensitively on its coefficients.
Where it is used
Polynomial roots describe the natural behaviour of linear systems.
- Control and filters. The roots of the characteristic polynomial are the poles of a system; they decide stability and the shape of a filter’s response.
- Vibrations and circuits. Natural frequencies and damping.
- Algebra and geometry. Intersections of curves, and eigenvalues via the companion matrix.
- Numerical lessons. The famous Wilkinson polynomial shows how sensitive roots can be to tiny changes in coefficients.
History
The quadratic formula was known in Babylon; the cubic and quartic were solved by radicals in sixteenth-century Italy by Scipione del Ferro, Niccolò Tartaglia and Lodovico Ferrari, and published by Gerolamo Cardano in Ars Magna (1545). Paolo Ruffini (1799) and Niels Henrik Abel (1824) proved that no such formula exists for the general quintic, and Évariste Galois explained why. From then on, roots of polynomials of high degree had to be computed numerically, by methods from Newton’s and Horner’s to Bernoulli’s, Graeffe’s and, in 1970, the Jenkins-Traub algorithm.
James Wilkinson, testing a new program on the Pilot ACE computer in the 1950s, chose the polynomial with roots as an easy test, and found it impossible. His analysis (1959), which he later called “the most traumatic experience in my career as a numerical analyst”, showed that the difficulty lay in the polynomial, not the program, and established the ideas of conditioning and backward error. With the QR algorithm for eigenvalues (1961), it became natural to compute polynomial roots as eigenvalues, the approach Cleve Moler used in MATLAB; Alan Edelman and H. Murakami (1995) proved that it is backward stable once the matrix is balanced.
The idea
The companion matrix
Divide the polynomial by its leading coefficient to make it monic: with . Its companion matrix is
The claim is that the eigenvalues of are exactly the roots of . To see why, let be a root and consider the vector of its descending powers, . Multiply it by row by row.
- Rows 2 to each contain a single 1, which copies the entry above: row 2 gives , row 3 gives , and so on down to . Each is times the corresponding entry of .
- Row 1 gives . Because , this equals , which is times the first entry of .
So : every root is an eigenvalue. Since has eigenvalues and has roots, there are no others. (Equivalently, expanding along the first row shows that is the characteristic polynomial of .) For , for example, , with trace and determinant .
Root finding has become an eigenvalue problem, for which a robust general-purpose method exists: the QR algorithm. The companion matrix is already in upper Hessenberg form (zero below the first subdiagonal), which is the form the QR algorithm works on, and the eigenvalue computation costs operations. Specialised structured QR algorithms reduce this to .
Balancing
The entries of can range over many orders of magnitude: the coefficients of Wilkinson’s polynomial (below) run from 1 to . The rounding errors of the QR algorithm are proportional to the largest entries of the matrix, so the information in the small entries is lost.
Balancing is a change of units that evens out the sizes. It replaces by , where is a diagonal matrix chosen to make each row and the matching column similar in size. This is a similarity transformation, so the eigenvalues are unchanged. If the entries of are powers of 2, the scaling only changes exponents and introduces no rounding error at all. Without balancing, this library’s eigenvalue solver returned 18 zeros and a wild complex pair for Wilkinson’s polynomial; with it, all 20 roots to within .
Conditioning: Wilkinson’s polynomial
Why only to within ? Because the roots of this polynomial are extraordinarily sensitive to its coefficients, and no algorithm can overcome that.
Sensitivity of a root. Ask how much a root moves if the coefficient of changes by a small amount . The perturbed polynomial is , and its root satisfies
To first order in the small quantities, and . Solving for ,
The factor is the condition number of the root with respect to that coefficient. It is large when the root is large (the numerator) or when the graph of is nearly flat at the root, as it is when roots are close together (the denominator).
Wilkinson’s example. Take , with the innocent-looking roots , and consider the coefficient of , which is . For the roots 15 and 16 the factor is about . Wilkinson changed that coefficient by , a relative change of , and ten of the roots became five complex pairs:
Figure 4.4. Wilkinson's polynomial.
What a good algorithm can promise. Merely storing the coefficients of in double precision perturbs them by more than enough to move the upper roots by . No algorithm can do better than the conditioning allows. The right standard is backward stability: the computed roots are the exact roots of a polynomial whose coefficients are close to the given ones. The companion matrix method with balancing achieves this in a norm-wise sense.
Table 4.4. Accuracy of polynomial root finding.
| polynomial | real roots found | largest error |
|---|---|---|
| 5 | 1.2e-14 | |
| 10 | 1.4e-10 | |
| 15 | 3.8e-6 | |
| 20 | 4.1e-3 | |
| the same, , with changed by | 10 | n/a |
| 1 | 6.7e-16 |
The lesson for practice: a polynomial given by its roots or by its values should not be converted to coefficients if it can be avoided. Polynomials of high degree are better represented in another basis, such as the Chebyshev basis.
Multiple roots
Multiple roots are the extreme case of ill-conditioning, since there and the formula above breaks down. A direct argument shows what happens. Near a root of multiplicity the polynomial behaves like . Perturb it by a small constant : the equation has the solutions , with the complex -th roots of . A perturbation of size moves the root by , which is far larger. With rounding errors of , a triple root is known only to about .
The perturbed roots lie evenly spaced on a small circle around , which is what the computed eigenvalues look like: a small regular cluster, often a real value and a nearly real complex pair. The centre of the circle is still , so the mean of the cluster is far more accurate than its members: for the members are off by and the mean by .
Real roots
polynomial_roots returns
the distinct real roots. It takes the eigenvalues that are real, or nearly real ()
with vanishing at their real part to within rounding error; groups eigenvalues between which
is indistinguishable from zero into one root at their mean; and polishes isolated roots with a few
steps of Newton’s method.
Algorithm
All complex roots (polynomial_roots_complex). Input: coefficients from the highest power
down.
- Clean up. Strip leading zero coefficients, which lower the true degree. Strip trailing zero coefficients too: each is a root at , recorded and factored out.
- Form the companion matrix of the remaining polynomial, after dividing by its leading coefficient.
- Compute its eigenvalues: balance the matrix, and apply the shifted QR algorithm of the general eigensolver (the matrix is already in Hessenberg form). The eigenvalues, with the zeros from step 1, are the roots.
The cost is for degree .
Distinct real roots (polynomial_roots). From the complex roots:
- Filter. Keep an eigenvalue if its imaginary part is exactly zero, or if it is small () and evaluated at its real part is zero to within the rounding error of Horner’s rule.
- Cluster. Sort the survivors. Merge neighbours into one group when they are close together and is indistinguishable from zero midway between them: they are the scattered images of one multiple root.
- Report. For a group of several eigenvalues, return their mean. For an isolated one, polish it with up to four steps of Newton’s method and return the result.
Implementation
The companion matrix and its eigenvalues:
// p(z)/a₀ = zⁿ + c₁ zⁿ⁻¹ + … + cₙ is the characteristic polynomial of this matrix.
let mut companion = Array2::<f64>::zeros((n, n));
for j in 0..n {
companion[[0, j]] = -coeffs[j + 1] / coeffs[0];
}
for i in 1..n {
companion[[i, i - 1]] = 1.0;
}
let values = companion.eigvals().map_err(|e| format!("polynomial_roots_complex: {e:?}"))?;
The real roots:
fn real_roots(coeffs: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
let deg = coeffs.len() - 1;
match deg {
0 => return Ok(Vec::new()),
1 => return Ok(vec![-coeffs[1] / coeffs[0]]),
_ => {}
}
// The rounding error in evaluating p at x: below it, the value of p(x) means nothing.
let noise = |x: f64| 8.0 * deg as f64 * f64::EPSILON * eval_abs(coeffs, x);
let mut eig = companion_eigenvalues(coeffs)?;
// A real eigenvalue is a real root; a nearly real pair is a multiple real root perturbed by
// rounding (by about ε^(1/m)), if p vanishes at its real part to within rounding error.
eig.retain(|z| z.im == 0.0 || (z.im.abs() <= 1e-3 * z.norm().max(1.0) && eval(coeffs, z.re).abs() <= noise(z.re)));
eig.sort_by(|a, b| a.re.total_cmp(&b.re));
// Group eigenvalues that p cannot tell apart: close together, with p in the noise between.
let mut out = Vec::new();
let mut i = 0;
while i < eig.len() {
let mut j = i + 1;
while j < eig.len() {
let (a, b) = (eig[j - 1].re, eig[j].re);
let mid = 0.5 * (a + b);
if b - a > 1e-3 * mid.abs().max(1.0) || eval(coeffs, mid).abs() > noise(mid) {
break;
}
j += 1;
}
let mean = eig[i..j].iter().map(|z| z.re).sum::<f64>() / (j - i) as f64;
out.push(if j - i == 1 { polish(coeffs, mean) } else { mean });
i = j;
}
Ok(out)
}
/// A few Newton steps, each accepted only if it reduces |p|.
fn polish(coeffs: &[f64], mut x: f64) -> f64 {
let d = derivative(coeffs);
let mut fx = eval(coeffs, x).abs();
for _ in 0..4 {
let step = eval(coeffs, x) / eval(&d, x);
let y = x - step;
let fy = eval(coeffs, y).abs();
if fy.is_nan() || fy >= fx {
break;
}
(x, fx) = (y, fy);
}
x
}
- Coefficients run from the highest power down, as in MATLAB and NumPy:
[1, 0, -2]is . - The “rounding error” in evaluating by Horner’s rule is bounded by a small multiple of ; values below it carry no information about the sign of .
- The library does not isolate the real roots recursively between the roots of : an implementation of that approach reported critical points as roots (25 “roots” for degree 10) and overflowed at degree 20. It uses the eigenvalue method instead.
In practice
//! Roots of polynomials, real and complex.
//!
//! Run with `cargo run -p lib_jsl_root_finding --example root_finding_polynomial`.
use lib_jsl_root_finding::{polynomial_roots, polynomial_roots_complex};
fn main() {
// Coefficients run from the highest power down: x⁴ − 10x² + 9 = (x² − 1)(x² − 9).
println!("real roots: {:?}", polynomial_roots(&[1.0, 0.0, -10.0, 0.0, 9.0]));
// x³ − 1: one real root and two complex ones.
println!("real roots of x³ − 1: {:?}", polynomial_roots(&[1.0, 0.0, 0.0, -1.0]));
for z in polynomial_roots_complex(&[1.0, 0.0, 0.0, -1.0]).unwrap() {
println!(" complex root {:.6} {:+.6}i", z.re, z.im);
}
// A repeated root is reported once by polynomial_roots, but with its multiplicity (as a
// small cluster) by polynomial_roots_complex: (x − 2)³ = x³ − 6x² + 12x − 8.
println!("(x − 2)³: {:?}", polynomial_roots(&[1.0, -6.0, 12.0, -8.0]));
println!("as eigenvalues: {:?}", polynomial_roots_complex(&[1.0, -6.0, 12.0, -8.0]).unwrap());
}
Strengths
- All roots at once, complex ones included, with no starting guesses.
- Backward stable, using a mature eigenvalue algorithm.
Weaknesses
- cost and memory: for degrees in the thousands, use structured or iterative methods (Aberth-Ehrlich, or eigenvalues of a colleague matrix in the Chebyshev basis).
- Roots of ill-conditioned polynomials are inaccurate, as with any method, and multiple roots are found only to about in the complex output.
- Distinct real roots too close together for to separate in floating point are merged.
Exercises
- Show by expanding the determinant that the characteristic polynomial of the companion matrix is .
- Compute the condition factor for each root of Wilkinson’s polynomial and plot it. Which roots are most sensitive?
- Compute the roots of for with
polynomial_roots_complexand verify that they lie close to a circle of radius proportional to . - The Chebyshev polynomial has well-separated roots . Find them from its monomial coefficients and measure the errors. Why are they so much smaller than for ?
- Find the poles of a Butterworth filter of order 8 as the roots of and check that they lie on a circle.
Hints and answers
- Expand the determinant along the row or column that holds the coefficients, or use induction on : each expansion step contributes one coefficient to the polynomial built so far.
- For , . The factor peaks for at about , with the roots 14 to 17 all above ; the smallest and largest roots are far less sensitive.
- A perturbation of size in the constant term gives , whose roots are : a circle of radius about 1. For and the radius is about .
- For each coefficient the sensitivity of a root is . The roots of lie in and are well separated, so is not small and ; for the roots go up to 20, so the powers are huge while the root spacing is only 1.
- is , so and the sixteen roots are equally spaced on the unit circle, at angles . The eight in the left half-plane are the filter’s poles.
Further reading
- J. H. Wilkinson, “The evaluation of the zeros of ill-conditioned polynomials”, Numerische Mathematik 1 (1959) 150–180, and “The perfidious polynomial”, in Studies in Numerical Analysis, MAA, 1984.
- A. Edelman and H. Murakami, “Polynomial roots from companion matrix eigenvalues”, Mathematics of Computation 64 (1995) 763–776.
- B. N. Parlett and C. Reinsch, “Balancing a matrix for calculation of eigenvalues and eigenvectors”, Numerische Mathematik 13 (1969) 293–304.
- M. A. Jenkins and J. F. Traub, “A three-stage variable-shift iteration for polynomial zeros”, SIAM Journal on Numerical Analysis 7 (1970) 545–566.
- V. Y. Pan, “Solving a polynomial equation: some history and recent progress”, SIAM Review 39 (1997) 187–220.