1/* Single-precision log function.
2 Copyright (C) 2017-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19#include <math.h>
20#include <stdint.h>
21#include <libm-alias-finite.h>
22#include <libm-alias-float.h>
23#include "math_config.h"
24
25/*
26LOGF_TABLE_BITS = 4
27LOGF_POLY_ORDER = 4
28
29ULP error: 0.818 (nearest rounding.)
30Relative error: 1.957 * 2^-26 (before rounding.)
31*/
32
33#define T __logf_data.tab
34#define A __logf_data.poly
35#define Ln2 __logf_data.ln2
36#define N (1 << LOGF_TABLE_BITS)
37#define OFF 0x3f330000
38
39float
40__logf (float x)
41{
42 /* double_t for better performance on targets with FLT_EVAL_METHOD==2. */
43 double_t z, r, r2, y, y0, invc, logc;
44 uint32_t ix, iz, tmp;
45 int k, i;
46
47 ix = asuint (f: x);
48#if WANT_ROUNDING
49 /* Fix sign of zero with downward rounding when x==1. */
50 if (__glibc_unlikely (ix == 0x3f800000))
51 return 0;
52#endif
53 if (__glibc_unlikely (ix - 0x00800000 >= 0x7f800000 - 0x00800000))
54 {
55 /* x < 0x1p-126 or inf or nan. */
56 if (ix * 2 == 0)
57 return __math_divzerof (1);
58 if (ix == 0x7f800000) /* log(inf) == inf. */
59 return x;
60 if ((ix & 0x80000000) || ix * 2 >= 0xff000000)
61 return __math_invalidf (x);
62 /* x is subnormal, normalize it. */
63 ix = asuint (f: x * 0x1p23f);
64 ix -= 23 << 23;
65 }
66
67 /* x = 2^k z; where z is in range [OFF,2*OFF] and exact.
68 The range is split into N subintervals.
69 The ith subinterval contains z and c is near its center. */
70 tmp = ix - OFF;
71 i = (tmp >> (23 - LOGF_TABLE_BITS)) % N;
72 k = (int32_t) tmp >> 23; /* arithmetic shift */
73 iz = ix - (tmp & 0x1ff << 23);
74 invc = T[i].invc;
75 logc = T[i].logc;
76 z = (double_t) asfloat (i: iz);
77
78 /* log(x) = log1p(z/c-1) + log(c) + k*Ln2 */
79 r = z * invc - 1;
80 y0 = logc + (double_t) k * Ln2;
81
82 /* Pipelined polynomial evaluation to approximate log1p(r). */
83 r2 = r * r;
84 y = A[1] * r + A[2];
85 y = A[0] * r2 + y;
86 y = y * r2 + (y0 + r);
87 return (float) y;
88}
89#ifndef __logf
90strong_alias (__logf, __ieee754_logf)
91libm_alias_finite (__ieee754_logf, __logf)
92versioned_symbol (libm, __logf, logf, GLIBC_2_27);
93libm_alias_float_other (__log, log)
94#endif
95

source code of glibc/sysdeps/ieee754/flt-32/e_logf.c