1//===-- Double-precision e^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/exp.h"
10#include "common_constants.h" // Lookup tables EXP_M1 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/config.h"
26#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
27
28namespace LIBC_NAMESPACE_DECL {
29
30using fputil::DoubleDouble;
31using fputil::TripleDouble;
32using Float128 = typename fputil::DyadicFloat<128>;
33
34using LIBC_NAMESPACE::operator""_u128;
35
36// log2(e)
37constexpr double LOG2_E = 0x1.71547652b82fep+0;
38
39// Error bounds:
40// Errors when using double precision.
41constexpr double ERR_D = 0x1.8p-63;
42
43#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
44// Errors when using double-double precision.
45constexpr double ERR_DD = 0x1.0p-99;
46#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
47
48// -2^-12 * log(2)
49// > a = -2^-12 * log(2);
50// > b = round(a, 30, RN);
51// > c = round(a - b, 30, RN);
52// > d = round(a - b - c, D, RN);
53// Errors < 1.5 * 2^-133
54constexpr double MLOG_2_EXP2_M12_HI = -0x1.62e42ffp-13;
55constexpr double MLOG_2_EXP2_M12_MID = 0x1.718432a1b0e26p-47;
56
57#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
58constexpr double MLOG_2_EXP2_M12_MID_30 = 0x1.718432ap-47;
59constexpr double MLOG_2_EXP2_M12_LO = 0x1.b0e2633fe0685p-79;
60#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
61
62namespace {
63
64// Polynomial approximations with double precision:
65// Return expm1(dx) / x ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
66// For |dx| < 2^-13 + 2^-30:
67// | output - expm1(dx) / dx | < 2^-51.
68LIBC_INLINE double poly_approx_d(double dx) {
69 // dx^2
70 double dx2 = dx * dx;
71 // c0 = 1 + dx / 2
72 double c0 = fputil::multiply_add(dx, 0.5, 1.0);
73 // c1 = 1/6 + dx / 24
74 double c1 =
75 fputil::multiply_add(dx, 0x1.5555555555555p-5, 0x1.5555555555555p-3);
76 // p = dx^2 * c1 + c0 = 1 + dx / 2 + dx^2 / 6 + dx^3 / 24
77 double p = fputil::multiply_add(dx2, c1, c0);
78 return p;
79}
80
81#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
82// Polynomial approximation with double-double precision:
83// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^6 / 720
84// For |dx| < 2^-13 + 2^-30:
85// | output - exp(dx) | < 2^-101
86DoubleDouble poly_approx_dd(const DoubleDouble &dx) {
87 // Taylor polynomial.
88 constexpr DoubleDouble COEFFS[] = {
89 {0, 0x1p0}, // 1
90 {0, 0x1p0}, // 1
91 {0, 0x1p-1}, // 1/2
92 {0x1.5555555555555p-57, 0x1.5555555555555p-3}, // 1/6
93 {0x1.5555555555555p-59, 0x1.5555555555555p-5}, // 1/24
94 {0x1.1111111111111p-63, 0x1.1111111111111p-7}, // 1/120
95 {-0x1.f49f49f49f49fp-65, 0x1.6c16c16c16c17p-10}, // 1/720
96 };
97
98 DoubleDouble p = fputil::polyeval(dx, COEFFS[0], COEFFS[1], COEFFS[2],
99 COEFFS[3], COEFFS[4], COEFFS[5], COEFFS[6]);
100 return p;
101}
102
103// Polynomial approximation with 128-bit precision:
104// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^7 / 5040
105// For |dx| < 2^-13 + 2^-30:
106// | output - exp(dx) | < 2^-126.
107Float128 poly_approx_f128(const Float128 &dx) {
108 constexpr Float128 COEFFS_128[]{
109 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
110 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
111 {Sign::POS, -128, 0x80000000'00000000'00000000'00000000_u128}, // 0.5
112 {Sign::POS, -130, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/6
113 {Sign::POS, -132, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/24
114 {Sign::POS, -134, 0x88888888'88888888'88888888'88888889_u128}, // 1/120
115 {Sign::POS, -137, 0xb60b60b6'0b60b60b'60b60b60'b60b60b6_u128}, // 1/720
116 {Sign::POS, -140, 0xd00d00d0'0d00d00d'00d00d00'd00d00d0_u128}, // 1/5040
117 };
118
119 Float128 p = fputil::polyeval(dx, COEFFS_128[0], COEFFS_128[1], COEFFS_128[2],
120 COEFFS_128[3], COEFFS_128[4], COEFFS_128[5],
121 COEFFS_128[6], COEFFS_128[7]);
122 return p;
123}
124
125// Compute exp(x) using 128-bit precision.
126// TODO(lntue): investigate triple-double precision implementation for this
127// step.
128Float128 exp_f128(double x, double kd, int idx1, int idx2) {
129 // Recalculate dx:
130
131 double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
132 double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact
133 double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-133
134
135 Float128 dx = fputil::quick_add(
136 Float128(t1), fputil::quick_add(Float128(t2), Float128(t3)));
137
138 // TODO: Skip recalculating exp_mid1 and exp_mid2.
139 Float128 exp_mid1 =
140 fputil::quick_add(Float128(EXP2_MID1[idx1].hi),
141 fputil::quick_add(Float128(EXP2_MID1[idx1].mid),
142 Float128(EXP2_MID1[idx1].lo)));
143
144 Float128 exp_mid2 =
145 fputil::quick_add(Float128(EXP2_MID2[idx2].hi),
146 fputil::quick_add(Float128(EXP2_MID2[idx2].mid),
147 Float128(EXP2_MID2[idx2].lo)));
148
149 Float128 exp_mid = fputil::quick_mul(exp_mid1, exp_mid2);
150
151 Float128 p = poly_approx_f128(dx);
152
153 Float128 r = fputil::quick_mul(exp_mid, p);
154
155 r.exponent += static_cast<int>(kd) >> 12;
156
157 return r;
158}
159
160// Compute exp(x) with double-double precision.
161DoubleDouble exp_double_double(double x, double kd,
162 const DoubleDouble &exp_mid) {
163 // Recalculate dx:
164 // dx = x - k * 2^-12 * log(2)
165 double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
166 double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact
167 double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-130
168
169 DoubleDouble dx = fputil::exact_add(t1, t2);
170 dx.lo += t3;
171
172 // Degree-6 Taylor polynomial approximation in double-double precision.
173 // | p - exp(x) | < 2^-100.
174 DoubleDouble p = poly_approx_dd(dx);
175
176 // Error bounds: 2^-99.
177 DoubleDouble r = fputil::quick_mult(exp_mid, p);
178
179 return r;
180}
181#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
182
183// Check for exceptional cases when
184// |x| <= 2^-53 or x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9
185double set_exceptional(double x) {
186 using FPBits = typename fputil::FPBits<double>;
187 FPBits xbits(x);
188
189 uint64_t x_u = xbits.uintval();
190 uint64_t x_abs = xbits.abs().uintval();
191
192 // |x| <= 2^-53
193 if (x_abs <= 0x3ca0'0000'0000'0000ULL) {
194 // exp(x) ~ 1 + x
195 return 1 + x;
196 }
197
198 // x <= log(2^-1075) || x >= 0x1.6232bdd7abcd3p+9 or inf/nan.
199
200 // x <= log(2^-1075) or -inf/nan
201 if (x_u >= 0xc087'4910'd52d'3052ULL) {
202 // exp(-Inf) = 0
203 if (xbits.is_inf())
204 return 0.0;
205
206 // exp(nan) = nan
207 if (xbits.is_nan())
208 return x;
209
210 if (fputil::quick_get_round() == FE_UPWARD)
211 return FPBits::min_subnormal().get_val();
212 fputil::set_errno_if_required(ERANGE);
213 fputil::raise_except_if_required(FE_UNDERFLOW);
214 return 0.0;
215 }
216
217 // x >= round(log(MAX_NORMAL), D, RU) = 0x1.62e42fefa39fp+9 or +inf/nan
218 // x is finite
219 if (x_u < 0x7ff0'0000'0000'0000ULL) {
220 int rounding = fputil::quick_get_round();
221 if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)
222 return FPBits::max_normal().get_val();
223
224 fputil::set_errno_if_required(ERANGE);
225 fputil::raise_except_if_required(FE_OVERFLOW);
226 }
227 // x is +inf or nan
228 return x + FPBits::inf().get_val();
229}
230
231} // namespace
232
233LLVM_LIBC_FUNCTION(double, exp, (double x)) {
234 using FPBits = typename fputil::FPBits<double>;
235 FPBits xbits(x);
236
237 uint64_t x_u = xbits.uintval();
238
239 // Upper bound: max normal number = 2^1023 * (2 - 2^-52)
240 // > round(log (2^1023 ( 2 - 2^-52 )), D, RU) = 0x1.62e42fefa39fp+9
241 // > round(log (2^1023 ( 2 - 2^-52 )), D, RD) = 0x1.62e42fefa39efp+9
242 // > round(log (2^1023 ( 2 - 2^-52 )), D, RN) = 0x1.62e42fefa39efp+9
243 // > round(exp(0x1.62e42fefa39fp+9), D, RN) = infty
244
245 // Lower bound: min denormal number / 2 = 2^-1075
246 // > round(log(2^-1075), D, RN) = -0x1.74910d52d3052p9
247
248 // Another lower bound: min normal number = 2^-1022
249 // > round(log(2^-1022), D, RN) = -0x1.6232bdd7abcd2p9
250
251 // x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9 or |x| < 2^-53.
252 if (LIBC_UNLIKELY(x_u >= 0xc0874910d52d3052 ||
253 (x_u < 0xbca0000000000000 && x_u >= 0x40862e42fefa39f0) ||
254 x_u < 0x3ca0000000000000)) {
255 return set_exceptional(x);
256 }
257
258 // Now log(2^-1075) <= x <= -2^-53 or 2^-53 <= x < log(2^1023 * (2 - 2^-52))
259
260 // Range reduction:
261 // Let x = log(2) * (hi + mid1 + mid2) + lo
262 // in which:
263 // hi is an integer
264 // mid1 * 2^6 is an integer
265 // mid2 * 2^12 is an integer
266 // then:
267 // exp(x) = 2^hi * 2^(mid1) * 2^(mid2) * exp(lo).
268 // With this formula:
269 // - multiplying by 2^hi is exact and cheap, simply by adding the exponent
270 // field.
271 // - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.
272 // - exp(lo) ~ 1 + lo + a0 * lo^2 + ...
273 //
274 // They can be defined by:
275 // hi + mid1 + mid2 = 2^(-12) * round(2^12 * log_2(e) * x)
276 // If we store L2E = round(log2(e), D, RN), then:
277 // log2(e) - L2E ~ 1.5 * 2^(-56)
278 // So the errors when computing in double precision is:
279 // | x * 2^12 * log_2(e) - D(x * 2^12 * L2E) | <=
280 // <= | x * 2^12 * log_2(e) - x * 2^12 * L2E | +
281 // + | x * 2^12 * L2E - D(x * 2^12 * L2E) |
282 // <= 2^12 * ( |x| * 1.5 * 2^-56 + eps(x)) for RN
283 // 2^12 * ( |x| * 1.5 * 2^-56 + 2*eps(x)) for other rounding modes.
284 // So if:
285 // hi + mid1 + mid2 = 2^(-12) * round(x * 2^12 * L2E) is computed entirely
286 // in double precision, the reduced argument:
287 // lo = x - log(2) * (hi + mid1 + mid2) is bounded by:
288 // |lo| <= 2^-13 + (|x| * 1.5 * 2^-56 + 2*eps(x))
289 // < 2^-13 + (1.5 * 2^9 * 1.5 * 2^-56 + 2*2^(9 - 52))
290 // < 2^-13 + 2^-41
291 //
292
293 // The following trick computes the round(x * L2E) more efficiently
294 // than using the rounding instructions, with the tradeoff for less accuracy,
295 // and hence a slightly larger range for the reduced argument `lo`.
296 //
297 // To be precise, since |x| < |log(2^-1075)| < 1.5 * 2^9,
298 // |x * 2^12 * L2E| < 1.5 * 2^9 * 1.5 < 2^23,
299 // So we can fit the rounded result round(x * 2^12 * L2E) in int32_t.
300 // Thus, the goal is to be able to use an additional addition and fixed width
301 // shift to get an int32_t representing round(x * 2^12 * L2E).
302 //
303 // Assuming int32_t using 2-complement representation, since the mantissa part
304 // of a double precision is unsigned with the leading bit hidden, if we add an
305 // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the
306 // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be
307 // considered as a proper 2-complement representations of x*2^12*L2E.
308 //
309 // One small problem with this approach is that the sum (x*2^12*L2E + C) in
310 // double precision is rounded to the least significant bit of the dorminant
311 // factor C. In order to minimize the rounding errors from this addition, we
312 // want to minimize e1. Another constraint that we want is that after
313 // shifting the mantissa so that the least significant bit of int32_t
314 // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without
315 // any adjustment. So combining these 2 requirements, we can choose
316 // C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence
317 // after right shifting the mantissa, the resulting int32_t has correct sign.
318 // With this choice of C, the number of mantissa bits we need to shift to the
319 // right is: 52 - 33 = 19.
320 //
321 // Moreover, since the integer right shifts are equivalent to rounding down,
322 // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-
323 // +infinity. So in particular, we can compute:
324 // hmm = x * 2^12 * L2E + C,
325 // where C = 2^33 + 2^32 + 2^-1, then if
326 // k = int32_t(lower 51 bits of double(x * 2^12 * L2E + C) >> 19),
327 // the reduced argument:
328 // lo = x - log(2) * 2^-12 * k is bounded by:
329 // |lo| <= 2^-13 + 2^-41 + 2^-12*2^-19
330 // = 2^-13 + 2^-31 + 2^-41.
331 //
332 // Finally, notice that k only uses the mantissa of x * 2^12 * L2E, so the
333 // exponent 2^12 is not needed. So we can simply define
334 // C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and
335 // k = int32_t(lower 51 bits of double(x * L2E + C) >> 19).
336
337 // Rounding errors <= 2^-31 + 2^-41.
338 double tmp = fputil::multiply_add(x, LOG2_E, 0x1.8000'0000'4p21);
339 int k = static_cast<int>(cpp::bit_cast<uint64_t>(tmp) >> 19);
340 double kd = static_cast<double>(k);
341
342 uint32_t idx1 = (k >> 6) & 0x3f;
343 uint32_t idx2 = k & 0x3f;
344 int hi = k >> 12;
345
346 bool denorm = (hi <= -1022);
347
348 DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};
349 DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};
350
351 DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);
352
353 // |x - (hi + mid1 + mid2) * log(2) - dx| < 2^11 * eps(M_LOG_2_EXP2_M12.lo)
354 // = 2^11 * 2^-13 * 2^-52
355 // = 2^-54.
356 // |dx| < 2^-13 + 2^-30.
357 double lo_h = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
358 double dx = fputil::multiply_add(kd, MLOG_2_EXP2_M12_MID, lo_h);
359
360 // We use the degree-4 Taylor polynomial to approximate exp(lo):
361 // exp(lo) ~ 1 + lo + lo^2 / 2 + lo^3 / 6 + lo^4 / 24 = 1 + lo * P(lo)
362 // So that the errors are bounded by:
363 // |P(lo) - expm1(lo)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58
364 // Let P_ be an evaluation of P where all intermediate computations are in
365 // double precision. Using either Horner's or Estrin's schemes, the evaluated
366 // errors can be bounded by:
367 // |P_(dx) - P(dx)| < 2^-51
368 // => |dx * P_(dx) - expm1(lo) | < 1.5 * 2^-64
369 // => 2^(mid1 + mid2) * |dx * P_(dx) - expm1(lo)| < 1.5 * 2^-63.
370 // Since we approximate
371 // 2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,
372 // We use the expression:
373 // (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~
374 // ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)
375 // with errors bounded by 1.5 * 2^-63.
376
377 double mid_lo = dx * exp_mid.hi;
378
379 // Approximate expm1(dx)/dx ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
380 double p = poly_approx_d(dx);
381
382 double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
383
384#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
385 if (LIBC_UNLIKELY(denorm)) {
386 return ziv_test_denorm</*SKIP_ZIV_TEST=*/true>(hi, exp_mid.hi, lo, ERR_D)
387 .value();
388 } else {
389 // to multiply by 2^hi, a fast way is to simply add hi to the exponent
390 // field.
391 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
392 double r =
393 cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(exp_mid.hi + lo));
394 return r;
395 }
396#else
397 if (LIBC_UNLIKELY(denorm)) {
398 if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, ERR_D);
399 LIBC_LIKELY(r.has_value()))
400 return r.value();
401 } else {
402 double upper = exp_mid.hi + (lo + ERR_D);
403 double lower = exp_mid.hi + (lo - ERR_D);
404
405 if (LIBC_LIKELY(upper == lower)) {
406 // to multiply by 2^hi, a fast way is to simply add hi to the exponent
407 // field.
408 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
409 double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper));
410 return r;
411 }
412 }
413
414 // Use double-double
415 DoubleDouble r_dd = exp_double_double(x, kd, exp_mid);
416
417 if (LIBC_UNLIKELY(denorm)) {
418 if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, ERR_DD);
419 LIBC_LIKELY(r.has_value()))
420 return r.value();
421 } else {
422 double upper_dd = r_dd.hi + (r_dd.lo + ERR_DD);
423 double lower_dd = r_dd.hi + (r_dd.lo - ERR_DD);
424
425 if (LIBC_LIKELY(upper_dd == lower_dd)) {
426 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
427 double r =
428 cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper_dd));
429 return r;
430 }
431 }
432
433 // Use 128-bit precision
434 Float128 r_f128 = exp_f128(x, kd, idx1, idx2);
435
436 return static_cast<double>(r_f128);
437#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
438}
439
440} // namespace LIBC_NAMESPACE_DECL
441

source code of libc/src/math/generic/exp.cpp