1 /*
2 * Single-precision vector tanh(x) function.
3 *
4 * Copyright (c) 2022-2023, Arm Limited.
5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6 */
7
8 #include "v_math.h"
9 #include "pl_sig.h"
10 #include "pl_test.h"
11
12 #if V_SUPPORTED
13
14 #include "v_expm1f_inline.h"
15
16 #define BoringBound \
17 0x41102cb3 /* 0x1.205966p+3, above which tanhf rounds to 1 (or -1 for \
18 negative). */
19 #define AbsMask 0x7fffffff
20
21 static NOINLINE v_f32_t
special_case(v_f32_t x,v_f32_t y,v_u32_t special)22 special_case (v_f32_t x, v_f32_t y, v_u32_t special)
23 {
24 return v_call_f32 (tanhf, x, y, special);
25 }
26
27 /* Approximation for single-precision vector tanh(x), using a simplified version
28 of expm1f. The maximum error is 2.58 ULP:
29 __v_tanhf(0x1.fa5eep-5) got 0x1.f9ba02p-5
30 want 0x1.f9ba08p-5. */
V_NAME(tanhf)31 VPCS_ATTR v_f32_t V_NAME (tanhf) (v_f32_t x)
32 {
33 v_u32_t ix = v_as_u32_f32 (x);
34 v_u32_t iax = ix & AbsMask;
35 v_u32_t sign = ix & ~AbsMask;
36 v_u32_t is_boring = v_cond_u32 (iax > BoringBound);
37 v_f32_t boring = v_as_f32_u32 (sign | One);
38
39 #if WANT_SIMD_EXCEPT
40 /* If fp exceptions are to be triggered properly, set all special and boring
41 lanes to 1, which will trigger no exceptions, and fix them up later. */
42 v_u32_t special = v_cond_u32 ((iax > 0x7f800000) | (iax < 0x34000000));
43 ix = v_sel_u32 (is_boring, v_u32 (One), ix);
44 if (unlikely (v_any_u32 (special)))
45 ix = v_sel_u32 (special, v_u32 (One), ix);
46 #else
47 v_u32_t special = v_cond_u32 ((iax > 0x7f800000) | (iax == 0));
48 #endif
49
50 /* tanh(x) = (e^2x - 1) / (e^2x + 1). */
51 v_f32_t q = expm1f_inline (2 * v_as_f32_u32 (ix));
52 v_f32_t y = q / (q + 2);
53 y = v_sel_f32 (is_boring, boring, y);
54 if (unlikely (v_any_u32 (special)))
55 return special_case (x, y, special);
56 return y;
57 }
58 VPCS_ALIAS
59
60 PL_SIG (V, F, 1, tanh, -10.0, 10.0)
61 PL_TEST_ULP (V_NAME (tanhf), 2.09)
62 PL_TEST_EXPECT_FENV (V_NAME (tanhf), WANT_SIMD_EXCEPT)
63 PL_TEST_INTERVAL (V_NAME (tanhf), 0, 0x1p-23, 1000)
64 PL_TEST_INTERVAL (V_NAME (tanhf), -0, -0x1p-23, 1000)
65 PL_TEST_INTERVAL (V_NAME (tanhf), 0x1p-23, 0x1.205966p+3, 100000)
66 PL_TEST_INTERVAL (V_NAME (tanhf), -0x1p-23, -0x1.205966p+3, 100000)
67 PL_TEST_INTERVAL (V_NAME (tanhf), 0x1.205966p+3, inf, 100)
68 PL_TEST_INTERVAL (V_NAME (tanhf), -0x1.205966p+3, -inf, 100)
69 #endif
70