• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Double-precision 10^x function ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/math/exp10.h"
10 #include "common_constants.h" // Lookup tables EXP2_MID1 and EXP_M2.
11 #include "explogxf.h"         // ziv_test_denorm.
12 #include "src/__support/CPP/bit.h"
13 #include "src/__support/CPP/optional.h"
14 #include "src/__support/FPUtil/FEnvImpl.h"
15 #include "src/__support/FPUtil/FPBits.h"
16 #include "src/__support/FPUtil/PolyEval.h"
17 #include "src/__support/FPUtil/double_double.h"
18 #include "src/__support/FPUtil/dyadic_float.h"
19 #include "src/__support/FPUtil/multiply_add.h"
20 #include "src/__support/FPUtil/nearest_integer.h"
21 #include "src/__support/FPUtil/rounding_mode.h"
22 #include "src/__support/FPUtil/triple_double.h"
23 #include "src/__support/common.h"
24 #include "src/__support/integer_literals.h"
25 #include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
26 
27 #include <errno.h>
28 
29 namespace LIBC_NAMESPACE {
30 
31 using fputil::DoubleDouble;
32 using fputil::TripleDouble;
33 using Float128 = typename fputil::DyadicFloat<128>;
34 
35 using LIBC_NAMESPACE::operator""_u128;
36 
37 // log2(10)
38 constexpr double LOG2_10 = 0x1.a934f0979a371p+1;
39 
40 // -2^-12 * log10(2)
41 // > a = -2^-12 * log10(2);
42 // > b = round(a, 32, RN);
43 // > c = round(a - b, 32, RN);
44 // > d = round(a - b - c, D, RN);
45 // Errors < 1.5 * 2^-144
46 constexpr double MLOG10_2_EXP2_M12_HI = -0x1.3441350ap-14;
47 constexpr double MLOG10_2_EXP2_M12_MID = 0x1.0c0219dc1da99p-51;
48 constexpr double MLOG10_2_EXP2_M12_MID_32 = 0x1.0c0219dcp-51;
49 constexpr double MLOG10_2_EXP2_M12_LO = 0x1.da994fd20dba2p-87;
50 
51 // Error bounds:
52 // Errors when using double precision.
53 constexpr double ERR_D = 0x1.8p-63;
54 
55 // Errors when using double-double precision.
56 constexpr double ERR_DD = 0x1.8p-99;
57 
58 namespace {
59 
60 // Polynomial approximations with double precision.  Generated by Sollya with:
61 // > P = fpminimax((10^x - 1)/x, 3, [|D...|], [-2^-14, 2^-14]);
62 // > P;
63 // Error bounds:
64 //   | output - (10^dx - 1) / dx | < 2^-52.
poly_approx_d(double dx)65 LIBC_INLINE double poly_approx_d(double dx) {
66   // dx^2
67   double dx2 = dx * dx;
68   double c0 =
69       fputil::multiply_add(dx, 0x1.53524c73cea6ap+1, 0x1.26bb1bbb55516p+1);
70   double c1 =
71       fputil::multiply_add(dx, 0x1.2bd75cc6afc65p+0, 0x1.0470587aa264cp+1);
72   double p = fputil::multiply_add(dx2, c1, c0);
73   return p;
74 }
75 
76 // Polynomial approximation with double-double precision.  Generated by Solya
77 // with:
78 // > P = fpminimax((10^x - 1)/x, 5, [|DD...|], [-2^-14, 2^-14]);
79 // Error bounds:
80 //   | output - 10^(dx) | < 2^-101
poly_approx_dd(const DoubleDouble & dx)81 DoubleDouble poly_approx_dd(const DoubleDouble &dx) {
82   // Taylor polynomial.
83   constexpr DoubleDouble COEFFS[] = {
84       {0, 0x1p0},
85       {-0x1.f48ad494e927bp-53, 0x1.26bb1bbb55516p1},
86       {-0x1.e2bfab3191cd2p-53, 0x1.53524c73cea69p1},
87       {0x1.80fb65ec3b503p-53, 0x1.0470591de2ca4p1},
88       {0x1.338fc05e21e55p-54, 0x1.2bd7609fd98c4p0},
89       {0x1.d4ea116818fbp-56, 0x1.1429ffd519865p-1},
90       {-0x1.872a8ff352077p-57, 0x1.a7ed70847c8b3p-3},
91 
92   };
93 
94   DoubleDouble p = fputil::polyeval(dx, COEFFS[0], COEFFS[1], COEFFS[2],
95                                     COEFFS[3], COEFFS[4], COEFFS[5], COEFFS[6]);
96   return p;
97 }
98 
99 // Polynomial approximation with 128-bit precision:
100 // Return exp(dx) ~ 1 + a0 * dx + a1 * dx^2 + ... + a6 * dx^7
101 // For |dx| < 2^-14:
102 //   | output - 10^dx | < 1.5 * 2^-124.
poly_approx_f128(const Float128 & dx)103 Float128 poly_approx_f128(const Float128 &dx) {
104   constexpr Float128 COEFFS_128[]{
105       {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
106       {Sign::POS, -126, 0x935d8ddd'aaa8ac16'ea56d62b'82d30a2d_u128},
107       {Sign::POS, -126, 0xa9a92639'e753443a'80a99ce7'5f4d5bdb_u128},
108       {Sign::POS, -126, 0x82382c8e'f1652304'6a4f9d7d'bf6c9635_u128},
109       {Sign::POS, -124, 0x12bd7609'fd98c44c'34578701'9216c7af_u128},
110       {Sign::POS, -127, 0x450a7ff4'7535d889'cc41ed7e'0d27aee5_u128},
111       {Sign::POS, -130, 0xd3f6b844'702d636b'8326bb91'a6e7601d_u128},
112       {Sign::POS, -130, 0x45b937f0'd05bb1cd'fa7b46df'314112a9_u128},
113   };
114 
115   Float128 p = fputil::polyeval(dx, COEFFS_128[0], COEFFS_128[1], COEFFS_128[2],
116                                 COEFFS_128[3], COEFFS_128[4], COEFFS_128[5],
117                                 COEFFS_128[6], COEFFS_128[7]);
118   return p;
119 }
120 
121 // Compute 10^(x) using 128-bit precision.
122 // TODO(lntue): investigate triple-double precision implementation for this
123 // step.
exp10_f128(double x,double kd,int idx1,int idx2)124 Float128 exp10_f128(double x, double kd, int idx1, int idx2) {
125   double t1 = fputil::multiply_add(kd, MLOG10_2_EXP2_M12_HI, x); // exact
126   double t2 = kd * MLOG10_2_EXP2_M12_MID_32;                     // exact
127   double t3 = kd * MLOG10_2_EXP2_M12_LO; // Error < 2^-144
128 
129   Float128 dx = fputil::quick_add(
130       Float128(t1), fputil::quick_add(Float128(t2), Float128(t3)));
131 
132   // TODO: Skip recalculating exp_mid1 and exp_mid2.
133   Float128 exp_mid1 =
134       fputil::quick_add(Float128(EXP2_MID1[idx1].hi),
135                         fputil::quick_add(Float128(EXP2_MID1[idx1].mid),
136                                           Float128(EXP2_MID1[idx1].lo)));
137 
138   Float128 exp_mid2 =
139       fputil::quick_add(Float128(EXP2_MID2[idx2].hi),
140                         fputil::quick_add(Float128(EXP2_MID2[idx2].mid),
141                                           Float128(EXP2_MID2[idx2].lo)));
142 
143   Float128 exp_mid = fputil::quick_mul(exp_mid1, exp_mid2);
144 
145   Float128 p = poly_approx_f128(dx);
146 
147   Float128 r = fputil::quick_mul(exp_mid, p);
148 
149   r.exponent += static_cast<int>(kd) >> 12;
150 
151   return r;
152 }
153 
154 // Compute 10^x with double-double precision.
exp10_double_double(double x,double kd,const DoubleDouble & exp_mid)155 DoubleDouble exp10_double_double(double x, double kd,
156                                  const DoubleDouble &exp_mid) {
157   // Recalculate dx:
158   //   dx = x - k * 2^-12 * log10(2)
159   double t1 = fputil::multiply_add(kd, MLOG10_2_EXP2_M12_HI, x); // exact
160   double t2 = kd * MLOG10_2_EXP2_M12_MID_32;                     // exact
161   double t3 = kd * MLOG10_2_EXP2_M12_LO; // Error < 2^-140
162 
163   DoubleDouble dx = fputil::exact_add(t1, t2);
164   dx.lo += t3;
165 
166   // Degree-6 polynomial approximation in double-double precision.
167   // | p - 10^x | < 2^-103.
168   DoubleDouble p = poly_approx_dd(dx);
169 
170   // Error bounds: 2^-102.
171   DoubleDouble r = fputil::quick_mult(exp_mid, p);
172 
173   return r;
174 }
175 
176 // When output is denormal.
exp10_denorm(double x)177 double exp10_denorm(double x) {
178   // Range reduction.
179   double tmp = fputil::multiply_add(x, LOG2_10, 0x1.8000'0000'4p21);
180   int k = static_cast<int>(cpp::bit_cast<uint64_t>(tmp) >> 19);
181   double kd = static_cast<double>(k);
182 
183   uint32_t idx1 = (k >> 6) & 0x3f;
184   uint32_t idx2 = k & 0x3f;
185 
186   int hi = k >> 12;
187 
188   DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};
189   DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};
190   DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);
191 
192   // |dx| < 1.5 * 2^-15 + 2^-31 < 2^-14
193   double lo_h = fputil::multiply_add(kd, MLOG10_2_EXP2_M12_HI, x); // exact
194   double dx = fputil::multiply_add(kd, MLOG10_2_EXP2_M12_MID, lo_h);
195 
196   double mid_lo = dx * exp_mid.hi;
197 
198   // Approximate (10^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.
199   double p = poly_approx_d(dx);
200 
201   double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
202 
203   if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, ERR_D);
204       LIBC_LIKELY(r.has_value()))
205     return r.value();
206 
207   // Use double-double
208   DoubleDouble r_dd = exp10_double_double(x, kd, exp_mid);
209 
210   if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, ERR_DD);
211       LIBC_LIKELY(r.has_value()))
212     return r.value();
213 
214   // Use 128-bit precision
215   Float128 r_f128 = exp10_f128(x, kd, idx1, idx2);
216 
217   return static_cast<double>(r_f128);
218 }
219 
220 // Check for exceptional cases when:
221 //  * log10(1 - 2^-54) < x < log10(1 + 2^-53)
222 //  * x >= log10(2^1024)
223 //  * x <= log10(2^-1022)
224 //  * x is inf or nan
set_exceptional(double x)225 double set_exceptional(double x) {
226   using FPBits = typename fputil::FPBits<double>;
227   FPBits xbits(x);
228 
229   uint64_t x_u = xbits.uintval();
230   uint64_t x_abs = xbits.abs().uintval();
231 
232   // |x| < log10(1 + 2^-53)
233   if (x_abs <= 0x3c8bcb7b1526e50e) {
234     // 10^(x) ~ 1 + x/2
235     return fputil::multiply_add(x, 0.5, 1.0);
236   }
237 
238   // x <= log10(2^-1022) || x >= log10(2^1024) or inf/nan.
239   if (x_u >= 0xc0733a7146f72a42) {
240     // x <= log10(2^-1075) or -inf/nan
241     if (x_u > 0xc07439b746e36b52) {
242       // exp(-Inf) = 0
243       if (xbits.is_inf())
244         return 0.0;
245 
246       // exp(nan) = nan
247       if (xbits.is_nan())
248         return x;
249 
250       if (fputil::quick_get_round() == FE_UPWARD)
251         return FPBits::min_subnormal().get_val();
252       fputil::set_errno_if_required(ERANGE);
253       fputil::raise_except_if_required(FE_UNDERFLOW);
254       return 0.0;
255     }
256 
257     return exp10_denorm(x);
258   }
259 
260   // x >= log10(2^1024) or +inf/nan
261   // x is finite
262   if (x_u < 0x7ff0'0000'0000'0000ULL) {
263     int rounding = fputil::quick_get_round();
264     if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)
265       return FPBits::max_normal().get_val();
266 
267     fputil::set_errno_if_required(ERANGE);
268     fputil::raise_except_if_required(FE_OVERFLOW);
269   }
270   // x is +inf or nan
271   return x + FPBits::inf().get_val();
272 }
273 
274 } // namespace
275 
276 LLVM_LIBC_FUNCTION(double, exp10, (double x)) {
277   using FPBits = typename fputil::FPBits<double>;
278   FPBits xbits(x);
279 
280   uint64_t x_u = xbits.uintval();
281 
282   // x <= log10(2^-1022) or x >= log10(2^1024) or
283   // log10(1 - 2^-54) < x < log10(1 + 2^-53).
284   if (LIBC_UNLIKELY(x_u >= 0xc0733a7146f72a42 ||
285                     (x_u <= 0xbc7bcb7b1526e50e && x_u >= 0x40734413509f79ff) ||
286                     x_u < 0x3c8bcb7b1526e50e)) {
287     return set_exceptional(x);
288   }
289 
290   // Now log10(2^-1075) < x <= log10(1 - 2^-54) or
291   //     log10(1 + 2^-53) < x < log10(2^1024)
292 
293   // Range reduction:
294   // Let x = log10(2) * (hi + mid1 + mid2) + lo
295   // in which:
296   //   hi is an integer
297   //   mid1 * 2^6 is an integer
298   //   mid2 * 2^12 is an integer
299   // then:
300   //   10^(x) = 2^hi * 2^(mid1) * 2^(mid2) * 10^(lo).
301   // With this formula:
302   //   - multiplying by 2^hi is exact and cheap, simply by adding the exponent
303   //     field.
304   //   - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.
305   //   - 10^(lo) ~ 1 + a0*lo + a1 * lo^2 + ...
306   //
307   // We compute (hi + mid1 + mid2) together by perform the rounding on
308   //   x * log2(10) * 2^12.
309   // Since |x| < |log10(2^-1075)| < 2^9,
310   //   |x * 2^12| < 2^9 * 2^12 < 2^21,
311   // So we can fit the rounded result round(x * 2^12) in int32_t.
312   // Thus, the goal is to be able to use an additional addition and fixed width
313   // shift to get an int32_t representing round(x * 2^12).
314   //
315   // Assuming int32_t using 2-complement representation, since the mantissa part
316   // of a double precision is unsigned with the leading bit hidden, if we add an
317   // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^23 to the product, the
318   // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be
319   // considered as a proper 2-complement representations of x*2^12.
320   //
321   // One small problem with this approach is that the sum (x*2^12 + C) in
322   // double precision is rounded to the least significant bit of the dorminant
323   // factor C.  In order to minimize the rounding errors from this addition, we
324   // want to minimize e1.  Another constraint that we want is that after
325   // shifting the mantissa so that the least significant bit of int32_t
326   // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without
327   // any adjustment.  So combining these 2 requirements, we can choose
328   //   C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence
329   // after right shifting the mantissa, the resulting int32_t has correct sign.
330   // With this choice of C, the number of mantissa bits we need to shift to the
331   // right is: 52 - 33 = 19.
332   //
333   // Moreover, since the integer right shifts are equivalent to rounding down,
334   // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-
335   // +infinity.  So in particular, we can compute:
336   //   hmm = x * 2^12 + C,
337   // where C = 2^33 + 2^32 + 2^-1, then if
338   //   k = int32_t(lower 51 bits of double(x * 2^12 + C) >> 19),
339   // the reduced argument:
340   //   lo = x - log10(2) * 2^-12 * k is bounded by:
341   //   |lo|  = |x - log10(2) * 2^-12 * k|
342   //         = log10(2) * 2^-12 * | x * log2(10) * 2^12 - k |
343   //        <= log10(2) * 2^-12 * (2^-1 + 2^-19)
344   //         < 1.5 * 2^-2 * (2^-13 + 2^-31)
345   //         = 1.5 * (2^-15 * 2^-31)
346   //
347   // Finally, notice that k only uses the mantissa of x * 2^12, so the
348   // exponent 2^12 is not needed.  So we can simply define
349   //   C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and
350   //   k = int32_t(lower 51 bits of double(x + C) >> 19).
351 
352   // Rounding errors <= 2^-31.
353   double tmp = fputil::multiply_add(x, LOG2_10, 0x1.8000'0000'4p21);
354   int k = static_cast<int>(cpp::bit_cast<uint64_t>(tmp) >> 19);
355   double kd = static_cast<double>(k);
356 
357   uint32_t idx1 = (k >> 6) & 0x3f;
358   uint32_t idx2 = k & 0x3f;
359 
360   int hi = k >> 12;
361 
362   DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};
363   DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};
364   DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);
365 
366   // |dx| < 1.5 * 2^-15 + 2^-31 < 2^-14
367   double lo_h = fputil::multiply_add(kd, MLOG10_2_EXP2_M12_HI, x); // exact
368   double dx = fputil::multiply_add(kd, MLOG10_2_EXP2_M12_MID, lo_h);
369 
370   // We use the degree-4 polynomial to approximate 10^(lo):
371   //   10^(lo) ~ 1 + a0 * lo + a1 * lo^2 + a2 * lo^3 + a3 * lo^4
372   //           = 1 + lo * P(lo)
373   // So that the errors are bounded by:
374   //   |P(lo) - (10^lo - 1)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58
375   // Let P_ be an evaluation of P where all intermediate computations are in
376   // double precision.  Using either Horner's or Estrin's schemes, the evaluated
377   // errors can be bounded by:
378   //      |P_(lo) - P(lo)| < 2^-51
379   //   => |lo * P_(lo) - (2^lo - 1) | < 2^-65
380   //   => 2^(mid1 + mid2) * |lo * P_(lo) - expm1(lo)| < 2^-64.
381   // Since we approximate
382   //   2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,
383   // We use the expression:
384   //    (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~
385   //  ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)
386   // with errors bounded by 2^-64.
387 
388   double mid_lo = dx * exp_mid.hi;
389 
390   // Approximate (10^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.
391   double p = poly_approx_d(dx);
392 
393   double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
394 
395   double upper = exp_mid.hi + (lo + ERR_D);
396   double lower = exp_mid.hi + (lo - ERR_D);
397 
398   if (LIBC_LIKELY(upper == lower)) {
399     // To multiply by 2^hi, a fast way is to simply add hi to the exponent
400     // field.
401     int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
402     double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper));
403     return r;
404   }
405 
406   // Exact outputs when x = 1, 2, ..., 22 + hard to round with x = 23.
407   // Quick check mask: 0x800f'ffffU = ~(bits of 1.0 | ... | bits of 23.0)
408   if (LIBC_UNLIKELY((x_u & 0x8000'ffff'ffff'ffffULL) == 0ULL)) {
409     switch (x_u) {
410     case 0x3ff0000000000000: // x = 1.0
411       return 10.0;
412     case 0x4000000000000000: // x = 2.0
413       return 100.0;
414     case 0x4008000000000000: // x = 3.0
415       return 1'000.0;
416     case 0x4010000000000000: // x = 4.0
417       return 10'000.0;
418     case 0x4014000000000000: // x = 5.0
419       return 100'000.0;
420     case 0x4018000000000000: // x = 6.0
421       return 1'000'000.0;
422     case 0x401c000000000000: // x = 7.0
423       return 10'000'000.0;
424     case 0x4020000000000000: // x = 8.0
425       return 100'000'000.0;
426     case 0x4022000000000000: // x = 9.0
427       return 1'000'000'000.0;
428     case 0x4024000000000000: // x = 10.0
429       return 10'000'000'000.0;
430     case 0x4026000000000000: // x = 11.0
431       return 100'000'000'000.0;
432     case 0x4028000000000000: // x = 12.0
433       return 1'000'000'000'000.0;
434     case 0x402a000000000000: // x = 13.0
435       return 10'000'000'000'000.0;
436     case 0x402c000000000000: // x = 14.0
437       return 100'000'000'000'000.0;
438     case 0x402e000000000000: // x = 15.0
439       return 1'000'000'000'000'000.0;
440     case 0x4030000000000000: // x = 16.0
441       return 10'000'000'000'000'000.0;
442     case 0x4031000000000000: // x = 17.0
443       return 100'000'000'000'000'000.0;
444     case 0x4032000000000000: // x = 18.0
445       return 1'000'000'000'000'000'000.0;
446     case 0x4033000000000000: // x = 19.0
447       return 10'000'000'000'000'000'000.0;
448     case 0x4034000000000000: // x = 20.0
449       return 100'000'000'000'000'000'000.0;
450     case 0x4035000000000000: // x = 21.0
451       return 1'000'000'000'000'000'000'000.0;
452     case 0x4036000000000000: // x = 22.0
453       return 10'000'000'000'000'000'000'000.0;
454     case 0x4037000000000000: // x = 23.0
455       return 0x1.52d02c7e14af6p76 + x;
456     }
457   }
458 
459   // Use double-double
460   DoubleDouble r_dd = exp10_double_double(x, kd, exp_mid);
461 
462   double upper_dd = r_dd.hi + (r_dd.lo + ERR_DD);
463   double lower_dd = r_dd.hi + (r_dd.lo - ERR_DD);
464 
465   if (LIBC_LIKELY(upper_dd == lower_dd)) {
466     // To multiply by 2^hi, a fast way is to simply add hi to the exponent
467     // field.
468     int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
469     double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper_dd));
470     return r;
471   }
472 
473   // Use 128-bit precision
474   Float128 r_f128 = exp10_f128(x, kd, idx1, idx2);
475 
476   return static_cast<double>(r_f128);
477 }
478 
479 } // namespace LIBC_NAMESPACE
480