1 /*
2 * Single-precision log 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 "logf_data.h"
12
13 /*
14 LOGF_TABLE_BITS = 4
15 LOGF_POLY_ORDER = 4
16
17 ULP error: 0.818 (nearest rounding.)
18 Relative error: 1.957 * 2^-26 (before rounding.)
19 */
20
21 #define T __logf_data.tab
22 #define A __logf_data.poly
23 #define Ln2 __logf_data.ln2
24 #define N (1 << LOGF_TABLE_BITS)
25 #define OFF 0x3f330000
26
logf(float x)27 float logf(float x)
28 {
29 double_t z, r, r2, y, y0, invc, logc;
30 uint32_t ix, iz, tmp;
31 int k, i;
32
33 ix = asuint(x);
34 /* Fix sign of zero with downward rounding when x==1. */
35 if (WANT_ROUNDING && predict_false(ix == 0x3f800000))
36 return 0;
37 if (predict_false(ix - 0x00800000 >= 0x7f800000 - 0x00800000)) {
38 /* x < 0x1p-126 or inf or nan. */
39 if (ix * 2 == 0)
40 return __math_divzerof(1);
41 if (ix == 0x7f800000) /* log(inf) == inf. */
42 return x;
43 if ((ix & 0x80000000) || ix * 2 >= 0xff000000)
44 return __math_invalidf(x);
45 /* x is subnormal, normalize it. */
46 ix = asuint(x * 0x1p23f);
47 ix -= 23 << 23;
48 }
49
50 /* x = 2^k z; where z is in range [OFF,2*OFF] and exact.
51 The range is split into N subintervals.
52 The ith subinterval contains z and c is near its center. */
53 tmp = ix - OFF;
54 i = (tmp >> (23 - LOGF_TABLE_BITS)) % N;
55 k = (int32_t)tmp >> 23; /* arithmetic shift */
56 iz = ix - (tmp & 0x1ff << 23);
57 invc = T[i].invc;
58 logc = T[i].logc;
59 z = (double_t)asfloat(iz);
60
61 /* log(x) = log1p(z/c-1) + log(c) + k*Ln2 */
62 r = z * invc - 1;
63 y0 = logc + (double_t)k * Ln2;
64
65 /* Pipelined polynomial evaluation to approximate log1p(r). */
66 r2 = r * r;
67 y = A[1] * r + A[2];
68 y = A[0] * r2 + y;
69 y = y * r2 + (y0 + r);
70 return eval_as_float(y);
71 }
72