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