xref: /freebsd/contrib/arm-optimized-routines/pl/math/expf.c (revision 6580f5c38dd5b01aeeaed16b370f1a12423437f0)
1 /*
2  * Single-precision e^x function.
3  *
4  * Copyright (c) 2017-2023, 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 
12 /*
13 EXPF_TABLE_BITS = 5
14 EXPF_POLY_ORDER = 3
15 
16 ULP error: 0.502 (nearest rounding.)
17 Relative error: 1.69 * 2^-34 in [-ln2/64, ln2/64] (before rounding.)
18 Wrong count: 170635 (all nearest rounding wrong results with fma.)
19 Non-nearest ULP error: 1 (rounded ULP error)
20 */
21 
22 #define N (1 << EXPF_TABLE_BITS)
23 #define InvLn2N __expf_data.invln2_scaled
24 #define T __expf_data.tab
25 #define C __expf_data.poly_scaled
26 
27 static inline uint32_t
28 top12 (float x)
29 {
30   return asuint (x) >> 20;
31 }
32 
33 float
34 optr_aor_exp_f32 (float x)
35 {
36   uint32_t abstop;
37   uint64_t ki, t;
38   /* double_t for better performance on targets with FLT_EVAL_METHOD==2.  */
39   double_t kd, xd, z, r, r2, y, s;
40 
41   xd = (double_t) x;
42   abstop = top12 (x) & 0x7ff;
43   if (unlikely (abstop >= top12 (88.0f)))
44     {
45       /* |x| >= 88 or x is nan.  */
46       if (asuint (x) == asuint (-INFINITY))
47 	return 0.0f;
48       if (abstop >= top12 (INFINITY))
49 	return x + x;
50       if (x > 0x1.62e42ep6f) /* x > log(0x1p128) ~= 88.72 */
51 	return __math_oflowf (0);
52       if (x < -0x1.9fe368p6f) /* x < log(0x1p-150) ~= -103.97 */
53 	return __math_uflowf (0);
54     }
55 
56   /* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k.  */
57   z = InvLn2N * xd;
58 
59   /* Round and convert z to int, the result is in [-150*N, 128*N] and
60      ideally nearest int is used, otherwise the magnitude of r can be
61      bigger which gives larger approximation error.  */
62   kd = round (z);
63   ki = lround (z);
64   r = z - kd;
65 
66   /* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
67   t = T[ki % N];
68   t += ki << (52 - EXPF_TABLE_BITS);
69   s = asdouble (t);
70   z = C[0] * r + C[1];
71   r2 = r * r;
72   y = C[2] * r + 1;
73   y = z * r2 + y;
74   y = y * s;
75   return eval_as_float (y);
76 }
77