xref: /freebsd/contrib/arm-optimized-routines/math/logf.c (revision 6c05f3a74f30934ee60919cc97e16ec69b542b06)
1 /*
2  * Single-precision log 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 LOGF_TABLE_BITS = 4
16 LOGF_POLY_ORDER = 4
17 
18 ULP error: 0.818 (nearest rounding.)
19 Relative error: 1.957 * 2^-26 (before rounding.)
20 */
21 
22 #define T __logf_data.tab
23 #define A __logf_data.poly
24 #define Ln2 __logf_data.ln2
25 #define N (1 << LOGF_TABLE_BITS)
26 #define OFF 0x3f330000
27 
28 float
29 logf (float x)
30 {
31   /* double_t for better performance on targets with FLT_EVAL_METHOD==2.  */
32   double_t z, r, r2, y, y0, invc, logc;
33   uint32_t ix, iz, tmp;
34   int k, i;
35 
36   ix = asuint (x);
37 #if WANT_ROUNDING
38   /* Fix sign of zero with downward rounding when x==1.  */
39   if (unlikely (ix == 0x3f800000))
40     return 0;
41 #endif
42   if (unlikely (ix - 0x00800000 >= 0x7f800000 - 0x00800000))
43     {
44       /* x < 0x1p-126 or inf or nan.  */
45       if (ix * 2 == 0)
46 	return __math_divzerof (1);
47       if (ix == 0x7f800000) /* log(inf) == inf.  */
48 	return x;
49       if ((ix & 0x80000000) || ix * 2 >= 0xff000000)
50 	return __math_invalidf (x);
51       /* x is subnormal, normalize it.  */
52       ix = asuint (x * 0x1p23f);
53       ix -= 23 << 23;
54     }
55 
56   /* x = 2^k z; where z is in range [OFF,2*OFF] and exact.
57      The range is split into N subintervals.
58      The ith subinterval contains z and c is near its center.  */
59   tmp = ix - OFF;
60   i = (tmp >> (23 - LOGF_TABLE_BITS)) % N;
61   k = (int32_t) tmp >> 23; /* arithmetic shift */
62   iz = ix - (tmp & 0xff800000);
63   invc = T[i].invc;
64   logc = T[i].logc;
65   z = (double_t) asfloat (iz);
66 
67   /* log(x) = log1p(z/c-1) + log(c) + k*Ln2 */
68   r = z * invc - 1;
69   y0 = logc + (double_t) k * Ln2;
70 
71   /* Pipelined polynomial evaluation to approximate log1p(r).  */
72   r2 = r * r;
73   y = A[1] * r + A[2];
74   y = A[0] * r2 + y;
75   y = y * r2 + (y0 + r);
76   return eval_as_float (y);
77 }
78 #if USE_GLIBC_ABI
79 strong_alias (logf, __logf_finite)
80 hidden_alias (logf, __ieee754_logf)
81 #endif
82 
83 TEST_SIG (S, F, 1, log, 0.01, 11.1)
84 TEST_ULP (logf, 0.32)
85 TEST_ULP_NONNEAREST (logf, 0.5)
86 TEST_INTERVAL (logf, 0, 0xffff0000, 10000)
87 TEST_INTERVAL (logf, 0x1p-4, 0x1p4, 500000)
88 TEST_INTERVAL (logf, 0, inf, 50000)
89