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