The exact sum rounded once to the nearest double, ties to even.
191 {
192 if (nonfinite_ != 0.0 || std::isnan(nonfinite_)) return nonfinite_;
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 }
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;
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
216
217
218 constexpr long kSubnormalLimit =
kOrigin - 1022;
219 if (msb < kSubnormalLimit) {
220 std::uint64_t quantum = 0;
223 quantum = (quantum << 1) | bit(i);
225 bool sticky = false;
227 sticky = bit(i) != 0;
228 if (round_bit && (sticky || (quantum & 1u))) ++quantum;
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 }
static constexpr int kOrigin
Bit 0 has weight 2^-kOrigin.