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