Skip to main content

lib_jsl_interpolation/one_d/
pade_approximants.rs

1//! Padé approximants built from Taylor series coefficients.
2//!
3//! See the book entry [Rational interpolation and approximation](https://jwkunz.github.io/lib_jsl/book/interpolation/rational.html#padé-approximants).
4
5use lib_jsl_core::*;
6use ndarray::{Array1, Array2};
7use lib_jsl_linalg::Solve;
8
9/// The `[L/M]` Padé approximant `P(x)/Q(x)` with `deg P <= L`, `deg Q <= M`, `Q(0) = 1`, whose
10/// Taylor series matches the given one through order `L + M`.
11#[derive(Debug, Clone)]
12pub struct PadeApproximant {
13    numerator: Vec<f64>,
14    denominator: Vec<f64>,
15}
16
17impl PadeApproximant {
18    /// Builds the `[l/m]` approximant from Taylor coefficients `c[0..=l+m]` (lowest order first).
19    pub fn new(taylor: &[f64], l: usize, m: usize) -> Result<Self, ErrorsJSL> {
20        if taylor.len() < l + m + 1 {
21            return Err(ErrorsJSL::IncompatibleArraySizes((taylor.len(), l + m + 1)));
22        }
23        let c = |k: isize| if k < 0 { 0.0 } else { taylor[k as usize] };
24        let mut q = vec![1.0];
25        if m > 0 {
26            // Σ_{j=1..m} q_j c_{L+i-j} = -c_{L+i}, i = 1..m.
27            let a = Array2::from_shape_fn((m, m), |(i, j)| c((l + i + 1) as isize - (j + 1) as isize));
28            let b = Array1::from_shape_fn(m, |i| -c((l + i + 1) as isize));
29            let sol = a.solve(&b).map_err(|_| ErrorsJSL::RuntimeError("singular Padé system"))?;
30            q.extend(sol.iter());
31        }
32        let p = (0..=l)
33            .map(|i| (0..=i.min(m)).map(|j| q[j] * c((i - j) as isize)).sum())
34            .collect();
35        Ok(PadeApproximant { numerator: p, denominator: q })
36    }
37
38    /// Numerator coefficients, lowest order first.
39    pub fn numerator(&self) -> &[f64] {
40        &self.numerator
41    }
42
43    /// Denominator coefficients, lowest order first (`denominator()[0] == 1`).
44    pub fn denominator(&self) -> &[f64] {
45        &self.denominator
46    }
47
48    /// Evaluates `P(x) / Q(x)` by Horner's rule.
49    pub fn evaluate(&self, x: f64) -> f64 {
50        let horner = |c: &[f64]| c.iter().rev().fold(0.0, |acc, &k| acc * x + k);
51        horner(&self.numerator) / horner(&self.denominator)
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn exp_pade_2_2_known_coefficients() {
61        // exp(x) series: 1, 1, 1/2, 1/6, 1/24 -> [2/2] = (1 + x/2 + x²/12)/(1 - x/2 + x²/12)
62        let t = [1.0, 1.0, 0.5, 1.0 / 6.0, 1.0 / 24.0];
63        let p = PadeApproximant::new(&t, 2, 2).unwrap();
64        for (a, b) in p.numerator().iter().zip([1.0, 0.5, 1.0 / 12.0]) {
65            assert!((a - b).abs() < 1e-12);
66        }
67        for (a, b) in p.denominator().iter().zip([1.0, -0.5, 1.0 / 12.0]) {
68            assert!((a - b).abs() < 1e-12);
69        }
70        assert!((p.evaluate(1.0) - 19.0 / 7.0).abs() < 1e-12);
71    }
72
73    #[test]
74    fn beats_the_taylor_polynomial_beyond_its_radius() {
75        // ln(1+x) at x = 3 is outside the Taylor radius; the [4/4] approximant still works.
76        let t: Vec<f64> = (0..9).map(|k| if k == 0 { 0.0 } else { (-1.0f64).powi(k + 1) / k as f64 }).collect();
77        let p = PadeApproximant::new(&t, 4, 4).unwrap();
78        assert!((p.evaluate(3.0) - 4.0f64.ln()).abs() < 5e-3);
79    }
80
81    #[test]
82    fn pure_polynomial_when_m_is_zero() {
83        let p = PadeApproximant::new(&[1.0, 2.0, 3.0], 2, 0).unwrap();
84        assert_eq!(p.evaluate(2.0), 17.0);
85        assert!(PadeApproximant::new(&[1.0], 2, 2).is_err());
86    }
87}