Loading...
Searching...
No Matches
ExactSum.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
22
23#ifndef GPR_LINALG_EXACT_SUM_H_
24#define GPR_LINALG_EXACT_SUM_H_
25
26#include <cmath>
27#include <cstdint>
28#include <cstring>
29#include <limits>
30
31namespace gpr {
32namespace linalg {
33
34class ExactSum {
35public:
41 static constexpr int kLimbs = 169;
43 static constexpr int kOrigin = 2148;
45 static constexpr int kDoubleShift = 1074;
46
47 ExactSum() noexcept
48 {
49 std::memset(limb_, 0, sizeof(limb_));
50 }
51
54 void add(double x) noexcept
55 {
56 const Factor factor = factorOf(x);
57 if (factor.nonfinite) {
58 nonfinite_ += x;
59 return;
60 }
61 addMagnitude(factor.significand, factor.lsb + kDoubleShift,
62 factor.negative);
63 }
64
70 void addProduct(double a, double b) noexcept
71 {
72 const Factor left = factorOf(a);
73 const Factor right = factorOf(b);
74 if (left.nonfinite || right.nonfinite) {
75 nonfinite_ += a * b;
76 return;
77 }
78 addMagnitude(left.significand * right.significand, left.lsb + right.lsb,
79 left.negative != right.negative);
80 }
81
86 void addTripleProduct(double a, double b, double c) noexcept
87 {
88 const Factor left = factorOf(a);
89 const Factor middle = factorOf(b);
90 const Factor right = factorOf(c);
91 if (left.nonfinite || middle.nonfinite || right.nonfinite) {
92 nonfinite_ += a * b * c;
93 return;
94 }
95 const ExactWide product = left.significand * middle.significand;
96 ExactWide low_magnitude =
97 (product & static_cast<ExactWide>(~std::uint64_t{0})) *
98 right.significand;
99 ExactWide high_magnitude = (product >> 64) * right.significand;
100 int low_bit = left.lsb + middle.lsb + right.lsb - kDoubleShift;
101 int high_bit = low_bit + 64;
102 const bool negative =
103 (left.negative != middle.negative) != right.negative;
104 // Bits below the origin are not stored. A nonzero residue stays as a
105 // sticky bit at the origin so a later rounding still sees it. The
106 // limb window holds every finite triple product, so a product that
107 // still does not fit is the only one reported as infinite here.
108 const auto align = [](ExactWide& magnitude, int& bit) noexcept {
109 if (magnitude == 0) return true;
110 if (bit < 0) {
111 const int drop = -bit;
112 bool sticky = true;
113 if (drop < 128) {
114 sticky = (magnitude & ((ExactWide{1} << drop) - 1)) != 0;
115 magnitude >>= drop;
116 } else {
117 magnitude = 0;
118 }
119 if (sticky) magnitude |= ExactWide{1};
120 bit = 0;
121 if (magnitude == 0) return true;
122 }
123 const int digit = bit >> 5;
124 return digit >= 0 && digit + 4 < kLimbs;
125 };
126 if (!align(low_magnitude, low_bit) ||
127 !align(high_magnitude, high_bit)) {
128 nonfinite_ += negative ? -std::numeric_limits<double>::infinity()
129 : std::numeric_limits<double>::infinity();
130 return;
131 }
132 addMagnitude(low_magnitude, low_bit, negative);
133 addMagnitude(high_magnitude, high_bit, negative);
134 }
135
138 void assignLimbs(const std::int64_t* digits) noexcept
139 {
140 std::memcpy(limb_, digits, sizeof(limb_));
141 pending_ = 0;
142 normalize();
143 }
144
146 void merge(const ExactSum& other) noexcept
147 {
148 normalize();
149 ExactSum copy = other;
150 copy.normalize();
151 for (int k = 0; k < kLimbs; ++k)
152 limb_[k] += copy.limb_[k];
153 nonfinite_ += copy.nonfinite_;
154 normalize();
155 }
156
159 void normalize() noexcept
160 {
161 for (int k = 0; k + 1 < kLimbs; ++k) {
162 const std::int64_t carry = limb_[k] >> 32;
163 limb_[k] -= carry * (std::int64_t{1} << 32);
164 limb_[k + 1] += carry;
165 }
166 pending_ = 0;
167 }
168
170 std::int64_t* limbs() noexcept
171 {
172 return limb_;
173 }
174 const std::int64_t* limbs() const noexcept
175 {
176 return limb_;
177 }
178
180 double nonfinite() const noexcept
181 {
182 return nonfinite_;
183 }
184 void setNonfinite(double value) noexcept
185 {
186 nonfinite_ = value;
187 }
188
190 double value() const noexcept
191 {
192 if (nonfinite_ != 0.0 || std::isnan(nonfinite_)) return nonfinite_;
193 ExactSum work = *this;
194 work.normalize();
195 bool negative = work.limb_[kLimbs - 1] < 0;
196 if (negative) {
197 for (int k = 0; k < kLimbs; ++k)
198 work.limb_[k] = -work.limb_[k];
199 work.normalize();
200 }
201 int top = kLimbs - 1;
202 while (top >= 0 && work.limb_[top] == 0)
203 --top;
204 if (top < 0) return 0.0;
205 int top_bit = 63;
206 while (!((static_cast<std::uint64_t>(work.limb_[top]) >> top_bit) & 1u))
207 --top_bit;
208 const long msb = 32L * top + top_bit; // weight 2^(msb - kOrigin)
209 const auto bit = [&](long index) -> std::uint64_t {
210 if (index < 0) return 0;
211 return (static_cast<std::uint64_t>(work.limb_[index >> 5]) >>
212 (index & 31)) &
213 1u;
214 };
215 // A subnormal double has quantum 2^-1074. Rounding to a 53-bit
216 // significand and then again inside ldexp is one ulp low, so the
217 // quantum decision is made once, ties to even.
218 constexpr long kSubnormalLimit = kOrigin - 1022;
219 if (msb < kSubnormalLimit) {
220 std::uint64_t quantum = 0;
221 if (msb >= kDoubleShift) {
222 for (long i = msb; i >= kDoubleShift; --i)
223 quantum = (quantum << 1) | bit(i);
224 const std::uint64_t round_bit = bit(kDoubleShift - 1);
225 bool sticky = false;
226 for (long i = kDoubleShift - 2; i >= 0 && !sticky; --i)
227 sticky = bit(i) != 0;
228 if (round_bit && (sticky || (quantum & 1u))) ++quantum;
229 } else if (msb == kDoubleShift - 1) {
230 bool sticky = false;
231 for (long i = msb - 1; i >= 0 && !sticky; --i)
232 sticky = bit(i) != 0;
233 if (sticky) quantum = 1;
234 }
235 const double magnitude =
236 std::ldexp(static_cast<double>(quantum), -kDoubleShift);
237 return negative ? -magnitude : magnitude;
238 }
239 std::uint64_t mantissa = 0;
240 for (long i = msb; i > msb - 53; --i)
241 mantissa = (mantissa << 1) | bit(i);
242 const std::uint64_t round_bit = bit(msb - 53);
243 bool sticky = false;
244 for (long i = msb - 54; i >= 0 && !sticky; --i)
245 sticky = bit(i) != 0;
246 if (round_bit && (sticky || (mantissa & 1u))) ++mantissa;
247 const long scale = msb - 52 - kOrigin;
248 const double magnitude =
249 std::ldexp(static_cast<double>(mantissa), static_cast<int>(scale));
250 return negative ? -magnitude : magnitude;
251 }
252
253private:
254 // The widest integer the compiler offers is a GNU extension; __extension__
255 // keeps -Wpedantic quiet for every includer of this header.
256 __extension__ typedef unsigned __int128 ExactWide;
257
258 struct Factor {
259 ExactWide significand = 0;
260 int lsb = 0;
261 bool negative = false;
262 bool nonfinite = false;
263 };
264
265 static Factor factorOf(double x) noexcept
266 {
267 Factor factor;
268 std::uint64_t bits = 0;
269 std::memcpy(&bits, &x, sizeof(bits));
270 factor.negative = (bits >> 63) != 0;
271 const std::uint64_t exponent = (bits >> 52) & 0x7ffu;
272 if (exponent == 0x7ffu) {
273 factor.nonfinite = true;
274 return factor;
275 }
276 std::uint64_t mantissa = bits & ((std::uint64_t{1} << 52) - 1);
277 if (exponent != 0) {
278 mantissa |= std::uint64_t{1} << 52;
279 factor.lsb = static_cast<int>(exponent) - 1;
280 }
281 factor.significand = mantissa;
282 return factor;
283 }
284
286 void addMagnitude(ExactWide magnitude, int bit, bool negative) noexcept
287 {
288 if (magnitude == 0) return;
289 std::uint32_t piece[4];
290 for (int i = 0; i < 4; ++i) {
291 piece[i] = static_cast<std::uint32_t>(magnitude & 0xffffffffu);
292 magnitude >>= 32;
293 }
294 const unsigned shift = static_cast<unsigned>(bit & 31);
295 const int digit = bit >> 5;
296 std::uint64_t spill = 0;
297 for (int i = 0; i < 4; ++i) {
298 const std::uint64_t wide =
299 (static_cast<std::uint64_t>(piece[i]) << shift) | spill;
300 const std::int64_t chunk =
301 static_cast<std::int64_t>(wide & 0xffffffffu);
302 spill = wide >> 32;
303 if (negative)
304 limb_[digit + i] -= chunk;
305 else
306 limb_[digit + i] += chunk;
307 }
308 if (spill != 0) {
309 const std::int64_t chunk = static_cast<std::int64_t>(spill);
310 if (negative)
311 limb_[digit + 4] -= chunk;
312 else
313 limb_[digit + 4] += chunk;
314 }
315 if (++pending_ >= kNormalizeInterval) normalize();
316 }
317
318 static constexpr int kNormalizeInterval = 1 << 28;
319
320 std::int64_t limb_[kLimbs];
321 double nonfinite_ = 0.0;
322 int pending_ = 0;
323};
324
325} // namespace linalg
326} // namespace gpr
327
328#endif // GPR_LINALG_EXACT_SUM_H_
@ x
Definition Enums.h:28
void addProduct(double a, double b) noexcept
Definition ExactSum.h:70
double nonfinite() const noexcept
Sum of the non-finite addends (0 when every addend was finite).
Definition ExactSum.h:180
void assignLimbs(const std::int64_t *digits) noexcept
Definition ExactSum.h:138
void add(double x) noexcept
Definition ExactSum.h:54
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
Definition ExactSum.h:190
const std::int64_t * limbs() const noexcept
Definition ExactSum.h:174
void addTripleProduct(double a, double b, double c) noexcept
Definition ExactSum.h:86
static constexpr int kOrigin
Bit 0 has weight 2^-kOrigin.
Definition ExactSum.h:43
ExactSum() noexcept
Definition ExactSum.h:47
void setNonfinite(double value) noexcept
Definition ExactSum.h:184
std::int64_t * limbs() noexcept
Canonical digits for message passing: normalize(), then limbs().
Definition ExactSum.h:170
static constexpr int kLimbs
Definition ExactSum.h:41
static constexpr int kDoubleShift
A finite double's least bit lies this many bits above bit 0.
Definition ExactSum.h:45
void normalize() noexcept
Definition ExactSum.h:159
void merge(const ExactSum &other) noexcept
Adds another accumulator exactly.
Definition ExactSum.h:146
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
STL namespace.