github.com/afumu/libc@v0.0.6/musl/src/math/expf.c (about)

     1  /*
     2   * Single-precision e^x function.
     3   *
     4   * Copyright (c) 2017-2018, Arm Limited.
     5   * SPDX-License-Identifier: MIT
     6   */
     7  
     8  #include <math.h>
     9  #include <stdint.h>
    10  #include "libm.h"
    11  #include "exp2f_data.h"
    12  
    13  /*
    14  EXP2F_TABLE_BITS = 5
    15  EXP2F_POLY_ORDER = 3
    16  
    17  ULP error: 0.502 (nearest rounding.)
    18  Relative error: 1.69 * 2^-34 in [-ln2/64, ln2/64] (before rounding.)
    19  Wrong count: 170635 (all nearest rounding wrong results with fma.)
    20  Non-nearest ULP error: 1 (rounded ULP error)
    21  */
    22  
    23  #define N (1 << EXP2F_TABLE_BITS)
    24  #define InvLn2N __exp2f_data.invln2_scaled
    25  #define T __exp2f_data.tab
    26  #define C __exp2f_data.poly_scaled
    27  
    28  static inline uint32_t top12(float x)
    29  {
    30  	return asuint(x) >> 20;
    31  }
    32  
    33  float expf(float x)
    34  {
    35  	uint32_t abstop;
    36  	uint64_t ki, t;
    37  	double_t kd, xd, z, r, r2, y, s;
    38  
    39  	xd = (double_t)x;
    40  	abstop = top12(x) & 0x7ff;
    41  	if (predict_false(abstop >= top12(88.0f))) {
    42  		/* |x| >= 88 or x is nan.  */
    43  		if (asuint(x) == asuint(-INFINITY))
    44  			return 0.0f;
    45  		if (abstop >= top12(INFINITY))
    46  			return x + x;
    47  		if (x > 0x1.62e42ep6f) /* x > log(0x1p128) ~= 88.72 */
    48  			return __math_oflowf(0);
    49  		if (x < -0x1.9fe368p6f) /* x < log(0x1p-150) ~= -103.97 */
    50  			return __math_uflowf(0);
    51  	}
    52  
    53  	/* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k.  */
    54  	z = InvLn2N * xd;
    55  
    56  	/* Round and convert z to int, the result is in [-150*N, 128*N] and
    57  	   ideally ties-to-even rule is used, otherwise the magnitude of r
    58  	   can be bigger which gives larger approximation error.  */
    59  #if TOINT_INTRINSICS
    60  	kd = roundtoint(z);
    61  	ki = converttoint(z);
    62  #else
    63  # define SHIFT __exp2f_data.shift
    64  	kd = eval_as_double(z + SHIFT);
    65  	ki = asuint64(kd);
    66  	kd -= SHIFT;
    67  #endif
    68  	r = z - kd;
    69  
    70  	/* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
    71  	t = T[ki % N];
    72  	t += ki << (52 - EXP2F_TABLE_BITS);
    73  	s = asdouble(t);
    74  	z = C[0] * r + C[1];
    75  	r2 = r * r;
    76  	y = C[2] * r + 1;
    77  	y = z * r2 + y;
    78  	y = y * s;
    79  	return eval_as_float(y);
    80  }