1 /*
2 * Single-precision log2 function.
3 *
4 * Copyright (c) 2017-2024, Arm Limited.
5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6 */
7
8 #include <math.h>
9 #include <stdint.h>
10 #include "math_config.h"
11 #include "test_defs.h"
12 #include "test_sig.h"
13
14 /*
15 LOG2F_TABLE_BITS = 4
16 LOG2F_POLY_ORDER = 4
17
18 ULP error: 0.752 (nearest rounding.)
19 Relative error: 1.9 * 2^-26 (before rounding.)
20 */
21
22 #define N (1 << LOG2F_TABLE_BITS)
23 #define T __log2f_data.tab
24 #define A __log2f_data.poly
25 #define OFF 0x3f330000
26
27 float
log2f(float x)28 log2f (float x)
29 {
30 /* double_t for better performance on targets with FLT_EVAL_METHOD==2. */
31 double_t z, r, r2, p, y, y0, invc, logc;
32 uint32_t ix, iz, top, tmp;
33 int k, i;
34
35 ix = asuint (x);
36 #if WANT_ROUNDING
37 /* Fix sign of zero with downward rounding when x==1. */
38 if (unlikely (ix == 0x3f800000))
39 return 0;
40 #endif
41 if (unlikely (ix - 0x00800000 >= 0x7f800000 - 0x00800000))
42 {
43 /* x < 0x1p-126 or inf or nan. */
44 if (ix * 2 == 0)
45 return __math_divzerof (1);
46 if (ix == 0x7f800000) /* log2(inf) == inf. */
47 return x;
48 if ((ix & 0x80000000) || ix * 2 >= 0xff000000)
49 return __math_invalidf (x);
50 /* x is subnormal, normalize it. */
51 ix = asuint (x * 0x1p23f);
52 ix -= 23 << 23;
53 }
54
55 /* x = 2^k z; where z is in range [OFF,2*OFF] and exact.
56 The range is split into N subintervals.
57 The ith subinterval contains z and c is near its center. */
58 tmp = ix - OFF;
59 i = (tmp >> (23 - LOG2F_TABLE_BITS)) % N;
60 top = tmp & 0xff800000;
61 iz = ix - top;
62 k = (int32_t) tmp >> 23; /* arithmetic shift */
63 invc = T[i].invc;
64 logc = T[i].logc;
65 z = (double_t) asfloat (iz);
66
67 /* log2(x) = log1p(z/c-1)/ln2 + log2(c) + k */
68 r = z * invc - 1;
69 y0 = logc + (double_t) k;
70
71 /* Pipelined polynomial evaluation to approximate log1p(r)/ln2. */
72 r2 = r * r;
73 y = A[1] * r + A[2];
74 y = A[0] * r2 + y;
75 p = A[3] * r + y0;
76 y = y * r2 + p;
77 return eval_as_float (y);
78 }
79 #if USE_GLIBC_ABI
80 strong_alias (log2f, __log2f_finite)
81 hidden_alias (log2f, __ieee754_log2f)
82 #endif
83
84 TEST_SIG (S, F, 1, log2, 0.01, 11.1)
85 TEST_ULP (log2f, 0.26)
86 TEST_ULP_NONNEAREST (log2f, 0.5)
87 TEST_INTERVAL (log2f, 0, 0xffff0000, 10000)
88 TEST_INTERVAL (log2f, 0x1p-4, 0x1p4, 50000)
89 TEST_INTERVAL (log2f, 0, inf, 50000)
90