Skip to main content

lib_jsl_integration/
tanh_sinh.rs

1//! Tanh-sinh (double exponential) quadrature.
2
3use crate::can_integrate::CanIntegrate1D;
4use lib_jsl_core::ErrorsJSL;
5use std::f64::consts::FRAC_PI_2;
6
7/// Integrates over a finite interval with the substitution `x = tanh(π/2 · sinh t)` (Takahasi and
8/// Mori), which makes the transformed integrand decay double exponentially and lets the
9/// trapezoid rule in `t` converge exponentially fast, even for integrable endpoint singularities
10/// such as `1/√x` or `ln x`. The step is halved each level (reusing earlier points) until two
11/// successive estimates agree to the tolerance.
12///
13/// Abscissae are formed from the endpoint distance `(b − a)/(1 + e^{2u})`. Points whose absolute
14/// position rounds onto an endpoint are skipped by [`CanIntegrate1D::integrate`]; for
15/// singularities at endpoints away from zero (such as `1/√(1 − x²)`), use
16/// [`TanhSinhEngine::integrate_with_complement`], which also passes that exact distance so the
17/// integrand can avoid the cancellation in `1 − x`.
18#[derive(Debug, Clone)]
19pub struct TanhSinhEngine {
20    lower_bound: f64,
21    upper_bound: f64,
22    /// Relative tolerance between successive levels (default 1e-12).
23    pub tolerance: f64,
24    /// Maximum number of step halvings (default 10, i.e. h = 2⁻¹⁰).
25    pub max_levels: usize,
26}
27
28/// Half-width of the `t` interval. Because abscissae are formed from endpoint distances, `t` can
29/// run until those distances (about `e^{−π e^t / 2}`) approach the smallest normal double, which
30/// captures the tail mass of strong singularities such as `x^{−1/2}`.
31const T_MAX: f64 = 6.0;
32
33impl TanhSinhEngine {
34    /// A tanh-sinh integrator over `[lower_bound, upper_bound]` with the default tolerance and
35    /// level limit.
36    ///
37    /// ```
38    /// use lib_jsl_integration::tanh_sinh::TanhSinhEngine;
39    ///
40    /// // ∫₀¹ ln(x) dx = −1, with a logarithmic singularity at x = 0.
41    /// let (value, _) = TanhSinhEngine::new(0.0, 1.0).integrate_with_error(f64::ln).unwrap();
42    /// assert!((value + 1.0).abs() < 1e-12);
43    /// ```
44    pub fn new(lower_bound: f64, upper_bound: f64) -> Self {
45        TanhSinhEngine { lower_bound, upper_bound, tolerance: 1e-12, max_levels: 10 }
46    }
47
48    /// The integral together with the difference between the last two levels (an error
49    /// estimate, typically very pessimistic since convergence is exponential).
50    pub fn integrate_with_error<F: Fn(f64) -> f64>(&self, f: F) -> Result<(f64, f64), ErrorsJSL> {
51        let (a, b) = (self.lower_bound, self.upper_bound);
52        self.integrate_with_complement(|x, _| if x == a || x == b { 0.0 } else { f(x) })
53    }
54
55    /// Integrates `f(x, c)`, where `c` is the signed offset of `x` from its nearer endpoint
56    /// (`x − a` in the lower half, `x − b` in the upper half), computed without rounding. Returns
57    /// the integral and an error estimate.
58    pub fn integrate_with_complement<F: Fn(f64, f64) -> f64>(&self, f: F) -> Result<(f64, f64), ErrorsJSL> {
59        let (a, b) = (self.lower_bound, self.upper_bound);
60        if !a.is_finite() || !b.is_finite() {
61            return Err(ErrorsJSL::InvalidInputRange("Tanh-sinh quadrature needs finite bounds."));
62        }
63        if a == b {
64            return Ok((0.0, 0.0));
65        }
66        let width = b - a;
67        // ANCHOR: tanh_sinh_pair
68        // Contribution of the symmetric pair ±t, scaled by the weight.
69        let pair = |t: f64| -> f64 {
70            let u = FRAC_PI_2 * t.sinh();
71            let cosh_u = u.cosh();
72            let weight = FRAC_PI_2 * t.cosh() / (cosh_u * cosh_u);
73            if weight == 0.0 || !weight.is_finite() {
74                return 0.0;
75            }
76            let offset = width / (1.0 + (2.0 * u).exp());
77            if offset == 0.0 {
78                return 0.0;
79            }
80            let mut s = f(a + offset, offset) + f(b - offset, -offset);
81            if t == 0.0 {
82                s *= 0.5;
83            }
84            weight * s
85        };
86        // ANCHOR_END: tanh_sinh_pair
87        // ANCHOR: tanh_sinh_levels
88        let mut h = 1.0;
89        let mut sum: f64 = (0..=(T_MAX as usize)).map(|k| pair(k as f64)).sum();
90        let mut estimate = 0.5 * width * h * sum;
91        let mut error = f64::INFINITY;
92        for _ in 0..self.max_levels {
93            h *= 0.5;
94            // New points are the odd multiples of the halved step.
95            let count = (T_MAX / h) as usize;
96            let new: f64 = (1..=count).step_by(2).map(|k| pair(k as f64 * h)).sum();
97            sum += new;
98            let next = 0.5 * width * h * sum;
99            error = (next - estimate).abs();
100            estimate = next;
101            if error <= self.tolerance * estimate.abs() {
102                break;
103            }
104        }
105        // ANCHOR_END: tanh_sinh_levels
106        Ok((estimate, error))
107    }
108}
109
110impl CanIntegrate1D for TanhSinhEngine {
111    fn set_lower_bound(&mut self, x: f64) {
112        self.lower_bound = x;
113    }
114    fn set_upper_bound(&mut self, x: f64) {
115        self.upper_bound = x;
116    }
117    fn integrate<F>(&self, f: F) -> Result<f64, ErrorsJSL>
118    where
119        F: Fn(f64) -> f64,
120    {
121        self.integrate_with_error(f).map(|(v, _)| v)
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use std::f64::consts::PI;
129
130    #[test]
131    fn handles_endpoint_singularities_to_near_machine_precision() {
132        type Case<'a> = (&'a dyn Fn(f64) -> f64, f64, f64, f64);
133        let cases: [Case; 5] = [
134            (&|x: f64| 1.0 / x.sqrt(), 0.0, 1.0, 2.0),
135            (&|x: f64| x.ln(), 0.0, 1.0, -1.0),
136            (&|x: f64| (x * (1.0 - x)).ln(), 0.0, 1.0, -2.0),
137            (&|x: f64| x.exp(), 0.0, 1.0, std::f64::consts::E - 1.0),
138            (&|x: f64| 1.0 / (1.0 + x * x), -3.0, 5.0, 5f64.atan() + 3f64.atan()),
139        ];
140        for (i, (f, a, b, want)) in cases.iter().enumerate() {
141            let (got, err) = TanhSinhEngine::new(*a, *b).integrate_with_error(f).unwrap();
142            assert!((got - want).abs() < 1e-12 * want.abs().max(1.0), "case {i}: {got} vs {want} (est {err})");
143        }
144    }
145
146    #[test]
147    fn complement_form_resolves_singularities_at_nonzero_endpoints() {
148        // 1/√(1 − x²) = 1/√((1 − x)(1 + x)); the offset c gives 1 ∓ x exactly near ±1.
149        let engine = TanhSinhEngine::new(-1.0, 1.0);
150        let (got, _) = engine
151            .integrate_with_complement(|x, c| {
152                let (one_minus, one_plus) = if c < 0.0 { (-c, 1.0 + x) } else { (1.0 - x, c) };
153                1.0 / (one_minus * one_plus).sqrt()
154            })
155            .unwrap();
156        assert!((got - PI).abs() < 1e-13, "{got}");
157        // The plain form loses only the unresolvable tail next to the endpoints.
158        let plain = engine.integrate(|x| 1.0 / (1.0 - x * x).sqrt()).unwrap();
159        assert!((plain - PI).abs() < 1e-6, "{plain}");
160    }
161
162    #[test]
163    fn reversed_and_degenerate_intervals() {
164        let mut e = TanhSinhEngine::new(2.0, 0.0);
165        assert!((e.integrate(|x| x * x).unwrap() + 8.0 / 3.0).abs() < 1e-13);
166        e.set_upper_bound(2.0);
167        assert_eq!(e.integrate(|x| x).unwrap(), 0.0);
168        assert!(TanhSinhEngine::new(0.0, f64::INFINITY).integrate(|x| x).is_err());
169    }
170}