Skip to main content

lib_jsl_interpolation/one_d/
krogh.rs

1//! Krogh's interpolating polynomial through values and derivatives (SciPy's
2//! `KroghInterpolator`): a node repeated `s + 1` times carries the value and the first `s`
3//! derivatives there. The polynomial is kept in Newton form, whose coefficients are confluent
4//! divided differences.
5//!
6//! See the book entry [Piecewise polynomials, Hermite data and scattered interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/piecewise-scattered.html#hermite-data-krogh-and-cubic-hermite-splines).
7
8use lib_jsl_core::ErrorsJSL;
9
10/// The polynomial of degree `n − 1` through `n` conditions.
11#[derive(Clone, Debug, PartialEq)]
12pub struct KroghInterpolator {
13    xi: Vec<f64>,
14    /// Newton coefficients `c₀, …, c_{n−1}`: `p(x) = c₀ + c₁(x − x₀) + c₂(x − x₀)(x − x₁) + …`.
15    c: Vec<f64>,
16}
17
18fn factorial(s: usize) -> f64 {
19    (1..=s).map(|i| i as f64).product()
20}
21
22impl KroghInterpolator {
23    // ANCHOR: krogh
24    /// Builds the interpolant. `xi` lists the nodes with each repeated node consecutive; `yi[k]`
25    /// is the value at `xi[k]` if it is the first copy, else the derivative whose order is the
26    /// number of earlier copies. Divided differences with repeated nodes become derivatives
27    /// divided by factorials, which is how `Vk[0] = yᵢ/s!` enters.
28    pub fn new(xi: &[f64], yi: &[f64]) -> Result<KroghInterpolator, ErrorsJSL> {
29        let n = xi.len();
30        if n == 0 || yi.len() != n {
31            return Err(ErrorsJSL::InvalidInputRange("need one value per node"));
32        }
33        let mut c = vec![0.0; n];
34        c[0] = yi[0];
35        let mut vk = vec![0.0; n];
36        for k in 1..n {
37            let mut s = 0;
38            while s <= k && xi[k - s] == xi[k] {
39                s += 1;
40            }
41            s -= 1;
42            vk[0] = yi[k] / factorial(s);
43            for i in 0..k - s {
44                if xi[i] == xi[k] {
45                    return Err(ErrorsJSL::InvalidInputRange("copies of a node must be consecutive"));
46                }
47                vk[i + 1] = if s == 0 { (c[i] - vk[i]) / (xi[i] - xi[k]) } else { (vk[i + 1] - vk[i]) / (xi[i] - xi[k]) };
48            }
49            c[k] = vk[k - s];
50        }
51        Ok(KroghInterpolator { xi: xi.to_vec(), c })
52    }
53    // ANCHOR_END: krogh
54
55    /// The value at `x`, by nested multiplication of the Newton form.
56    pub fn evaluate(&self, x: f64) -> f64 {
57        let n = self.c.len();
58        let mut p = self.c[n - 1];
59        for k in (0..n - 1).rev() {
60            p = p * (x - self.xi[k]) + self.c[k];
61        }
62        p
63    }
64
65    /// The value and the first `count − 1` derivatives at `x` (SciPy's `derivatives`), by
66    /// SciPy's recurrence on the products `Π (x − xᵢ)`.
67    pub fn derivatives(&self, x: f64, count: usize) -> Vec<f64> {
68        let n = self.c.len();
69        let mut pi = vec![0.0; n];
70        let mut w = vec![0.0; n];
71        pi[0] = 1.0;
72        let mut p = self.c[0];
73        for k in 1..n {
74            w[k - 1] = x - self.xi[k - 1];
75            pi[k] = w[k - 1] * pi[k - 1];
76            p += pi[k] * self.c[k];
77        }
78        let mut cn = vec![0.0; count.max(n + 1)];
79        cn[..n].copy_from_slice(&self.c);
80        cn[0] = p;
81        for k in 1..n {
82            for i in 1..n - k + 1 {
83                pi[i] += w[k + i - 1] * pi[i - 1];
84                cn[k] += pi[i] * cn[k + i];
85            }
86            cn[k] *= factorial(k);
87        }
88        cn[n] = 0.0;
89        cn.truncate(count);
90        cn
91    }
92
93    /// The `nu`-th derivative at `x`.
94    pub fn derivative(&self, x: f64, nu: usize) -> f64 {
95        self.derivatives(x, nu + 1)[nu]
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn hermite_conditions_are_met() {
105        // p(0) = 1, p'(0) = 2, p(1) = 0, p'(1) = −1, p''(1) = 4: a quartic.
106        let k = KroghInterpolator::new(&[0.0, 0.0, 1.0, 1.0, 1.0], &[1.0, 2.0, 0.0, -1.0, 4.0]).unwrap();
107        assert!((k.evaluate(0.0) - 1.0).abs() < 1e-14);
108        assert!((k.derivative(0.0, 1) - 2.0).abs() < 1e-13);
109        assert!(k.evaluate(1.0).abs() < 1e-14);
110        assert!((k.derivative(1.0, 1) + 1.0).abs() < 1e-13);
111        assert!((k.derivative(1.0, 2) - 4.0).abs() < 1e-12);
112        assert_eq!(k.derivative(0.3, 5), 0.0);
113    }
114
115    #[test]
116    fn plain_nodes_reproduce_a_polynomial() {
117        let f = |x: f64| 2.0 * x.powi(3) - x + 0.5;
118        let xi = [-1.0, 0.2, 0.9, 2.0];
119        let k = KroghInterpolator::new(&xi, &xi.map(f)).unwrap();
120        let d = k.derivatives(0.7, 5);
121        assert!((d[0] - f(0.7)).abs() < 1e-13);
122        assert!((d[1] - (6.0 * 0.49 - 1.0)).abs() < 1e-12);
123        assert!((d[2] - 6.0 * 2.0 * 0.7).abs() < 1e-12);
124        assert!((d[3] - 12.0).abs() < 1e-12);
125        assert_eq!(d[4], 0.0);
126    }
127}