93 lines · c
1/*2 * Single-precision e^x function.3 *4 * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.5 * See https://llvm.org/LICENSE.txt for license information.6 * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception7 */8 9#include <math.h>10#include <stdint.h>11#include "math_config.h"12 13/*14EXP2F_TABLE_BITS = 515EXP2F_POLY_ORDER = 316 17ULP error: 0.502 (nearest rounding.)18Relative error: 1.69 * 2^-34 in [-ln2/64, ln2/64] (before rounding.)19Wrong count: 170635 (all nearest rounding wrong results with fma.)20Non-nearest ULP error: 1 (rounded ULP error)21*/22 23#define N (1 << EXP2F_TABLE_BITS)24#define InvLn2N __exp2f_data.invln2_scaled25#define T __exp2f_data.tab26#define C __exp2f_data.poly_scaled27 28static inline uint32_t29top12 (float x)30{31 return asuint (x) >> 20;32}33 34float35expf (float x)36{37 uint32_t abstop;38 uint64_t ki, t;39 /* double_t for better performance on targets with FLT_EVAL_METHOD==2. */40 double_t kd, xd, z, r, r2, y, s;41 42 xd = (double_t) x;43 abstop = top12 (x) & 0x7ff;44 if (unlikely (abstop >= top12 (88.0f)))45 {46 /* |x| >= 88 or x is nan. */47 if (asuint (x) == asuint (-INFINITY))48 return 0.0f;49 if (abstop >= top12 (INFINITY))50 return x + x;51 if (x > 0x1.62e42ep6f) /* x > log(0x1p128) ~= 88.72 */52 return __math_oflowf (0);53 if (x < -0x1.9fe368p6f) /* x < log(0x1p-150) ~= -103.97 */54 return __math_uflowf (0);55#if WANT_ERRNO_UFLOW56 if (x < -0x1.9d1d9ep6f) /* x < log(0x1p-149) ~= -103.28 */57 return __math_may_uflowf (0);58#endif59 }60 61 /* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k. */62 z = InvLn2N * xd;63 64 /* Round and convert z to int, the result is in [-150*N, 128*N] and65 ideally nearest int is used, otherwise the magnitude of r can be66 bigger which gives larger approximation error. */67#if TOINT_INTRINSICS68 kd = roundtoint (z);69 ki = converttoint (z);70#else71# define SHIFT __exp2f_data.shift72 kd = eval_as_double (z + SHIFT);73 ki = asuint64 (kd);74 kd -= SHIFT;75#endif76 r = z - kd;77 78 /* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */79 t = T[ki % N];80 t += ki << (52 - EXP2F_TABLE_BITS);81 s = asdouble (t);82 z = C[0] * r + C[1];83 r2 = r * r;84 y = C[2] * r + 1;85 y = z * r2 + y;86 y = y * s;87 return eval_as_float (y);88}89#if USE_GLIBC_ABI90strong_alias (expf, __expf_finite)91hidden_alias (expf, __ieee754_expf)92#endif93