Skip to main content

lib_jsl_number_theory/
polynomial.rs

1//! Polynomial evaluation, construction from roots, and roots by companion-matrix eigenvalues.
2//!
3//! See the book entry [Polynomials and decimal-string integers](https://jwkunz.github.io/lib_jsl/book/number-theory/polynomials.html).
4
5use ndarray::{Array1, Array2};
6use lib_jsl_linalg::Eig;
7use num_complex::Complex;
8
9use lib_jsl_core::{C1D, ErrorsJSL, IsAnalytic};
10
11/// Evaluate a polynomial at `x` using Horner's rule.
12///
13/// The coefficient slice is interpreted in descending powers, so
14/// `[a0, a1, ..., an]` represents:
15///
16/// `a0*x^n + a1*x^(n-1) + ... + an`
17pub fn polynomial_eval<T: IsAnalytic>(coeffs: &[T], x: Complex<f64>) -> Complex<f64> {
18    let mut acc = Complex::new(0.0, 0.0);
19    for coeff in coeffs {
20        acc = acc * x + coeff.to_complex();
21    }
22    acc
23}
24
25/// Form a monic polynomial from its roots.
26///
27/// The returned coefficients are in descending powers.
28pub fn polynomial_from_roots(roots: &[Complex<f64>]) -> C1D {
29    let mut coeffs = vec![Complex::new(1.0, 0.0)];
30    for &root in roots {
31        let mut next = vec![Complex::new(0.0, 0.0); coeffs.len() + 1];
32        for (i, &coeff) in coeffs.iter().enumerate() {
33            next[i] += coeff;
34            next[i + 1] -= coeff * root;
35        }
36        coeffs = next;
37    }
38    Array1::from_vec(coeffs)
39}
40
41/// Compute the roots of a polynomial using a companion-matrix eigenvalue solve.
42///
43/// The coefficient slice is interpreted in descending powers, so
44/// `[a0, a1, ..., an]` represents:
45///
46/// `a0*x^n + a1*x^(n-1) + ... + an`
47pub fn polynomial_roots<T: IsAnalytic>(coeffs: &[T]) -> Result<C1D, ErrorsJSL> {
48    if coeffs.is_empty() {
49        return Err(ErrorsJSL::InvalidInputRange(
50            "polynomial coefficients must be non-empty",
51        ));
52    }
53    if coeffs.len() == 1 {
54        return Ok(Array1::from_vec(vec![]));
55    }
56
57    let lead = coeffs[0].to_complex();
58    if lead.norm_sqr() <= 1e-24 {
59        return Err(ErrorsJSL::InvalidInputRange(
60            "leading polynomial coefficient must be non-zero",
61        ));
62    }
63
64    // ANCHOR: companion
65    let order = coeffs.len() - 1;
66    let mut companion = Array2::from_elem((order, order), Complex::new(0.0, 0.0));
67    for row in 1..order {
68        companion[[row, row - 1]] = Complex::new(1.0, 0.0);
69    }
70    for row in 0..order {
71        companion[[row, order - 1]] = -coeffs[order - row].to_complex() / lead;
72    }
73    // ANCHOR_END: companion
74
75    let (evals, _) = companion
76        .eig()
77        .map_err(|_| ErrorsJSL::RuntimeError("failed to compute polynomial roots"))?;
78    Ok(evals)
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    fn sort_by_real_then_imag(values: &mut [Complex<f64>]) {
86        values.sort_by(|a, b| {
87            a.re
88                .partial_cmp(&b.re)
89                .unwrap_or(std::cmp::Ordering::Equal)
90                .then_with(|| {
91                    a.im
92                        .partial_cmp(&b.im)
93                        .unwrap_or(std::cmp::Ordering::Equal)
94                })
95        });
96    }
97
98    #[test]
99    fn test_polynomial_eval_quadratic() {
100        let coeffs = [1.0, -3.0, 2.0];
101        let value = polynomial_eval(&coeffs, Complex::new(2.0, 0.0));
102        assert!(value.norm() < 1e-12);
103    }
104
105    #[test]
106    fn test_polynomial_from_roots() {
107        let roots = [Complex::new(1.0, 0.0), Complex::new(2.0, 0.0)];
108        let coeffs = polynomial_from_roots(&roots);
109        assert_eq!(coeffs.len(), 3);
110        assert!((coeffs[0] - Complex::new(1.0, 0.0)).norm() < 1e-12);
111        assert!((coeffs[1] - Complex::new(-3.0, 0.0)).norm() < 1e-12);
112        assert!((coeffs[2] - Complex::new(2.0, 0.0)).norm() < 1e-12);
113    }
114
115    #[test]
116    fn test_polynomial_roots_quadratic() {
117        let coeffs = [1.0, -3.0, 2.0];
118        let mut roots = polynomial_roots(&coeffs).unwrap().to_vec();
119        let mut expected = vec![Complex::new(1.0, 0.0), Complex::new(2.0, 0.0)];
120        sort_by_real_then_imag(&mut roots);
121        sort_by_real_then_imag(&mut expected);
122
123        for (actual, expected) in roots.iter().zip(expected.iter()) {
124            assert!((*actual - *expected).norm() < 1e-9);
125        }
126    }
127}