1 /* 2 * Single-precision vector tanh(x) function. 3 * 4 * Copyright (c) 2022-2024, Arm Limited. 5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception 6 */ 7 8 #include "v_math.h" 9 #include "test_sig.h" 10 #include "test_defs.h" 11 #include "v_expm1f_inline.h" 12 13 static const struct data 14 { 15 struct v_expm1f_data expm1f_consts; 16 uint32x4_t boring_bound, large_bound, onef; 17 } data = { 18 .expm1f_consts = V_EXPM1F_DATA, 19 /* 0x1.205966p+3, above which tanhf rounds to 1 (or -1 for negative). */ 20 .boring_bound = V4 (0x41102cb3), 21 .large_bound = V4 (0x7f800000), 22 }; 23 24 static float32x4_t NOINLINE VPCS_ATTR 25 special_case (float32x4_t x, uint32x4_t is_boring, float32x4_t boring, 26 float32x4_t q, uint32x4_t special) 27 { 28 return v_call_f32 ( 29 tanhf, x, 30 vbslq_f32 (is_boring, boring, vdivq_f32 (q, vaddq_f32 (q, v_f32 (2.0)))), 31 special); 32 } 33 34 /* Approximation for single-precision vector tanh(x), using a simplified 35 version of expm1f. The maximum error is 2.58 ULP: 36 _ZGVnN4v_tanhf (0x1.fa5eep-5) got 0x1.f9ba02p-5 37 want 0x1.f9ba08p-5. */ 38 float32x4_t VPCS_ATTR NOINLINE V_NAME_F1 (tanh) (float32x4_t x) 39 { 40 const struct data *d = ptr_barrier (&data); 41 42 uint32x4_t ix = vreinterpretq_u32_f32 (x); 43 float32x4_t ax = vabsq_f32 (x); 44 uint32x4_t iax = vreinterpretq_u32_f32 (ax); 45 uint32x4_t sign = veorq_u32 (ix, iax); 46 uint32x4_t is_boring = vcgtq_u32 (iax, d->boring_bound); 47 /* expm1 exponent bias is 1.0f reinterpreted to int. */ 48 float32x4_t boring = vreinterpretq_f32_u32 (vorrq_u32 ( 49 sign, vreinterpretq_u32_s32 (d->expm1f_consts.exponent_bias))); 50 51 #if WANT_SIMD_EXCEPT 52 /* If fp exceptions are to be triggered properly, set all special and boring 53 lanes to 0, which will trigger no exceptions, and fix them up later. */ 54 uint32x4_t special = vorrq_u32 (vcgtq_u32 (iax, d->large_bound), 55 vcltq_u32 (iax, v_u32 (0x34000000))); 56 x = v_zerofy_f32 (x, is_boring); 57 if (unlikely (v_any_u32 (special))) 58 x = v_zerofy_f32 (x, special); 59 #else 60 uint32x4_t special = vcgtq_u32 (iax, d->large_bound); 61 #endif 62 63 /* tanh(x) = (e^2x - 1) / (e^2x + 1). */ 64 float32x4_t q = expm1f_inline (vmulq_n_f32 (x, 2), &d->expm1f_consts); 65 66 if (unlikely (v_any_u32 (special))) 67 return special_case (vreinterpretq_f32_u32 (ix), is_boring, boring, q, 68 special); 69 70 float32x4_t y = vdivq_f32 (q, vaddq_f32 (q, v_f32 (2.0))); 71 return vbslq_f32 (is_boring, boring, y); 72 } 73 74 HALF_WIDTH_ALIAS_F1 (tanh) 75 76 TEST_SIG (V, F, 1, tanh, -10.0, 10.0) 77 TEST_ULP (V_NAME_F1 (tanh), 2.09) 78 TEST_DISABLE_FENV_IF_NOT (V_NAME_F1 (tanh), WANT_SIMD_EXCEPT) 79 TEST_SYM_INTERVAL (V_NAME_F1 (tanh), 0, 0x1p-23, 1000) 80 TEST_SYM_INTERVAL (V_NAME_F1 (tanh), 0x1p-23, 0x1.205966p+3, 100000) 81 TEST_SYM_INTERVAL (V_NAME_F1 (tanh), 0x1.205966p+3, inf, 100) 82