Skip to main content

lib_jsl_root_finding/
polynomial_roots.rs

1//! Polynomial roots as the eigenvalues of the companion matrix: all (complex) roots, or the
2//! real ones, polished and with repeated roots merged.
3//!
4//! See the book entry [Polynomial roots](https://jwkunz.github.io/lib_jsl/book/root_finding/polynomial-roots.html).
5
6use lib_jsl_core::ErrorsJSL;
7use lib_jsl_linalg::EigVals;
8use ndarray::Array2;
9use num_complex::Complex;
10
11fn eval(coeffs: &[f64], x: f64) -> f64 {
12    coeffs.iter().fold(0.0, |acc, &c| acc * x + c)
13}
14
15/// `Σ |aᵢ| |x|^(n−i)`, the scale of rounding errors in evaluating the polynomial at `x`.
16fn eval_abs(coeffs: &[f64], x: f64) -> f64 {
17    coeffs.iter().fold(0.0, |acc, &c| acc * x.abs() + c.abs())
18}
19
20fn derivative(coeffs: &[f64]) -> Vec<f64> {
21    let n = coeffs.len() - 1;
22    coeffs[..n].iter().enumerate().map(|(i, &c)| c * (n - i) as f64).collect()
23}
24
25/// Strips leading zero coefficients and factors out roots at zero; returns the reduced
26/// coefficients and the multiplicity of the zero root.
27fn normalise(coeffs: &[f64]) -> Option<(&[f64], usize)> {
28    let start = coeffs.iter().position(|&c| c != 0.0)?;
29    let mut c = &coeffs[start..];
30    let mut zeros = 0;
31    while c.len() > 1 && *c.last().unwrap() == 0.0 {
32        c = &c[..c.len() - 1];
33        zeros += 1;
34    }
35    Some((c, zeros))
36}
37
38/// Returns the real roots of a polynomial in ascending order.
39///
40/// `coeffs` are ordered from the highest degree to the constant term, e.g. `[1, 0, -2]` is
41/// `x^2 - 2`. The roots are the real eigenvalues of the companion matrix (see
42/// [`polynomial_roots_complex`]), each polished by Newton's method; an eigenvalue with an imaginary
43/// part below `10⁻³ |z|` counts as real when the polynomial vanishes at its real part to within
44/// rounding error. A repeated root, which appears as a cluster of nearby eigenvalues, is reported once, at
45/// the cluster's mean (accurate to about `ε^(1/m)` for multiplicity `m`, often much better).
46/// Distinct roots closer together than the rounding error of the polynomial can resolve are merged.
47pub fn polynomial_roots(coeffs: &[f64]) -> Vec<f64> {
48    let Some((reduced, zeros)) = normalise(coeffs) else { return Vec::new() };
49    // The QR iteration has never been observed to fail on a companion matrix; if it did, there
50    // would be no roots to report.
51    let mut r = real_roots(reduced).unwrap_or_default();
52    if zeros > 0 {
53        r.push(0.0);
54    }
55    r.sort_by(f64::total_cmp);
56    r.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * (1.0 + a.abs()));
57    r
58}
59
60// ANCHOR: real_roots
61fn real_roots(coeffs: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
62    let deg = coeffs.len() - 1;
63    match deg {
64        0 => return Ok(Vec::new()),
65        1 => return Ok(vec![-coeffs[1] / coeffs[0]]),
66        _ => {}
67    }
68    // The rounding error in evaluating p at x: below it, the value of p(x) means nothing.
69    let noise = |x: f64| 8.0 * deg as f64 * f64::EPSILON * eval_abs(coeffs, x);
70    let mut eig = companion_eigenvalues(coeffs)?;
71    // A real eigenvalue is a real root; a nearly real pair is a multiple real root perturbed by
72    // rounding (by about ε^(1/m)), if p vanishes at its real part to within rounding error.
73    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)));
74    eig.sort_by(|a, b| a.re.total_cmp(&b.re));
75    // Group eigenvalues that p cannot tell apart: close together, with p in the noise between.
76    let mut out = Vec::new();
77    let mut i = 0;
78    while i < eig.len() {
79        let mut j = i + 1;
80        while j < eig.len() {
81            let (a, b) = (eig[j - 1].re, eig[j].re);
82            let mid = 0.5 * (a + b);
83            if b - a > 1e-3 * mid.abs().max(1.0) || eval(coeffs, mid).abs() > noise(mid) {
84                break;
85            }
86            j += 1;
87        }
88        let mean = eig[i..j].iter().map(|z| z.re).sum::<f64>() / (j - i) as f64;
89        out.push(if j - i == 1 { polish(coeffs, mean) } else { mean });
90        i = j;
91    }
92    Ok(out)
93}
94
95/// A few Newton steps, each accepted only if it reduces |p|.
96fn polish(coeffs: &[f64], mut x: f64) -> f64 {
97    let d = derivative(coeffs);
98    let mut fx = eval(coeffs, x).abs();
99    for _ in 0..4 {
100        let step = eval(coeffs, x) / eval(&d, x);
101        let y = x - step;
102        let fy = eval(coeffs, y).abs();
103        if fy.is_nan() || fy >= fx {
104            break;
105        }
106        (x, fx) = (y, fy);
107    }
108    x
109}
110// ANCHOR_END: real_roots
111
112fn companion_eigenvalues(coeffs: &[f64]) -> Result<Vec<Complex<f64>>, String> {
113    let n = coeffs.len() - 1;
114    // ANCHOR: companion
115    // p(z)/a₀ = zⁿ + c₁ zⁿ⁻¹ + … + cₙ is the characteristic polynomial of this matrix.
116    let mut companion = Array2::<f64>::zeros((n, n));
117    for j in 0..n {
118        companion[[0, j]] = -coeffs[j + 1] / coeffs[0];
119    }
120    for i in 1..n {
121        companion[[i, i - 1]] = 1.0;
122    }
123    let values = companion.eigvals().map_err(|e| format!("polynomial_roots_complex: {e:?}"))?;
124    // ANCHOR_END: companion
125    Ok(values.to_vec())
126}
127
128/// All roots of a polynomial, complex ones included, as the eigenvalues of its companion matrix
129/// (the method of MATLAB's `roots`), sorted by real part and then imaginary part. Repeated roots
130/// appear with their multiplicity (and, being ill-conditioned, are accurate only to about
131/// `ε^(1/m)` for multiplicity `m`).
132pub fn polynomial_roots_complex(coeffs: &[f64]) -> Result<Vec<Complex<f64>>, String> {
133    let Some((coeffs, zeros)) = normalise(coeffs) else { return Ok(Vec::new()) };
134    let mut roots = vec![Complex::new(0.0, 0.0); zeros];
135    if coeffs.len() > 1 {
136        roots.extend(companion_eigenvalues(coeffs)?);
137    }
138    roots.sort_by(|a, b| a.re.total_cmp(&b.re).then(a.im.total_cmp(&b.im)));
139    Ok(roots)
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn quadratic() {
148        let r = polynomial_roots(&[1.0, 0.0, -2.0]);
149        assert_eq!(r.len(), 2);
150        assert!((r[0] + 2f64.sqrt()).abs() < 1e-10);
151        assert!((r[1] - 2f64.sqrt()).abs() < 1e-10);
152    }
153
154    #[test]
155    fn cubic_three_real() {
156        // (x-1)(x-2)(x-3)
157        let r = polynomial_roots(&[1.0, -6.0, 11.0, -6.0]);
158        assert_eq!(r.len(), 3);
159        for (got, want) in r.iter().zip([1.0, 2.0, 3.0]) {
160            assert!((got - want).abs() < 1e-9);
161        }
162    }
163
164    #[test]
165    fn no_real_roots() {
166        assert!(polynomial_roots(&[1.0, 0.0, 1.0]).is_empty());
167    }
168
169    #[test]
170    fn zero_root_and_leading_zero() {
171        // 0*x^3 + x^2 - x
172        let r = polynomial_roots(&[0.0, 1.0, -1.0, 0.0]);
173        assert_eq!(r.len(), 2);
174        assert!(r[0].abs() < 1e-12 && (r[1] - 1.0).abs() < 1e-10);
175    }
176
177    #[test]
178    fn repeated_root() {
179        // (x-1)^2
180        let r = polynomial_roots(&[1.0, -2.0, 1.0]);
181        assert_eq!(r.len(), 1);
182        assert!((r[0] - 1.0).abs() < 1e-6);
183    }
184
185    fn poly_from_roots(r: &[f64]) -> Vec<f64> {
186        let mut c = vec![1.0];
187        for &x in r {
188            let mut n = vec![0.0; c.len() + 1];
189            for (i, &a) in c.iter().enumerate() {
190                n[i] += a;
191                n[i + 1] -= a * x;
192            }
193            c = n;
194        }
195        c
196    }
197
198    #[test]
199    fn wilkinson_polynomials_give_exactly_their_roots() {
200        // The old isolation between critical points accepted critical points as roots (25 roots at
201        // degree 10) and its bound overflowed at degree 20; without balancing, the companion
202        // eigenvalues of the degree-20 polynomial were garbage.
203        for (n, tol) in [(10usize, 1e-9), (15, 1e-3), (20, 1e-2)] {
204            let roots: Vec<f64> = (1..=n).map(|k| k as f64).collect();
205            let found = polynomial_roots(&poly_from_roots(&roots));
206            assert_eq!(found.len(), n, "degree {n}: {found:?}");
207            let err = found.iter().zip(&roots).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
208            // Wilkinson's roots are ill-conditioned: errors grow quickly with the degree.
209            assert!(err < tol, "degree {n}: error {err:e}");
210        }
211        // Wilkinson's perturbation: 2⁻²³ off the x¹⁹ coefficient leaves ten real roots.
212        let mut w = poly_from_roots(&(1..=20).map(|k| k as f64).collect::<Vec<_>>());
213        w[1] -= 2f64.powi(-23);
214        let found = polynomial_roots(&w);
215        assert_eq!(found.len(), 10, "{found:?}");
216        assert!((found[9] - 20.8469).abs() < 1e-3, "{found:?}");
217        let r = polynomial_roots(&poly_from_roots(&[1.0, 1.0, 1.0]));
218        assert!(r.len() == 1 && (r[0] - 1.0).abs() < 1e-12, "{r:?}");
219    }
220
221    #[test]
222    fn complex_roots_from_the_companion_matrix() {
223        let r = polynomial_roots_complex(&[1.0, 0.0, 1.0]).unwrap();
224        assert!((r[0] - Complex::new(0.0, -1.0)).norm() < 1e-14 && (r[1] - Complex::new(0.0, 1.0)).norm() < 1e-14);
225        // x^4 + 1: the four primitive eighth roots of unity.
226        let r = polynomial_roots_complex(&[1.0, 0.0, 0.0, 0.0, 1.0]).unwrap();
227        assert!(r.iter().all(|z| (z.norm() - 1.0).abs() < 1e-14 && (z.powu(4) + 1.0).norm() < 1e-13));
228        // Leading and trailing zeros: 0·x³ + x² − x = x(x − 1).
229        let r = polynomial_roots_complex(&[0.0, 1.0, -1.0, 0.0]).unwrap();
230        assert_eq!(r.len(), 2);
231        assert!(r[0].norm() < 1e-15 && (r[1] - 1.0).norm() < 1e-14);
232    }
233}