Loading...
Searching...
No Matches
ExtendedReal.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4//
5// Working precision for the bordered variance certificate.
6//
7// Native long double is the working type when it is an IEEE binary format
8// with more than 53 significand bits (x87 extended, binary128). Where long
9// double is binary64 (macOS arm64, MSVC, and gcc/clang -mlong-double-64),
10// the working type is a Dekker double-double. Its spacing at 1 is 2^-105.
11// Dekker addition and multiplication are faithful to two such units, so the
12// enclosure models the type with unit roundoff u = 2^-104.
13//
14// A platform whose double is not IEEE binary64 cannot form this fallback.
15// The certificate then reports certified = 0.
16
17#ifndef GPR_ML_GP_EXTENDED_REAL_H_
18#define GPR_ML_GP_EXTENDED_REAL_H_
19
20#include <Eigen/Core>
21#include <algorithm>
22#include <cmath>
23#include <limits>
24#include <stdexcept>
25#include <type_traits>
26
27namespace gpr {
28namespace extended {
29
31 double hi = 0.0;
32 double lo = 0.0;
33
34 constexpr DoubleDouble() = default;
35 constexpr DoubleDouble(double high, double low) : hi(high), lo(low) { }
36 constexpr DoubleDouble(double value) : hi(value), lo(0.0) { }
37 constexpr DoubleDouble(int value) : hi(static_cast<double>(value)), lo(0.0)
38 {
39 }
40 // Eigen::Index is a 64-bit integer. A single constructor keeps
41 // static_cast<DoubleDouble>(index) unambiguous next to the double and
42 // long double constructors. Values are exact for magnitudes up to 2^53,
43 // which covers every matrix order this certificate accepts.
44 constexpr DoubleDouble(long long value)
45 : hi(static_cast<double>(value)), lo(0.0)
46 {
47 }
48 constexpr DoubleDouble(long value) : hi(static_cast<double>(value)), lo(0.0)
49 {
50 }
51 DoubleDouble(long double value)
52 : hi(static_cast<double>(value)),
53 lo(static_cast<double>(value - static_cast<long double>(hi)))
54 {
55 }
56
57 explicit operator double() const
58 {
59 return hi;
60 }
61};
62
63// Spacing of a normalized double-double near 1 is 2^-105. Dekker
64// operations are faithful to two of those units, so the model unit
65// roundoff is 2^-104 and the model gap at 1 (machine epsilon) is 2^-103.
66inline constexpr int kDoubleDoubleUnitRoundoffExp = -104;
67inline constexpr int kDoubleDoubleEpsilonExp = -103;
68inline constexpr int kDoubleDoubleDigits = 104;
69
70inline double modelUnitRoundoff()
71{
72 return std::ldexp(1.0, kDoubleDoubleUnitRoundoffExp);
73}
74
75inline double modelEpsilon()
76{
77 return std::ldexp(1.0, kDoubleDoubleEpsilonExp);
78}
79
80inline void twoSum(double a, double b, double& sum, double& error)
81{
82 sum = a + b;
83 const double b_virtual = sum - a;
84 const double a_virtual = sum - b_virtual;
85 error = (a - a_virtual) + (b - b_virtual);
86}
87
88inline void twoProd(double a, double b, double& product, double& error)
89{
90 product = a * b;
91 error = std::fma(a, b, -product);
92}
93
94inline DoubleDouble renorm(double hi, double lo)
95{
96 double sum, error;
97 twoSum(hi, lo, sum, error);
98 return DoubleDouble(sum, error);
99}
100
102{
103 double sum, error;
104 twoSum(a.hi, b.hi, sum, error);
105 error += a.lo;
106 error += b.lo;
107 return renorm(sum, error);
108}
109
111{
112 return a + DoubleDouble(-b.hi, -b.lo);
113}
114
116{
117 return DoubleDouble(-a.hi, -a.lo);
118}
119
121{
122 double product, error;
123 twoProd(a.hi, b.hi, product, error);
124 error += a.hi * b.lo;
125 error += a.lo * b.hi;
126 error += a.lo * b.lo;
127 return renorm(product, error);
128}
129
131{
132 if (b.hi == 0.0) {
133 const double quotient = a.hi / b.hi;
134 return DoubleDouble(quotient, 0.0);
135 }
136 const double q1 = a.hi / b.hi;
137 DoubleDouble remainder = a - DoubleDouble(q1) * b;
138 const double q2 = remainder.hi / b.hi;
139 remainder = remainder - DoubleDouble(q2) * b;
140 const double q3 = remainder.hi / b.hi;
141 double sum, error;
142 twoSum(q1, q2, sum, error);
143 error += q3;
144 return renorm(sum, error);
145}
146
148{
149 a = a + b;
150 return a;
151}
152
154{
155 a = a - b;
156 return a;
157}
158
160{
161 a = a * b;
162 return a;
163}
164
166{
167 a = a / b;
168 return a;
169}
170
171// Comparisons follow IEEE binary64: every ordered comparison and == are false
172// when either operand is not a number, and != is true. A double-double is not
173// a number when either limb is a NaN or its low limb is infinite (an
174// overflowed product has hi = inf and lo = NaN). A clean infinity, hi = +-inf
175// with a finite low limb, orders by its high limb, so -inf < 0 < +inf.
177{
178 return std::isnan(a.hi) || !std::isfinite(a.lo);
179}
180
182{
183 if (unordered(a) || unordered(b)) return false;
184 return a.hi == b.hi && (!std::isfinite(a.hi) || a.lo == b.lo);
185}
186
188{
189 return !(a == b);
190}
191
193{
194 if (unordered(a) || unordered(b)) return false;
195 if (a.hi != b.hi) return a.hi < b.hi;
196 return std::isfinite(a.hi) && a.lo < b.lo;
197}
198
200{
201 return b < a;
202}
203
205{
206 return a < b || a == b;
207}
208
210{
211 return b < a || a == b;
212}
213
215{
216 if (a.hi < 0.0 || (a.hi == 0.0 && a.lo < 0.0))
217 return DoubleDouble(-a.hi, -a.lo);
218 return a;
219}
220
222{
223 if (!(a.hi > 0.0)) {
224 if (a.hi == 0.0 && a.lo == 0.0) return DoubleDouble(0.0);
225 return DoubleDouble(std::numeric_limits<double>::quiet_NaN(), 0.0);
226 }
227 const double root = std::sqrt(a.hi);
228 const DoubleDouble correction =
229 (a - DoubleDouble(root) * DoubleDouble(root)) /
230 DoubleDouble(2.0 * root);
231 return DoubleDouble(root) + correction;
232}
233
234inline bool isfinite(DoubleDouble a)
235{
236 return std::isfinite(a.hi) && std::isfinite(a.lo);
237}
238
239inline bool isnan(DoubleDouble a)
240{
241 return std::isnan(a.hi) || std::isnan(a.lo);
242}
243
244inline constexpr bool nativeLongDoubleIsExtended()
245{
246 return std::numeric_limits<long double>::digits > 53 &&
247 std::numeric_limits<long double>::radix == 2 &&
248 std::numeric_limits<long double>::is_iec559;
249}
250
251inline constexpr bool binary64SupportsDoubleDouble()
252{
253 return std::numeric_limits<double>::digits == 53 &&
254 std::numeric_limits<double>::radix == 2 &&
255 std::numeric_limits<double>::is_iec559;
256}
257
258#if defined(GPR_SIMULATE_NO_EXTENDED)
259inline constexpr bool certificationAvailable()
260{
261 return false;
262}
263using WorkingReal = long double;
264#elif defined(GPR_FORCE_DOUBLE_DOUBLE)
265inline constexpr bool certificationAvailable()
266{
268}
270#else
271inline constexpr bool certificationAvailable()
272{
274}
276 std::conditional_t<nativeLongDoubleIsExtended(), long double, DoubleDouble>;
277#endif
278
279template <typename T>
281
282// Where long double has the binary64 format (MSVC, macOS arm64, gcc/clang
283// -mlong-double-64) a step is the binary64 nextafter. Under -mlong-double-64
284// on x86-64 glibc, nextafterl still takes an x87 operand, so calling it
285// returns garbage; the binary64 call is the same function of the value on
286// every such platform.
287template <>
288struct WorkingPrecision<long double> {
289 static constexpr bool kBinary64 =
290 std::numeric_limits<long double>::digits ==
291 std::numeric_limits<double>::digits &&
292 std::numeric_limits<long double>::max_exponent ==
293 std::numeric_limits<double>::max_exponent;
294
295 static long double unitRoundoff()
296 {
297 return 0.5L * std::numeric_limits<long double>::epsilon();
298 }
299
300 static long double nextUp(long double value)
301 {
302 if constexpr (kBinary64)
303 return std::nextafter(static_cast<double>(value),
304 std::numeric_limits<double>::infinity());
305 return std::nextafter(value,
306 std::numeric_limits<long double>::infinity());
307 }
308
309 static long double nextDown(long double value)
310 {
311 if constexpr (kBinary64)
312 return std::nextafter(static_cast<double>(value),
313 -std::numeric_limits<double>::infinity());
314 return std::nextafter(value,
315 -std::numeric_limits<long double>::infinity());
316 }
317};
318
319template <>
322 {
324 }
325
326 // One model gap (2 u abs(x)) upward. That covers a faithful Dekker
327 // result, which sits at most one model unit roundoff below the truth,
328 // and leaves a second unit for the step itself.
330 {
331 if (!std::isfinite(value.hi)) return value;
332 const double magnitude = std::abs(value.hi);
333 double step = std::ldexp(magnitude, kDoubleDoubleEpsilonExp);
334 // At the bottom of binary64's normal range, a relative
335 // double-double step underflows. The next representable outward
336 // value is nevertheless one binary64 subnormal away, not DBL_MIN.
337 if (!(step > 0.0)) step = std::numeric_limits<double>::denorm_min();
338 return value + DoubleDouble(step);
339 }
340
342 {
343 if (!std::isfinite(value.hi)) return value;
344 const double magnitude = std::abs(value.hi);
345 double step = std::ldexp(magnitude, kDoubleDoubleEpsilonExp);
346 if (!(step > 0.0)) step = std::numeric_limits<double>::denorm_min();
347 return value - DoubleDouble(step);
348 }
349};
350
351// Operations that form the directed scale 1 + k u / (1 - k u) on top of
352// the expression being bounded.
353inline constexpr int kDirectedScaleOps = 4;
354
355template <typename Work>
356bool workingFinite(Work value)
357{
358 using std::isfinite;
359 return isfinite(value);
360}
361
362// The nearest binary64 not above / not below a working value. A NaN carries
363// no bound, and neither does a double-double whose low limb is not finite (an
364// overflowed product has hi = inf and lo = NaN): comparing such a value is
365// false both ways, which used to return the high limb as if it were a bound.
366// They throw std::range_error instead. A clean infinity rounds to itself, +inf
367// being a valid upper bound and -inf a valid lower one.
368inline bool lowLimbFinite(double)
369{
370 return true;
371}
372
373inline bool lowLimbFinite(long double)
374{
375 return true;
376}
377
378inline bool lowLimbFinite(const DoubleDouble& value)
379{
380 return std::isfinite(value.lo);
381}
382
383template <typename Work>
384double roundedToDouble(Work value)
385{
386 const double result = static_cast<double>(value);
387 if (std::isnan(result) || !lowLimbFinite(value))
388 throw std::range_error(
389 "a working-precision value is not finite and has no binary64 "
390 "bound");
391 return result;
392}
393
394template <typename Work>
395double roundDownToDouble(Work value)
396{
397 double result = roundedToDouble(value);
398 if (static_cast<Work>(result) > value)
399 result =
400 std::nextafter(result, -std::numeric_limits<double>::infinity());
401 return result;
402}
403
404template <typename Work>
405double roundUpToDouble(Work value)
406{
407 double result = roundedToDouble(value);
408 if (static_cast<Work>(result) < value)
409 result =
410 std::nextafter(result, std::numeric_limits<double>::infinity());
411 return result;
412}
413
414// Binary64 operations rounded toward +inf or -inf without changing the
415// rounding mode. Each takes the round-to-nearest result and the exact
416// rounding error of that operation (TwoSum for a sum, fma for a product, the
417// fma remainder for a quotient), and steps one binary64 in the direction the
418// error points when it is nonzero. The result is the correctly directed
419// rounding of the exact value, so it is a rigorous bound and does not depend
420// on the thread, the rank count or the rounding mode of the caller. A product
421// or quotient below kUnderflowGuard is the one exception: it steps outward
422// unconditionally, so it is a bound at most one binary64 looser. No bound
423// crosses zero: the exact product or quotient has the sign of the operands,
424// so the lower bound of a positive one is at least +0 and the upper bound of
425// a negative one at most -0. A finite exact value whose rounding overflowed
426// is bounded toward zero by the largest finite binary64, not by the
427// infinity. A NaN operand, 0 * inf and inf - inf give NaN. Needs IEEE
428// binary64 and no -ffast-math, as the rest of this header does.
429namespace directed {
430
431inline double stepUp(double x)
432{
433 return std::nextafter(x, std::numeric_limits<double>::infinity());
434}
435
436inline double stepDown(double x)
437{
438 return std::nextafter(x, -std::numeric_limits<double>::infinity());
439}
440
441// Below this magnitude an fma error term can itself underflow, so a product
442// or quotient that small is rounded outward unconditionally.
443inline constexpr double kUnderflowGuard = 0x1p-960;
444
445// The rounded result of two finite operands is infinite: the exact value is
446// finite and beyond the largest binary64.
447inline bool finiteOverflow(double a, double b, double rounded)
448{
449 return std::isinf(rounded) && std::isfinite(a) && std::isfinite(b);
450}
451
452inline double addUp(double a, double b)
453{
454 const double s = a + b;
455 if (!std::isfinite(s))
456 return finiteOverflow(a, b, s) && s < 0.0
457 ? std::numeric_limits<double>::lowest()
458 : s;
459 // Fast2Sum needs its first input to have the greater magnitude. Besides
460 // being shorter than TwoSum, this avoids s - a overflowing when b is the
461 // larger operand and the finite sum lies near DBL_MAX.
462 if (std::fabs(b) > std::fabs(a)) std::swap(a, b);
463 const double err = b - (s - a);
464 return err > 0.0 ? stepUp(s) : s;
465}
466
467inline double addDown(double a, double b)
468{
469 const double s = a + b;
470 if (!std::isfinite(s))
471 return finiteOverflow(a, b, s) && s > 0.0
472 ? std::numeric_limits<double>::max()
473 : s;
474 if (std::fabs(b) > std::fabs(a)) std::swap(a, b);
475 const double err = b - (s - a);
476 return err < 0.0 ? stepDown(s) : s;
477}
478
479inline double subUp(double a, double b)
480{
481 return addUp(a, -b);
482}
483
484inline double subDown(double a, double b)
485{
486 return addDown(a, -b);
487}
488
489inline double mulUp(double a, double b)
490{
491 const double p = a * b;
492 if (!std::isfinite(p))
493 return finiteOverflow(a, b, p) && p < 0.0
494 ? std::numeric_limits<double>::lowest()
495 : p;
496 if (a == 0.0 || b == 0.0) return 0.0;
497 if (std::fabs(p) < kUnderflowGuard)
498 return p == 0.0 && std::signbit(a) != std::signbit(b) ? -0.0
499 : stepUp(p);
500 return std::fma(a, b, -p) > 0.0 ? stepUp(p) : p;
501}
502
503inline double mulDown(double a, double b)
504{
505 const double p = a * b;
506 if (!std::isfinite(p))
507 return finiteOverflow(a, b, p) && p > 0.0
508 ? std::numeric_limits<double>::max()
509 : p;
510 if (a == 0.0 || b == 0.0) return 0.0;
511 if (std::fabs(p) < kUnderflowGuard)
512 return p == 0.0 && std::signbit(a) == std::signbit(b) ? 0.0
513 : stepDown(p);
514 return std::fma(a, b, -p) < 0.0 ? stepDown(p) : p;
515}
516
517// Quotient rounded up. The divisor is nonzero. The fma remainder a - q b is
518// exact when abs(a) >= kUnderflowGuard; below it the remainder can underflow to
519// zero and hide a quotient that rounded down, so a small dividend is scaled
520// with its divisor by 2^200 first, which is exact and keeps the quotient.
521inline double divUp(double a, double b)
522{
523 if (a != 0.0 && std::fabs(a) < kUnderflowGuard && std::fabs(b) < 0x1p+800)
524 return divUp(a * 0x1p+200, b * 0x1p+200);
525 const double q = a / b;
526 if (!std::isfinite(q))
527 return finiteOverflow(a, b, q) && b != 0.0 && q < 0.0
528 ? std::numeric_limits<double>::lowest()
529 : q;
530 if (a == 0.0 || std::isinf(b)) return q;
531 if (std::fabs(q) < kUnderflowGuard)
532 return q == 0.0 && std::signbit(a) != std::signbit(b) ? -0.0
533 : stepUp(q);
534 const double remainder = std::fma(-q, b, a);
535 const bool exact_above = (remainder > 0.0) == (b > 0.0) && remainder != 0.0;
536 return exact_above ? stepUp(q) : q;
537}
538
539} // namespace directed
540
541// Upper bound on k u / (1 - k u) with k = expression_ops plus the operations
542// that form the scale, computed in the working type and returned as a
543// working number that is not below the exact value. Infinite when k u >= 1.
544template <typename Work>
545Work directedGammaUpper(long long expression_ops)
546{
547 using Prec = WorkingPrecision<Work>;
548 const long long total = expression_ops + kDirectedScaleOps;
549 if (total <= 0 || total > (1LL << 53))
550 return Work(std::numeric_limits<double>::infinity());
551 const Work k(static_cast<double>(total));
552 const Work u = Prec::unitRoundoff();
553 if (!(k * u < Work(1)))
554 return Work(std::numeric_limits<double>::infinity());
555 return (k * u) / (Work(1) - k * u);
556}
557
558// The next working number above value (1 + gamma_k). An exact zero stays
559// zero: the value is a sum of rounded terms and carries no relative error
560// when it is exactly zero. A residual that cancels in floating point is not
561// such a value; see frobeniusResidualUpperBound.
562template <typename Work>
563Work directedUpperBound(Work value, long long expression_ops)
564{
565 using Prec = WorkingPrecision<Work>;
566 if (!workingFinite(value))
567 return Work(std::numeric_limits<double>::infinity());
568 if (!(value > Work(0))) return Work(0);
569 return Prec::nextUp(value *
570 (Work(1) + directedGammaUpper<Work>(expression_ops)));
571}
572
573namespace scaled {
574
575// Exponent e with 2^(e-1) <= abs(leading limb) < 2^e, for a finite nonzero
576// value.
577inline int leadingExponent(long double value)
578{
579 int exponent = 0;
580 std::frexp(value, &exponent);
581 return exponent;
582}
583
584inline int leadingExponent(const DoubleDouble& value)
585{
586 int exponent = 0;
587 std::frexp(value.hi != 0.0 ? value.hi : value.lo, &exponent);
588 return exponent;
589}
590
591// value * 2^shift, limb by limb. exact is cleared when a limb was rounded,
592// which happens only when it lands below the normal range; each limb is then
593// off by at most half its smallest subnormal step.
594inline long double scaleByPowerOfTwo(long double value, int shift, bool& exact)
595{
596 const long double scaled = std::ldexp(value, shift);
597 if (std::ldexp(scaled, -shift) != value) exact = false;
598 return scaled;
599}
600
601inline DoubleDouble scaleByPowerOfTwo(const DoubleDouble& value, int shift,
602 bool& exact)
603{
604 const double hi = std::ldexp(value.hi, shift);
605 const double lo = std::ldexp(value.lo, shift);
606 if (std::ldexp(hi, -shift) != value.hi ||
607 std::ldexp(lo, -shift) != value.lo)
608 exact = false;
609 return DoubleDouble(hi, lo);
610}
611
612// The smallest subnormal step of one limb.
613template <typename Work>
615{
616 if constexpr (std::is_same_v<Work, DoubleDouble>)
617 return Work(std::numeric_limits<double>::denorm_min());
618 else
619 return std::numeric_limits<Work>::denorm_min();
620}
621
622// Entries with a magnitude in [2^kSafeLow, 2^kSafeHigh] square to at least
623// 2^-900 and sum to below 2^953 for any order below 2^53.
624inline constexpr int kSafeLow = -450;
625inline constexpr int kSafeHigh = 450;
626// Scaled entries below 2^kDroppedExp are not squared.
627inline constexpr int kDroppedExp = -460;
628
629// ||X||_F <= mantissa 2^exponent, where mantissa is what the working type
630// computed for a norm whose rounding is covered by `ops` operations: an
631// upper bound follows from directedUpperBound(mantissa, ops) 2^exponent.
632template <typename Work>
634 Work mantissa = Work(0);
635 int exponent = 0;
636 long long ops = 0;
637};
638
639// When every nonzero entry lies in [2^kSafeLow, 2^kSafeHigh] this is
640// X.norm() at exponent 0 with the depth entries + 2, as before. No square or
641// partial sum then leaves the normal range, and a low-limb correction term of
642// a double-double square that underflows errs by at most 2^-1075 <= 2^-175
643// abs(x)^2, inside the u^2 abs(x)^2 that the faithful product model already
644// allows for that term.
645//
646// Otherwise X is scaled by 2^-e, e the leading exponent of its largest entry,
647// in the manner of LAPACK dnrm2: the largest scaled entry lies in [1/2, 1).
648// Scaling up is exact. Scaling down (e > 0) can round a limb that falls below
649// the normal range, by at most 2^-1075 per limb, so a scaled entry y is off
650// by at most 2^-1074 and y_exact^2 <= y^2 + 2^-1072. Scaled entries below
651// 2^kDroppedExp are not squared: each has y_exact^2 < 2^-919. The squares
652// that are formed are at least 2^-920 and fall under the argument above. So
653// with N entries
654// sum y_exact^2 <= sum_{y >= 2^kDroppedExp} y^2 + N 2^-917,
655// and the second term is added to the computed sum explicitly. That sum is at
656// least 1/4, so the extra addition stays in the normal range and costs one
657// operation of depth, entries + 3 in all. A nonzero matrix has a positive
658// mantissa however small its entries are.
659template <typename Work, typename Plain>
660ScaledNorm<Work> scaledFrobeniusNorm(const Plain& matrix, long long norm_ops)
661{
662 using std::abs;
663 using std::sqrt;
664 bool finite = true;
665 bool nonzero = false;
666 bool safe = true;
667 int top = 0;
668 for (Eigen::Index j = 0; j < matrix.cols(); ++j) {
669 for (Eigen::Index i = 0; i < matrix.rows(); ++i) {
670 const Work value = matrix(i, j);
671 if (!workingFinite(value)) {
672 finite = false;
673 continue;
674 }
675 if (value == Work(0)) continue;
676 const int exponent = leadingExponent(value);
677 if (exponent - 1 < kSafeLow || exponent > kSafeHigh) safe = false;
678 top = nonzero ? std::max(top, exponent) : exponent;
679 nonzero = true;
680 }
681 }
682 if (!finite || !nonzero || safe)
683 return ScaledNorm<Work>{Work(matrix.norm()), 0, norm_ops};
684
685 const Work dropped_below(std::ldexp(1.0, kDroppedExp));
686 Work sum(0);
687 for (Eigen::Index j = 0; j < matrix.cols(); ++j) {
688 for (Eigen::Index i = 0; i < matrix.rows(); ++i) {
689 const Work value = matrix(i, j);
690 if (value == Work(0)) continue;
691 bool exact = true;
692 const Work y = abs(scaleByPowerOfTwo(value, -top, exact));
693 if (y < dropped_below) continue;
694 sum += y * y;
695 }
696 }
697 sum += Work(std::ldexp(static_cast<double>(matrix.size()), -917));
698 return ScaledNorm<Work>{sqrt(sum), top, norm_ops + 1};
699}
700
701} // namespace scaled
702
703// A bound on the Frobenius norm of the exact residual R, given the residual
704// M the working type computed and the entrywise sum of absolute values A of
705// the terms that formed each entry of M. Each entry of M differs from the
706// exact entry by at most gamma_m times that sum, with m the operation depth
707// of the entry in any summation order, so
708// ||R||_F <= ||M||_F + gamma_m ||A||_F.
709// The second term does not vanish when M cancels to zero, which a bound that
710// scales ||M|| alone cannot repair. Both norms carry their own sum-of-squares
711// depth, entries + 2. The entries of A are themselves sums of m rounded
712// nonnegative terms, so the computed A can lie below the exact one by gamma_m
713// of it: the second term also carries the m operations of its entries.
714//
715// Each norm is formed by scaled::scaledFrobeniusNorm, so a residual whose
716// squares underflow the working type (double-double has the binary64 range)
717// still bounds to a positive value. The head and tail are bounded at their
718// own scales, brought to the larger exponent K and summed there. Bringing one
719// down can round each limb below the normal range by at most 2^-1075, so when
720// that happened 2^-1072 is added before the sum is bounded, one more
721// operation. The sum times 2^K is exact unless it lands below the normal
722// range; then each limb is off by at most half a subnormal step, two steps
723// are added and the result is pushed one working step up, which covers the
724// rounding of that addition. When both norms are formed at exponent 0 (every
725// entry in the safe range) this is the unscaled bound bit for bit.
726template <typename Work, typename ComputedMatrix, typename AbsMatrix>
727Work frobeniusResidualUpperBound(const ComputedMatrix& computed,
728 const AbsMatrix& abs_terms,
729 long long entry_ops)
730{
731 using Prec = WorkingPrecision<Work>;
732 const long long norm_ops = static_cast<long long>(computed.size()) + 2;
733 const Work inf(std::numeric_limits<double>::infinity());
734 const Work u = Prec::unitRoundoff();
735 const Work m(static_cast<double>(entry_ops));
736 if (entry_ops <= 0 || !(m * u < Work(1))) return inf;
737 // Magnitudes, not computed.eval(): Eigen assigns X - A B as X, then
738 // -= A B, which rounds differently from the product the norm of the
739 // expression evaluates on its own.
740 const auto computed_magnitude = computed.cwiseAbs().eval();
741 const auto abs_magnitude = abs_terms.cwiseAbs().eval();
742 const scaled::ScaledNorm<Work> computed_norm =
743 scaled::scaledFrobeniusNorm<Work>(computed_magnitude, norm_ops);
744 const scaled::ScaledNorm<Work> abs_norm =
745 scaled::scaledFrobeniusNorm<Work>(abs_magnitude, norm_ops);
746 const Work gamma_entry = (m * u) / (Work(1) - m * u);
747 const Work head =
748 directedUpperBound<Work>(computed_norm.mantissa, computed_norm.ops);
749 const Work tail = directedUpperBound<Work>(
750 gamma_entry * abs_norm.mantissa, 3 + abs_norm.ops + entry_ops + 1);
751 if (!workingFinite(head) || !workingFinite(tail)) return inf;
752
753 const bool has_head = head > Work(0);
754 const bool has_tail = tail > Work(0);
755 int top = 0;
756 if (has_head && has_tail)
757 top = std::max(computed_norm.exponent, abs_norm.exponent);
758 else if (has_head)
759 top = computed_norm.exponent;
760 else if (has_tail)
761 top = abs_norm.exponent;
762 bool aligned_exact = true;
763 const Work head_at_top =
764 has_head ? scaled::scaleByPowerOfTwo(head, computed_norm.exponent - top,
765 aligned_exact)
766 : Work(0);
767 const Work tail_at_top =
768 has_tail ? scaled::scaleByPowerOfTwo(tail, abs_norm.exponent - top,
769 aligned_exact)
770 : Work(0);
771 Work sum = head_at_top + tail_at_top;
772 long long sum_ops = 1;
773 if (!aligned_exact) {
774 sum += Work(std::ldexp(1.0, -1072));
775 sum_ops = 2;
776 }
777 const Work bound_at_top = directedUpperBound<Work>(sum, sum_ops);
778 if (top == 0) return bound_at_top;
779 bool unscaled_exact = true;
780 const Work bound =
781 scaled::scaleByPowerOfTwo(bound_at_top, top, unscaled_exact);
782 if (!workingFinite(bound)) return inf;
783 if (unscaled_exact) return bound;
784 return Prec::nextUp(bound + Work(2) * scaled::limbDenormMin<Work>());
785}
786
787// Below this magnitude a rounded product or square root of the working type
788// is no longer within u of the exact result. Double-double keeps 2^-104 only
789// while its low limb is a normal binary64, about 2^-53 below the high limb.
790template <typename Work>
792{
793 if constexpr (std::is_same_v<Work, DoubleDouble>)
794 return Work(std::ldexp(1.0, -968));
795 else
796 return std::numeric_limits<Work>::min();
797}
798
799// The absolute error a product of the working type can add below that floor.
800// A double-double product rounds at most four binary64 results that underflow
801// (the error-free product and three cross terms), each by at most 2^-1075; a
802// square root adds the error of a residual of that size divided by twice the
803// root, which is at most this over the root. One rounding of a native type
804// adds half its smallest subnormal step. Both carry a factor of 16 or more.
805template <typename Work>
807{
808 if constexpr (std::is_same_v<Work, DoubleDouble>)
809 return Work(std::ldexp(1.0, -1068));
810 else
811 return Work(64) * std::numeric_limits<Work>::denorm_min();
812}
813
814template <typename Work>
816 Eigen::Matrix<Work, Eigen::Dynamic, Eigen::Dynamic> B;
817 // >= ||B B^T - B* B*^T||_F, B* the exact products.
818 Work gram_error = Work(0);
819 // An upper bound on ||B||_F when some entry left the relative model or
820 // its squares leave the normal range, else B.norm() as computed.
821 Work norm = Work(0);
822 bool underflow = false;
823};
824
825// B_ij = d_i v_ij sqrt(lambda_j) for the rank columns of the largest
826// eigenvalues, in descending order, formed in the working type as
827// (d_i v_ij) sqrt(lambda_j): three rounded operations per entry. While every
828// result stays above formedEntryRelativeFloor each is within u of the exact
829// one, so Bh_ij = B*_ij (1 + theta_ij) with abs(theta_ij) <= t = gamma_3 and
830// ||Bh Bh^T - B* B*^T||_F <= t (2 - t)/(1 - t)^2 ||Bh||_F^2
831// <= bb ||Bh||_F^2, bb = 2 t/(1 - t)^2,
832// the bound before, bit for bit, when no entry is near underflow.
833//
834// Below the floor an operation also errs absolutely, by eta (see
835// formedEntryAbsoluteError) for a product and by eta / sqrt(lambda_j) for the
836// root. With p = fl(d v) and s = fl(sqrt(lambda)) that gives
837// Bh = B' + E, B' = B* (1 + theta),
838// abs(E_ij) <= 2 eta abs(s_j) [p small] +
839// 2 (abs(p_ij) + eta) eta / s_j [lambda_j small] +
840// eta [Bh_ij small] = h_ij,
841// "small" meaning below twice the floor, so any exact result under the floor
842// is caught. With H = sum h_ij >= ||E||_F, ||B'||_F <= ||Bh||_F + H and
843// Bh Bh^T - B' B'^T = E B'^T + B' E^T + E E^T,
844// so the departure is at most bb (N + H)^2 + H (2 N + 3 H), N an upper bound
845// on ||Bh||_F taken at a scale where its squares do not underflow. Each
846// product there may itself land below the normal range; four subnormal steps
847// cover their rounding.
848template <typename Work, typename DiagScale, typename Vectors, typename Values>
849FormedFactor<Work> formScaledFactor(const DiagScale& diag_scale,
850 const Vectors& evecs_asc,
851 const Values& evals_asc, Eigen::Index rank,
852 int entry_ops)
853{
854 using std::abs;
855 using std::sqrt;
856 const Eigen::Index n = evecs_asc.rows();
858 out.B.resize(n, rank);
859 const Work floor2 = Work(2) * formedEntryRelativeFloor<Work>();
860 const Work eta = formedEntryAbsoluteError<Work>();
861 Work allowance(0);
862 bool scaled_norm = false;
863 for (Eigen::Index j = 0; j < rank; ++j) {
864 const Eigen::Index src = n - 1 - j;
865 const Work s = sqrt(evals_asc(src));
866 const bool root_small = abs(evals_asc(src)) < floor2;
867 for (Eigen::Index i = 0; i < n; ++i) {
868 const Work product = diag_scale(i) * evecs_asc(i, src);
869 const Work entry = product * s;
870 out.B(i, j) = entry;
871 if (entry != Work(0)) {
872 const int exponent = scaled::leadingExponent(entry);
873 if (exponent - 1 < scaled::kSafeLow ||
874 exponent > scaled::kSafeHigh)
875 scaled_norm = true;
876 }
877 const bool exact_zero =
878 diag_scale(i) == Work(0) || evecs_asc(i, src) == Work(0);
879 if (exact_zero) continue;
880 const bool product_small = abs(product) < floor2;
881 const bool entry_small = abs(entry) < floor2;
882 if (!(product_small || root_small || entry_small)) continue;
883 out.underflow = true;
884 if (product_small) allowance += Work(2) * abs(s);
885 if (root_small) allowance += Work(2) * (abs(product) + floor2) / s;
886 if (entry_small) allowance += Work(1);
887 }
888 }
889
890 const Work gamma = directedGammaUpper<Work>(entry_ops);
891 if (!(gamma < Work(1))) {
892 out.gram_error = Work(std::numeric_limits<double>::infinity());
893 out.norm = out.gram_error;
894 return out;
895 }
896 const Work gap = Work(1) - gamma;
897 const Work bb = directedUpperBound<Work>(Work(2) * gamma / (gap * gap), 6);
898 if (!out.underflow && !scaled_norm) {
899 out.gram_error = bb * out.B.squaredNorm();
900 out.norm = out.B.norm();
901 return out;
902 }
903
904 const long long entries = static_cast<long long>(out.B.size());
905 const Work dmin = scaled::limbDenormMin<Work>();
906 const Work norm = frobeniusResidualUpperBound<Work>(
907 out.B, decltype(out.B)::Zero(n, rank), 1);
908 const Work H =
910 eta * directedUpperBound<Work>(allowance, entries + 4), 1) +
911 Work(2) * dmin;
912 const Work total = norm + H;
913 const Work relative = directedUpperBound<Work>(bb * total * total, 3);
914 const Work absolute =
915 directedUpperBound<Work>(H * (Work(2) * norm + Work(3) * H), 4);
916 out.gram_error =
917 directedUpperBound<Work>(relative + absolute + Work(4) * dmin, 2);
918 out.norm = norm;
919 out.underflow = true;
920 return out;
921}
922
923// Enclosure [lower, upper] of y_scale^2 * calibration in the working type.
924// Each rounded product is pushed one working step outward, which covers the
925// product's rounding error in both working types. `valid` is false unless
926// the enclosure is positive and finite.
927template <typename Work>
929 Work lower = Work(0);
930 Work upper = Work(0);
931 bool valid = false;
932};
933
934template <typename Work>
936 double calibration)
937{
938 using Prec = WorkingPrecision<Work>;
940 if (!std::isfinite(y_scale) || !(y_scale > 0.0) ||
941 !std::isfinite(calibration) || !(calibration > 0.0))
942 return out;
943 const Work y(y_scale);
944 const Work square = y * y;
945 const Work c(calibration);
946 out.lower = Prec::nextDown(Prec::nextDown(square) * c);
947 out.upper = Prec::nextUp(Prec::nextUp(square) * c);
948 out.valid = out.lower > Work(0) && workingFinite(out.upper);
949 return out;
950}
951
952// value * scale, rounded outward to binary64. An exact zero stays zero. A
953// product beyond binary64 is still bounded: the upper bound is +inf (the
954// lowest finite for a negative value, whose upper side overflows toward
955// -inf) and the lower bound the largest finite value (-inf for a negative
956// one), instead of the NaN a double-double overflow leaves in its limbs. A
957// NaN value has no bound and throws std::range_error; an infinite value
958// scales to itself. The exact product has the sign of value, so the bound on
959// the side of zero never crosses it: a product that underflows in the working
960// type steps to -DBL_MIN below a positive value, and its lower bound is 0
961// instead (and its upper bound -0 for a negative value).
962template <typename Work>
963double scaledLowerBound(double value, const VarianceScaleEnclosure<Work>& scale)
964{
965 if (std::isnan(value))
966 throw std::range_error("a NaN has no scaled binary64 bound");
967 if (value == 0.0 || std::isinf(value)) return value == 0.0 ? 0.0 : value;
968 using Prec = WorkingPrecision<Work>;
969 const Work factor = value > 0.0 ? scale.lower : scale.upper;
970 const Work product = Work(value) * factor;
971 if (!workingFinite(product))
972 return value > 0.0 ? std::numeric_limits<double>::max()
973 : -std::numeric_limits<double>::infinity();
974 const Work below = Prec::nextDown(product);
975 if (!workingFinite(below))
976 return value > 0.0 ? std::numeric_limits<double>::max()
977 : -std::numeric_limits<double>::infinity();
978 const double bound = roundDownToDouble<Work>(below);
979 return value > 0.0 && std::signbit(bound) ? 0.0 : bound;
980}
981
982template <typename Work>
983double scaledUpperBound(double value, const VarianceScaleEnclosure<Work>& scale)
984{
985 if (std::isnan(value))
986 throw std::range_error("a NaN has no scaled binary64 bound");
987 if (value == 0.0 || std::isinf(value)) return value == 0.0 ? 0.0 : value;
988 using Prec = WorkingPrecision<Work>;
989 const Work factor = value > 0.0 ? scale.upper : scale.lower;
990 const Work product = Work(value) * factor;
991 if (!workingFinite(product))
992 return value > 0.0 ? std::numeric_limits<double>::infinity()
993 : std::numeric_limits<double>::lowest();
994 const Work above = Prec::nextUp(product);
995 if (!workingFinite(above))
996 return value > 0.0 ? std::numeric_limits<double>::infinity()
997 : std::numeric_limits<double>::lowest();
998 const double bound = roundUpToDouble<Work>(above);
999 return value < 0.0 && !std::signbit(bound) ? -0.0 : bound;
1000}
1001
1002// The exact product a * b of two binary64 values, as the nearest binary64
1003// not above and not below it (directed::mulDown and mulUp). The bounds are
1004// exact where the fma error is representable; near the subnormal range both
1005// step outward without crossing zero. A NaN operand and 0 * inf have no
1006// product, and both bounds are NaN.
1007inline void outwardProduct(double a, double b, double& down, double& up)
1008{
1009 down = directed::mulDown(a, b);
1010 up = directed::mulUp(a, b);
1011}
1012
1013} // namespace extended
1014} // namespace gpr
1015
1016namespace std {
1017template <>
1018struct numeric_limits<gpr::extended::DoubleDouble> {
1020 static constexpr bool is_specialized = true;
1021 static constexpr bool is_signed = true;
1022 static constexpr bool is_integer = false;
1023 static constexpr bool is_exact = false;
1024 static constexpr bool is_iec559 = false;
1025 static constexpr bool is_bounded = true;
1026 static constexpr bool is_modulo = false;
1028 static constexpr int digits10 = 31;
1029 static constexpr int max_digits10 = 36;
1030 static constexpr int radix = 2;
1031 static constexpr int min_exponent = numeric_limits<double>::min_exponent;
1032 static constexpr int max_exponent = numeric_limits<double>::max_exponent;
1033 static constexpr int min_exponent10 =
1034 numeric_limits<double>::min_exponent10;
1035 static constexpr int max_exponent10 =
1036 numeric_limits<double>::max_exponent10;
1037 static constexpr bool has_infinity = true;
1038 static constexpr bool has_quiet_NaN = true;
1039 static constexpr bool has_signaling_NaN = false;
1040 static constexpr float_denorm_style has_denorm = denorm_present;
1041 static constexpr bool has_denorm_loss = false;
1042 static constexpr bool traps = false;
1043 static constexpr bool tinyness_before = false;
1044 static constexpr float_round_style round_style = round_to_nearest;
1045
1047 {
1049 }
1051 {
1052 return value_type(0.5);
1053 }
1055 {
1056 return value_type(numeric_limits<double>::infinity(), 0.0);
1057 }
1059 {
1060 return value_type(numeric_limits<double>::quiet_NaN(), 0.0);
1061 }
1063 {
1064 return quiet_NaN();
1065 }
1067 {
1068 return value_type(numeric_limits<double>::denorm_min(), 0.0);
1069 }
1071 {
1072 return value_type(numeric_limits<double>::min(), 0.0);
1073 }
1075 {
1076 return value_type(numeric_limits<double>::max(), 0.0);
1077 }
1079 {
1080 return -max();
1081 }
1082};
1083} // namespace std
1084
1085namespace Eigen {
1086template <>
1087struct NumTraits<gpr::extended::DoubleDouble>
1088 : GenericNumTraits<gpr::extended::DoubleDouble> {
1093
1094 enum {
1102 };
1103
1104 static inline Real epsilon()
1105 {
1107 }
1108
1109 // Eigen's fuzzy comparisons. 2^10 model gaps, not a certificate tolerance.
1110 static inline Real dummy_precision()
1111 {
1112 return Real(
1113 std::ldexp(1.0, gpr::extended::kDoubleDoubleEpsilonExp + 10));
1114 }
1115
1116 static inline int digits10()
1117 {
1118 return 31;
1119 }
1120
1121 static inline int digits()
1122 {
1124 }
1125
1126 static inline Real highest()
1127 {
1128 return Real(std::numeric_limits<double>::max(), 0.0);
1129 }
1130
1131 static inline Real lowest()
1132 {
1133 return -highest();
1134 }
1135};
1136} // namespace Eigen
1137
1138#endif // GPR_ML_GP_EXTENDED_REAL_H_
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
double subUp(double a, double b)
double addUp(double a, double b)
bool finiteOverflow(double a, double b, double rounded)
constexpr double kUnderflowGuard
double stepUp(double x)
double divUp(double a, double b)
double subDown(double a, double b)
double mulUp(double a, double b)
double mulDown(double a, double b)
double stepDown(double x)
double addDown(double a, double b)
constexpr int kDroppedExp
ScaledNorm< Work > scaledFrobeniusNorm(const Plain &matrix, long long norm_ops)
constexpr int kSafeLow
constexpr int kSafeHigh
long double scaleByPowerOfTwo(long double value, int shift, bool &exact)
int leadingExponent(long double value)
bool isfinite(DoubleDouble a)
bool lowLimbFinite(double)
constexpr int kDoubleDoubleDigits
DoubleDouble operator*(DoubleDouble a, DoubleDouble b)
DoubleDouble renorm(double hi, double lo)
Work frobeniusResidualUpperBound(const ComputedMatrix &computed, const AbsMatrix &abs_terms, long long entry_ops)
DoubleDouble operator-(DoubleDouble a, DoubleDouble b)
Work formedEntryAbsoluteError()
bool unordered(DoubleDouble a)
void twoProd(double a, double b, double &product, double &error)
double modelUnitRoundoff()
constexpr bool nativeLongDoubleIsExtended()
Work directedGammaUpper(long long expression_ops)
bool operator!=(DoubleDouble a, DoubleDouble b)
std::conditional_t< nativeLongDoubleIsExtended(), long double, DoubleDouble > WorkingReal
void twoSum(double a, double b, double &sum, double &error)
constexpr int kDoubleDoubleUnitRoundoffExp
void outwardProduct(double a, double b, double &down, double &up)
double roundDownToDouble(Work value)
constexpr int kDoubleDoubleEpsilonExp
FormedFactor< Work > formScaledFactor(const DiagScale &diag_scale, const Vectors &evecs_asc, const Values &evals_asc, Eigen::Index rank, int entry_ops)
DoubleDouble sqrt(DoubleDouble a)
bool isnan(DoubleDouble a)
DoubleDouble operator+(DoubleDouble a, DoubleDouble b)
DoubleDouble & operator-=(DoubleDouble &a, DoubleDouble b)
bool operator<=(DoubleDouble a, DoubleDouble b)
DoubleDouble abs(DoubleDouble a)
DoubleDouble & operator/=(DoubleDouble &a, DoubleDouble b)
bool operator>=(DoubleDouble a, DoubleDouble b)
VarianceScaleEnclosure< Work > varianceScaleEnclosure(double y_scale, double calibration)
DoubleDouble operator/(DoubleDouble a, DoubleDouble b)
double modelEpsilon()
double scaledUpperBound(double value, const VarianceScaleEnclosure< Work > &scale)
constexpr bool certificationAvailable()
Work directedUpperBound(Work value, long long expression_ops)
bool operator==(DoubleDouble a, DoubleDouble b)
bool workingFinite(Work value)
bool operator<(DoubleDouble a, DoubleDouble b)
constexpr bool binary64SupportsDoubleDouble()
double roundedToDouble(Work value)
double roundUpToDouble(Work value)
double scaledLowerBound(double value, const VarianceScaleEnclosure< Work > &scale)
DoubleDouble & operator+=(DoubleDouble &a, DoubleDouble b)
Work formedEntryRelativeFloor()
constexpr int kDirectedScaleOps
bool operator>(DoubleDouble a, DoubleDouble b)
DoubleDouble & operator*=(DoubleDouble &a, DoubleDouble b)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
STL namespace.
constexpr DoubleDouble(double high, double low)
constexpr DoubleDouble(long value)
constexpr DoubleDouble(long long value)
constexpr DoubleDouble(int value)
constexpr DoubleDouble()=default
DoubleDouble(long double value)
constexpr DoubleDouble(double value)
Eigen::Matrix< Work, Eigen::Dynamic, Eigen::Dynamic > B
static DoubleDouble nextUp(DoubleDouble value)
static DoubleDouble nextDown(DoubleDouble value)
static long double nextUp(long double value)
static long double nextDown(long double value)
static constexpr float_round_style round_style
static constexpr float_denorm_style has_denorm