1 /* 2 * Single-precision log10 function. 3 * 4 * Copyright (c) 2022-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 11 #include "math_config.h" 12 #include "test_sig.h" 13 #include "test_defs.h" 14 15 /* Data associated to logf: 16 17 LOGF_TABLE_BITS = 4 18 LOGF_POLY_ORDER = 4 19 20 ULP error: 0.818 (nearest rounding.) 21 Relative error: 1.957 * 2^-26 (before rounding.). */ 22 23 #define T __logf_data.tab 24 #define A __logf_data.poly 25 #define Ln2 __logf_data.ln2 26 #define InvLn10 __logf_data.invln10 27 #define N (1 << LOGF_TABLE_BITS) 28 #define OFF 0x3f330000 29 30 /* This naive implementation of log10f mimics that of log 31 then simply scales the result by 1/log(10) to switch from base e to 32 base 10. Hence, most computations are carried out in double precision. 33 Scaling before rounding to single precision is both faster and more 34 accurate. 35 36 ULP error: 0.797 ulp (nearest rounding.). */ 37 float 38 log10f (float x) 39 { 40 /* double_t for better performance on targets with FLT_EVAL_METHOD==2. */ 41 double_t z, r, r2, y, y0, invc, logc; 42 uint32_t ix, iz, tmp; 43 int k, i; 44 45 ix = asuint (x); 46 #if WANT_ROUNDING 47 /* Fix sign of zero with downward rounding when x==1. */ 48 if (unlikely (ix == 0x3f800000)) 49 return 0; 50 #endif 51 if (unlikely (ix - 0x00800000 >= 0x7f800000 - 0x00800000)) 52 { 53 /* x < 0x1p-126 or inf or nan. */ 54 if (ix * 2 == 0) 55 return __math_divzerof (1); 56 if (ix == 0x7f800000) /* log(inf) == inf. */ 57 return x; 58 if ((ix & 0x80000000) || ix * 2 >= 0xff000000) 59 return __math_invalidf (x); 60 /* x is subnormal, normalize it. */ 61 ix = asuint (x * 0x1p23f); 62 ix -= 23 << 23; 63 } 64 65 /* x = 2^k z; where z is in range [OFF,2*OFF] and exact. 66 The range is split into N subintervals. 67 The ith subinterval contains z and c is near its center. */ 68 tmp = ix - OFF; 69 i = (tmp >> (23 - LOGF_TABLE_BITS)) % N; 70 k = (int32_t) tmp >> 23; /* arithmetic shift. */ 71 iz = ix - (tmp & 0xff800000); 72 invc = T[i].invc; 73 logc = T[i].logc; 74 z = (double_t) asfloat (iz); 75 76 /* log(x) = log1p(z/c-1) + log(c) + k*Ln2. */ 77 r = z * invc - 1; 78 y0 = logc + (double_t) k * Ln2; 79 80 /* Pipelined polynomial evaluation to approximate log1p(r). */ 81 r2 = r * r; 82 y = A[1] * r + A[2]; 83 y = A[0] * r2 + y; 84 y = y * r2 + (y0 + r); 85 86 /* Multiply by 1/log(10). */ 87 y = y * InvLn10; 88 89 return eval_as_float (y); 90 } 91 92 TEST_SIG (S, F, 1, log10, 0.01, 11.1) 93 TEST_ULP (log10f, 0.30) 94 TEST_ULP_NONNEAREST (log10f, 0.5) 95 TEST_INTERVAL (log10f, 0, 0xffff0000, 10000) 96 TEST_INTERVAL (log10f, 0x1p-127, 0x1p-26, 50000) 97 TEST_INTERVAL (log10f, 0x1p-26, 0x1p3, 50000) 98 TEST_INTERVAL (log10f, 0x1p-4, 0x1p4, 50000) 99 TEST_INTERVAL (log10f, 0, inf, 50000) 100