1 /*
2  * Single-precision e^x - 1 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 "hornerf.h"
9 #include "math_config.h"
10 #include "pl_sig.h"
11 #include "pl_test.h"
12 
13 #define Shift (0x1.8p23f)
14 #define InvLn2 (0x1.715476p+0f)
15 #define Ln2hi (0x1.62e4p-1f)
16 #define Ln2lo (0x1.7f7d1cp-20f)
17 #define AbsMask (0x7fffffff)
18 #define InfLimit                                                               \
19   (0x1.644716p6) /* Smallest value of x for which expm1(x) overflows.  */
20 #define NegLimit                                                               \
21   (-0x1.9bbabcp+6) /* Largest value of x for which expm1(x) rounds to 1.  */
22 
23 #define C(i) __expm1f_poly[i]
24 
25 /* Approximation for exp(x) - 1 using polynomial on a reduced interval.
26    The maximum error is 1.51 ULP:
27    expm1f(0x1.8baa96p-2) got 0x1.e2fb9p-2
28 			want 0x1.e2fb94p-2.  */
29 float
30 expm1f (float x)
31 {
32   uint32_t ix = asuint (x);
33   uint32_t ax = ix & AbsMask;
34 
35   /* Tiny: |x| < 0x1p-23. expm1(x) is closely approximated by x.
36      Inf:  x == +Inf => expm1(x) = x.  */
37   if (ax <= 0x34000000 || (ix == 0x7f800000))
38     return x;
39 
40   /* +/-NaN.  */
41   if (ax > 0x7f800000)
42     return __math_invalidf (x);
43 
44   if (x >= InfLimit)
45     return __math_oflowf (0);
46 
47   if (x <= NegLimit || ix == 0xff800000)
48     return -1;
49 
50   /* Reduce argument to smaller range:
51      Let i = round(x / ln2)
52      and f = x - i * ln2, then f is in [-ln2/2, ln2/2].
53      exp(x) - 1 = 2^i * (expm1(f) + 1) - 1
54      where 2^i is exact because i is an integer.  */
55   float j = fmaf (InvLn2, x, Shift) - Shift;
56   int32_t i = j;
57   float f = fmaf (j, -Ln2hi, x);
58   f = fmaf (j, -Ln2lo, f);
59 
60   /* Approximate expm1(f) using polynomial.
61      Taylor expansion for expm1(x) has the form:
62 	 x + ax^2 + bx^3 + cx^4 ....
63      So we calculate the polynomial P(f) = a + bf + cf^2 + ...
64      and assemble the approximation expm1(f) ~= f + f^2 * P(f).  */
65   float p = fmaf (f * f, HORNER_4 (f, C), f);
66   /* Assemble the result, using a slight rearrangement to achieve acceptable
67      accuracy.
68      expm1(x) ~= 2^i * (p + 1) - 1
69      Let t = 2^(i - 1).  */
70   float t = ldexpf (0.5f, i);
71   /* expm1(x) ~= 2 * (p * t + (t - 1/2)).  */
72   return 2 * fmaf (p, t, t - 0.5f);
73 }
74 
75 PL_SIG (S, F, 1, expm1, -9.9, 9.9)
76 PL_TEST_ULP (expm1f, 1.02)
77 PL_TEST_INTERVAL (expm1f, 0, 0x1p-23, 1000)
78 PL_TEST_INTERVAL (expm1f, -0, -0x1p-23, 1000)
79 PL_TEST_INTERVAL (expm1f, 0x1p-23, 0x1.644716p6, 100000)
80 PL_TEST_INTERVAL (expm1f, -0x1p-23, -0x1.9bbabcp+6, 100000)
81