Coverage Report

Created: 2025-08-26 06:41

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