lib_jsl_number_theory/
polynomial.rs1use ndarray::{Array1, Array2};
6use lib_jsl_linalg::Eig;
7use num_complex::Complex;
8
9use lib_jsl_core::{C1D, ErrorsJSL, IsAnalytic};
10
11pub 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
25pub 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
41pub 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 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 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}