1 /*
2 * Single-precision e^x function.
3 *
4 * Copyright (c) 2017-2024, Arm Limited.
5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6 */
7
8 #include <math.h>
9 #include <stdint.h>
10 #include "math_config.h"
11 #include "test_defs.h"
12 #include "test_sig.h"
13
14 /*
15 EXP2F_TABLE_BITS = 5
16 EXP2F_POLY_ORDER = 3
17
18 ULP error: 0.502 (nearest rounding.)
19 Relative error: 1.69 * 2^-34 in [-ln2/64, ln2/64] (before rounding.)
20 Wrong count: 170635 (all nearest rounding wrong results with fma.)
21 Non-nearest ULP error: 1 (rounded ULP error)
22 */
23
24 #define N (1 << EXP2F_TABLE_BITS)
25 #define InvLn2N __exp2f_data.invln2_scaled
26 #define T __exp2f_data.tab
27 #define C __exp2f_data.poly_scaled
28
29 static inline uint32_t
top12(float x)30 top12 (float x)
31 {
32 return asuint (x) >> 20;
33 }
34
35 float
expf(float x)36 expf (float x)
37 {
38 uint32_t abstop;
39 uint64_t ki, t;
40 /* double_t for better performance on targets with FLT_EVAL_METHOD==2. */
41 double_t kd, xd, z, r, r2, y, s;
42
43 xd = (double_t) x;
44 abstop = top12 (x) & 0x7ff;
45 if (unlikely (abstop >= top12 (88.0f)))
46 {
47 /* |x| >= 88 or x is nan. */
48 if (asuint (x) == asuint (-INFINITY))
49 return 0.0f;
50 if (abstop >= top12 (INFINITY))
51 return x + x;
52 if (x > 0x1.62e42ep6f) /* x > log(0x1p128) ~= 88.72 */
53 return __math_oflowf (0);
54 if (x < -0x1.9fe368p6f) /* x < log(0x1p-150) ~= -103.97 */
55 return __math_uflowf (0);
56 #if WANT_ERRNO_UFLOW
57 if (x < -0x1.9d1d9ep6f) /* x < log(0x1p-149) ~= -103.28 */
58 return __math_may_uflowf (0);
59 #endif
60 }
61
62 /* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k. */
63 z = InvLn2N * xd;
64
65 /* Round and convert z to int, the result is in [-150*N, 128*N] and
66 ideally nearest int is used, otherwise the magnitude of r can be
67 bigger which gives larger approximation error. */
68 #if TOINT_INTRINSICS
69 kd = roundtoint (z);
70 ki = converttoint (z);
71 #else
72 # define SHIFT __exp2f_data.shift
73 kd = eval_as_double (z + SHIFT);
74 ki = asuint64 (kd);
75 kd -= SHIFT;
76 #endif
77 r = z - kd;
78
79 /* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
80 t = T[ki % N];
81 t += ki << (52 - EXP2F_TABLE_BITS);
82 s = asdouble (t);
83 z = C[0] * r + C[1];
84 r2 = r * r;
85 y = C[2] * r + 1;
86 y = z * r2 + y;
87 y = y * s;
88 return eval_as_float (y);
89 }
90 #if USE_GLIBC_ABI
91 strong_alias (expf, __expf_finite)
92 hidden_alias (expf, __ieee754_expf)
93 #endif
94
95 TEST_SIG (S, F, 1, exp, -9.9, 9.9)
96 TEST_ULP (expf, 0.01)
97 TEST_ULP_NONNEAREST (expf, 0.5)
98 TEST_INTERVAL (expf, 0, 0xffff0000, 10000)
99 TEST_SYM_INTERVAL (expf, 0x1p-14, 0x1p8, 500000)
100