xref: /freebsd/contrib/arm-optimized-routines/pl/math/atanhf_3u1.c (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 /*
2  * Single-precision atanh(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 "math_config.h"
9 #include "mathlib.h"
10 #include "pl_sig.h"
11 #include "pl_test.h"
12 
13 #define AbsMask 0x7fffffff
14 #define Half 0x3f000000
15 #define One 0x3f800000
16 #define Four 0x40800000
17 #define Ln2 0x1.62e43p-1f
18 /* asuint(0x1p-12), below which atanhf(x) rounds to x.  */
19 #define TinyBound 0x39800000
20 
21 #define C(i) __log1pf_data.coeffs[i]
22 
23 static inline float
24 eval_poly (float m)
25 {
26   /* Approximate log(1+m) on [-0.25, 0.5] using Estrin scheme.  */
27   float p_12 = fmaf (m, C (1), C (0));
28   float p_34 = fmaf (m, C (3), C (2));
29   float p_56 = fmaf (m, C (5), C (4));
30   float p_78 = fmaf (m, C (7), C (6));
31 
32   float m2 = m * m;
33   float p_02 = fmaf (m2, p_12, m);
34   float p_36 = fmaf (m2, p_56, p_34);
35   float p_79 = fmaf (m2, C (8), p_78);
36 
37   float m4 = m2 * m2;
38   float p_06 = fmaf (m4, p_36, p_02);
39 
40   return fmaf (m4 * p_79, m4, p_06);
41 }
42 
43 static inline float
44 log1pf_inline (float x)
45 {
46   /* Helper for calculating log(x + 1). Copied from log1pf_2u1.c, with no
47      special-case handling. See that file for details of the algorithm.  */
48   float m = x + 1.0f;
49   int k = (asuint (m) - 0x3f400000) & 0xff800000;
50   float s = asfloat (Four - k);
51   float m_scale = asfloat (asuint (x) - k) + fmaf (0.25f, s, -1.0f);
52   float p = eval_poly (m_scale);
53   float scale_back = (float) k * 0x1.0p-23f;
54   return fmaf (scale_back, Ln2, p);
55 }
56 
57 /* Approximation for single-precision inverse tanh(x), using a simplified
58    version of log1p. Maximum error is 3.08 ULP:
59    atanhf(0x1.ff0d5p-5) got 0x1.ffb768p-5
60 		       want 0x1.ffb76ep-5.  */
61 float
62 atanhf (float x)
63 {
64   uint32_t ix = asuint (x);
65   uint32_t iax = ix & AbsMask;
66   uint32_t sign = ix & ~AbsMask;
67 
68   if (unlikely (iax < TinyBound))
69     return x;
70 
71   if (iax == One)
72     return __math_divzero (sign);
73 
74   if (unlikely (iax > One))
75     return __math_invalidf (x);
76 
77   float halfsign = asfloat (Half | sign);
78   float ax = asfloat (iax);
79   return halfsign * log1pf_inline ((2 * ax) / (1 - ax));
80 }
81 
82 PL_SIG (S, F, 1, atanh, -1.0, 1.0)
83 PL_TEST_ULP (atanhf, 2.59)
84 PL_TEST_SYM_INTERVAL (atanhf, 0, 0x1p-12, 500)
85 PL_TEST_SYM_INTERVAL (atanhf, 0x1p-12, 1, 200000)
86 PL_TEST_SYM_INTERVAL (atanhf, 1, inf, 1000)
87