1 use super::expm1; 2 3 /* tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x)) 4 * = (exp(2*x) - 1)/(exp(2*x) - 1 + 2) 5 * = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2) 6 */ 7 8 /// The hyperbolic tangent of `x` (f64). 9 /// 10 /// `x` is specified in radians. 11 #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] tanh(mut x: f64) -> f6412pub fn tanh(mut x: f64) -> f64 { 13 let mut uf: f64 = x; 14 let mut ui: u64 = f64::to_bits(uf); 15 16 let w: u32; 17 let sign: bool; 18 let mut t: f64; 19 20 /* x = |x| */ 21 sign = ui >> 63 != 0; 22 ui &= !1 / 2; 23 uf = f64::from_bits(ui); 24 x = uf; 25 w = (ui >> 32) as u32; 26 27 if w > 0x3fe193ea { 28 /* |x| > log(3)/2 ~= 0.5493 or nan */ 29 if w > 0x40340000 { 30 /* |x| > 20 or nan */ 31 /* note: this branch avoids raising overflow */ 32 t = 1.0 - 0.0 / x; 33 } else { 34 t = expm1(2.0 * x); 35 t = 1.0 - 2.0 / (t + 2.0); 36 } 37 } else if w > 0x3fd058ae { 38 /* |x| > log(5/3)/2 ~= 0.2554 */ 39 t = expm1(2.0 * x); 40 t = t / (t + 2.0); 41 } else if w >= 0x00100000 { 42 /* |x| >= 0x1p-1022, up to 2ulp error in [0.1,0.2554] */ 43 t = expm1(-2.0 * x); 44 t = -t / (t + 2.0); 45 } else { 46 /* |x| is subnormal */ 47 /* note: the branch above would not raise underflow in [0x1p-1023,0x1p-1022) */ 48 force_eval!(x as f32); 49 t = x; 50 } 51 52 if sign { -t } else { t } 53 } 54