1 /*
2  * Single-precision 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 #include "math_config.h"
8 #include "pl_sig.h"
9 #include "pl_test.h"
10 
11 #define BoringBound                                                            \
12   0x41102cb3 /* 0x1.205966p+3, above which tanhf rounds to 1 (or -1 for        \
13 		negative).  */
14 #define AbsMask 0x7fffffff
15 #define One 0x3f800000
16 
17 #define Shift (0x1.8p23f)
18 #define InvLn2 (0x1.715476p+0f)
19 #define Ln2hi (0x1.62e4p-1f)
20 #define Ln2lo (0x1.7f7d1cp-20f)
21 
22 #define C(i) __expm1f_poly[i]
23 
24 static inline float
25 expm1f_inline (float x)
26 {
27   /* Helper routine for calculating exp(x) - 1.
28      Copied from expm1f_1u6.c, with several simplifications:
29      - No special-case handling for tiny or special values, instead return early
30        from the main routine.
31      - No special handling for large values:
32        - No early return for infinity.
33        - Simpler combination of p and t in final stage of algorithm.
34        - |i| < 27, so can calculate t by simpler shift-and-add, instead of
35 	 ldexpf (same as vector algorithm).  */
36 
37   /* Reduce argument: f in [-ln2/2, ln2/2], i is exact.  */
38   float j = fmaf (InvLn2, x, Shift) - Shift;
39   int32_t i = j;
40   float f = fmaf (j, -Ln2hi, x);
41   f = fmaf (j, -Ln2lo, f);
42 
43   /* Approximate expm1(f) with polynomial P, expm1(f) ~= f + f^2 * P(f).
44      Uses Estrin scheme, where the main expm1f routine uses Horner.  */
45   float f2 = f * f;
46   float p_01 = fmaf (f, C (1), C (0));
47   float p_23 = fmaf (f, C (3), C (2));
48   float p = fmaf (f2, p_23, p_01);
49   p = fmaf (f2 * f2, C (4), p);
50   p = fmaf (f2, p, f);
51 
52   /* t = 2^i.  */
53   float t = asfloat ((uint32_t) (i + 127) << 23);
54   /* expm1(x) ~= p * t + (t - 1).  */
55   return fmaf (p, t, t - 1);
56 }
57 
58 /* Approximation for single-precision tanh(x), using a simplified version of
59    expm1f. The maximum error is 2.58 ULP:
60    tanhf(0x1.fa5eep-5) got 0x1.f9ba02p-5
61 		      want 0x1.f9ba08p-5.  */
62 float
63 tanhf (float x)
64 {
65   uint32_t ix = asuint (x);
66   uint32_t iax = ix & AbsMask;
67   uint32_t sign = ix & ~AbsMask;
68 
69   if (unlikely (iax > BoringBound))
70     {
71       if (iax > 0x7f800000)
72 	return __math_invalidf (x);
73       return asfloat (One | sign);
74     }
75 
76   if (unlikely (iax < 0x34000000))
77     return x;
78 
79   /* tanh(x) = (e^2x - 1) / (e^2x + 1).  */
80   float q = expm1f_inline (2 * x);
81   return q / (q + 2);
82 }
83 
84 PL_SIG (S, F, 1, tanh, -10.0, 10.0)
85 PL_TEST_ULP (tanhf, 2.09)
86 PL_TEST_SYM_INTERVAL (tanhf, 0, 0x1p-23, 1000)
87 PL_TEST_SYM_INTERVAL (tanhf, 0x1p-23, 0x1.205966p+3, 100000)
88 PL_TEST_SYM_INTERVAL (tanhf, 0x1.205966p+3, inf, 100)
89