22 int length,
double& result)
24 if (length < 0 || std::fegetround() != FE_TONEAREST)
return false;
26 double correction = 0.0;
27 double absolute_residuals = 0.0;
28 const auto add = [&](
double value) {
29 const double next = sum + value;
31 correction += residual;
32 absolute_residuals += std::abs(residual);
35 for (
int i = 0; i < length; ++i) {
36 const double a = left[i], b = right[i];
37 uint64_t bits_a, bits_b;
38 std::memcpy(&bits_a, &a,
sizeof(a));
39 std::memcpy(&bits_b, &b,
sizeof(b));
40 bits_a &= UINT64_C(0x7fffffffffffffff);
41 bits_b &= UINT64_C(0x7fffffffffffffff);
42 if (bits_a >= UINT64_C(0x7ff0000000000000) ||
43 bits_b >= UINT64_C(0x7ff0000000000000))
45 if (bits_a == 0 || bits_b == 0)
continue;
46 if (std::abs(a) < 0x1p-400 || std::abs(a) > 0x1p400 ||
47 std::abs(b) < 0x1p-400 || std::abs(b) > 0x1p400)
49 const double product = a * b;
51 add(std::fma(a, b, -product));
53 if (absolute_residuals == 0.0) {
61 const double infinity = std::numeric_limits<double>::infinity();
62 const double bound = std::nextafter(
63 (
static_cast<double>(length) * 0x1p-51) * absolute_residuals, infinity);
64 const double rounded = sum + correction;
66 const double previous = std::nextafter(rounded, -infinity);
67 const double following = std::nextafter(rounded, infinity);
68 if (!std::isfinite(previous) || !std::isfinite(following))
return false;
69 const double lower_radius = (rounded - previous) * 0.5;
70 const double upper_radius = (following - rounded) * 0.5;
71 const double lower = std::nextafter(residual - bound, -infinity);
72 const double upper = std::nextafter(residual + bound, infinity);
73 if (lower > -lower_radius && upper < upper_radius) {