Skip to main content

lib_jsl_interpolation/one_d/
floater_hormann.rs

1//! Floater-Hormann rational interpolation (barycentric, no poles on the real line).
2//!
3//! See the book entry [Rational interpolation and approximation](https://jwkunz.github.io/lib_jsl/book/interpolation/rational.html#floater-hormann-interpolation).
4
5use super::lagrange_interpolant::barycentric_eval;
6use crate::interpolation_trait::InterpolationTrait;
7use lib_jsl_core::*;
8
9/// Rational interpolant of blending degree `d` (0 <= d <= n-1) through points with strictly
10/// increasing abscissae. `d = 0` is Berrut's interpolant; `d = n-1` is the polynomial interpolant.
11/// Convergence is O(h^(d+1)) for smooth functions on any node distribution.
12#[derive(Debug)]
13pub struct FloaterHormann<'a> {
14    x_values: VR1D<'a>,
15    y_values: VR1D<'a>,
16    weights: R1D,
17}
18
19impl<'a> FloaterHormann<'a> {
20    pub fn new(x_values: VR1D<'a>, y_values: VR1D<'a>, d: usize) -> Result<Self, ErrorsJSL> {
21        let mut r = FloaterHormann { x_values, y_values, weights: R1D::zeros(0) };
22        r.verify_sizes(1)?;
23        let n = x_values.len();
24        if d >= n {
25            return Err(ErrorsJSL::InvalidInputRange("blending degree must be below the point count"));
26        }
27        if x_values.iter().zip(x_values.iter().skip(1)).any(|(a, b)| b <= a) {
28            return Err(ErrorsJSL::InvalidInputRange("x values must be strictly increasing"));
29        }
30        // w_i = (-1)^(i-d) * sum over k in [i-d, i] (k in 0..n-d) of prod_{j=k..k+d, j != i} 1/|x_i - x_j|
31        let mut w = R1D::zeros(n);
32        for i in 0..n {
33            let lo = i.saturating_sub(d);
34            let hi = i.min(n - 1 - d);
35            let mut sum = 0.0;
36            for k in lo..=hi {
37                let mut prod = 1.0;
38                for j in k..=k + d {
39                    if j != i {
40                        prod /= (x_values[i] - x_values[j]).abs();
41                    }
42                }
43                sum += prod;
44            }
45            w[i] = if (i + d).is_multiple_of(2) { sum } else { -sum };
46        }
47        r.weights = w;
48        Ok(r)
49    }
50}
51
52impl<'a> InterpolationTrait<'a> for FloaterHormann<'a> {
53    fn get_x_values(&self) -> VR1D<'a> {
54        self.x_values
55    }
56    fn set_x_values(&mut self, x: VR1D<'a>) {
57        self.x_values = x;
58    }
59    fn get_y_values(&self) -> VR1D<'a> {
60        self.y_values
61    }
62    fn set_y_values(&mut self, y: VR1D<'a>) {
63        self.y_values = y;
64    }
65    fn get_cached_location(&self) -> Option<usize> {
66        None
67    }
68    fn set_cached_location(&mut self, _: usize) {}
69    fn raw_interpolate(&mut self, _: usize, _: f64) -> Result<f64, ErrorsJSL> {
70        Err(ErrorsJSL::NotImplementedYet)
71    }
72    fn interpolate_at(&mut self, x: f64) -> Result<f64, ErrorsJSL> {
73        Ok(barycentric_eval(self.x_values, self.y_values, self.weights.view(), x))
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::one_d::lagrange_interpolant::LagrangeInterpolant;
81
82    #[test]
83    fn runge_function_equispaced_is_stable() -> Result<(), ErrorsJSL> {
84        // Runge's function on 41 equispaced points: the polynomial interpolant explodes, FH does not.
85        let n = 41;
86        let x = R1D::from_iter((0..n).map(|k| -1.0 + 2.0 * k as f64 / (n - 1) as f64));
87        let f = |v: f64| 1.0 / (1.0 + 25.0 * v * v);
88        let y = x.mapv(f);
89        let mut fh = FloaterHormann::new(x.view(), y.view(), 5)?;
90        let mut poly = LagrangeInterpolant::new(x.view(), y.view())?;
91        let (mut e_fh, mut e_poly): (f64, f64) = (0.0, 0.0);
92        for k in 0..=400 {
93            let v = -1.0 + 2.0 * (k as f64 + 0.37) / 401.0;
94            e_fh = e_fh.max((fh.interpolate_at(v)? - f(v)).abs());
95            e_poly = e_poly.max((poly.interpolate_at(v)? - f(v)).abs());
96        }
97        assert!(e_fh < 1e-4, "fh error {e_fh}");
98        assert!(e_poly > 10.0 * e_fh, "poly error {e_poly}");
99        Ok(())
100    }
101
102    #[test]
103    fn full_degree_equals_polynomial_and_nodes_exact() -> Result<(), ErrorsJSL> {
104        let x = R1D::from_vec(vec![0.0, 0.7, 1.5, 2.0, 3.1]);
105        let y = R1D::from_vec(vec![1.0, -2.0, 0.5, 4.0, 3.0]);
106        let mut fh = FloaterHormann::new(x.view(), y.view(), 4)?;
107        let mut lg = LagrangeInterpolant::new(x.view(), y.view())?;
108        for &v in &[0.3, 1.1, 2.6] {
109            assert!((fh.interpolate_at(v)? - lg.interpolate_at(v)?).abs() < 1e-10);
110        }
111        assert_eq!(fh.interpolate_at(1.5)?, 0.5);
112        Ok(())
113    }
114}