xref: /freebsd/contrib/arm-optimized-routines/math/exp2f.c (revision dd21556857e8d40f66bf5ad54754d9d52669ebf7)
1 /*
2  * Single-precision 2^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 [-1/64, 1/64] (before rounding.)
20 Wrong count: 168353 (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 T __exp2f_data.tab
26 #define C __exp2f_data.poly
27 #define SHIFT __exp2f_data.shift_scaled
28 
29 static inline uint32_t
30 top12 (float x)
31 {
32   return asuint (x) >> 20;
33 }
34 
35 float
36 exp2f (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 (128.0f)))
46     {
47       /* |x| >= 128 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 > 0.0f)
53 	return __math_oflowf (0);
54       if (x <= -150.0f)
55 	return __math_uflowf (0);
56 #if WANT_ERRNO_UFLOW
57       if (x < -149.0f)
58 	return __math_may_uflowf (0);
59 #endif
60     }
61 
62   /* x = k/N + r with r in [-1/(2N), 1/(2N)] and int k.  */
63   kd = eval_as_double (xd + SHIFT);
64   ki = asuint64 (kd);
65   kd -= SHIFT; /* k/N for int k.  */
66   r = xd - kd;
67 
68   /* exp2(x) = 2^(k/N) * 2^r ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
69   t = T[ki % N];
70   t += ki << (52 - EXP2F_TABLE_BITS);
71   s = asdouble (t);
72   z = C[0] * r + C[1];
73   r2 = r * r;
74   y = C[2] * r + 1;
75   y = z * r2 + y;
76   y = y * s;
77   return eval_as_float (y);
78 }
79 #if USE_GLIBC_ABI
80 strong_alias (exp2f, __exp2f_finite)
81 hidden_alias (exp2f, __ieee754_exp2f)
82 #endif
83 
84 TEST_SIG (S, F, 1, exp2, -9.9, 9.9)
85 TEST_ULP (exp2f, 0.01)
86 TEST_ULP_NONNEAREST (exp2f, 0.5)
87 TEST_INTERVAL (exp2f, 0, 0xffff0000, 10000)
88 TEST_SYM_INTERVAL (exp2f, 0x1p-14, 0x1p8, 50000)
89