xref: /freebsd/contrib/arm-optimized-routines/pl/math/tanh_3u.c (revision 9f23cbd6cae82fd77edfad7173432fa8dccd0a95)
1 /*
2  * Double-precision tanh(x) function.
3  *
4  * Copyright (c) 2023, Arm Limited.
5  * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6  */
7 #include "math_config.h"
8 #include "estrin.h"
9 #include "pl_sig.h"
10 #include "pl_test.h"
11 
12 #define AbsMask 0x7fffffffffffffff
13 #define InvLn2 0x1.71547652b82fep0
14 #define Ln2hi 0x1.62e42fefa39efp-1
15 #define Ln2lo 0x1.abc9e3b39803fp-56
16 #define Shift 0x1.8p52
17 #define C(i) __expm1_poly[i]
18 
19 #define BoringBound 0x403241bf835f9d5f /* asuint64 (0x1.241bf835f9d5fp+4).  */
20 #define TinyBound 0x3e40000000000000   /* asuint64 (0x1p-27).  */
21 #define One 0x3ff0000000000000
22 
23 static inline double
24 expm1_inline (double x)
25 {
26   /* Helper routine for calculating exp(x) - 1. Copied from expm1_2u5.c, with
27      several simplifications:
28      - No special-case handling for tiny or special values.
29      - Simpler combination of p and t in final stage of the algorithm.
30      - Use shift-and-add instead of ldexp to calculate t.  */
31 
32   /* Reduce argument: f in [-ln2/2, ln2/2], i is exact.  */
33   double j = fma (InvLn2, x, Shift) - Shift;
34   int64_t i = j;
35   double f = fma (j, -Ln2hi, x);
36   f = fma (j, -Ln2lo, f);
37 
38   /* Approximate expm1(f) using polynomial.  */
39   double f2 = f * f;
40   double f4 = f2 * f2;
41   double p = fma (f2, ESTRIN_10 (f, f2, f4, f4 * f4, C), f);
42 
43   /* t = 2 ^ i.  */
44   double t = asdouble ((uint64_t) (i + 1023) << 52);
45   /* expm1(x) = p * t + (t - 1).  */
46   return fma (p, t, t - 1);
47 }
48 
49 /* Approximation for double-precision tanh(x), using a simplified version of
50    expm1. The greatest observed error is 2.75 ULP:
51    tanh(-0x1.c143c3a44e087p-3) got -0x1.ba31ba4691ab7p-3
52 			      want -0x1.ba31ba4691ab4p-3.  */
53 double
54 tanh (double x)
55 {
56   uint64_t ix = asuint64 (x);
57   uint64_t ia = ix & AbsMask;
58   uint64_t sign = ix & ~AbsMask;
59 
60   if (unlikely (ia > BoringBound))
61     {
62       if (ia > 0x7ff0000000000000)
63 	return __math_invalid (x);
64       return asdouble (One | sign);
65     }
66 
67   if (unlikely (ia < TinyBound))
68     return x;
69 
70   /* tanh(x) = (e^2x - 1) / (e^2x + 1).  */
71   double q = expm1_inline (2 * x);
72   return q / (q + 2);
73 }
74 
75 PL_SIG (S, D, 1, tanh, -10.0, 10.0)
76 PL_TEST_ULP (tanh, 2.26)
77 PL_TEST_INTERVAL (tanh, 0, TinyBound, 1000)
78 PL_TEST_INTERVAL (tanh, -0, -TinyBound, 1000)
79 PL_TEST_INTERVAL (tanh, TinyBound, BoringBound, 100000)
80 PL_TEST_INTERVAL (tanh, -TinyBound, -BoringBound, 100000)
81 PL_TEST_INTERVAL (tanh, BoringBound, inf, 1000)
82 PL_TEST_INTERVAL (tanh, -BoringBound, -inf, 1000)
83