lib_jsl_integration/
tanh_sinh.rs1use crate::can_integrate::CanIntegrate1D;
4use lib_jsl_core::ErrorsJSL;
5use std::f64::consts::FRAC_PI_2;
6
7#[derive(Debug, Clone)]
19pub struct TanhSinhEngine {
20 lower_bound: f64,
21 upper_bound: f64,
22 pub tolerance: f64,
24 pub max_levels: usize,
26}
27
28const T_MAX: f64 = 6.0;
32
33impl TanhSinhEngine {
34 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 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 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 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 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 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 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 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 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}