fixed_point128 1.0.1.0
128 bit integer, fixed point and floating point arithmetic for C++20
Loading...
Searching...
No Matches
fp128_decimal.h
Go to the documentation of this file.
1/***********************************************************************************
2 MIT License
3
4 Copyright (c) 2025 Eric Gur (ericgur@iname.com)
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23************************************************************************************/
24
25/**
26 * @file fp128_decimal.h
27 * @brief Exact conversion between binary128 and decimal.
28 *
29 * A binary128 value is a 113 bit integer times a power of two, so its decimal expansion is finite:
30 * at most 4933 digits before the point and 16494 after it. Everything here works with that
31 * expansion in full rather than with an approximation of it, which is what lets the digits be
32 * correctly rounded at any requested precision and lets a decimal string be read back to the
33 * nearest representable value.
34 *
35 * The alternative - scaling by a power of ten held in the type itself - cannot do either. A
36 * negative power of ten is not representable in binary, so every scaling rounds, and the error
37 * compounds across the digits. That is what the previous conversions did, and it left the string
38 * form of a value about an ulp away from the value and unable to survive a round trip.
39 *
40 * These are implementation details of float128, not part of the interface.
41 *
42 * @see float128.h
43 */
44
45#ifndef FP128_DECIMAL_H
46#define FP128_DECIMAL_H
47
48#include <cstdint>
49#include "fp128_shared.h"
50
51namespace fp128
52{
53namespace detail
54{
55
56/**
57 * @brief Fixed capacity unsigned big integer, 32 bit limbs, least significant first.
58 *
59 * The operations are only the ones the conversions use - multiply and divide by a value that fits
60 * in a limb, shift, compare - so none of them needs a general multi word division.
61 *
62 * @tparam Capacity Limbs. big_uint, the one every conversion uses, is sized for the widest
63 * intermediate they need: reading the smallest subnormal back from its decimal form scales
64 * a 40 digit mantissa by 2^16716, which is 527 limbs. wide_big_uint holds the same for a
65 * mantissa of MAX_EXACT_DIGITS digits, which only an input that long needs.
66 */
67template <int32_t Capacity> class basic_big_uint
68{
69public:
70 static constexpr int32_t CAPACITY = Capacity; ///< Limbs.
71 static constexpr int32_t LIMB_BITS = 32; ///< Bits per limb.
72 static constexpr uint64_t LIMB_BASE = 1ull << LIMB_BITS; ///< One past the largest limb value.
73
74 /// @brief Constructs zero.
75 basic_big_uint() noexcept : used(0), limb {} {}
76
77 /// @brief Sets the value to a 128 bit integer.
78 void set(uint64_t low, uint64_t high) noexcept
79 {
80 clear();
81 limb[0] = static_cast<uint32_t>(low);
82 limb[1] = static_cast<uint32_t>(low >> 32);
83 limb[2] = static_cast<uint32_t>(high);
84 limb[3] = static_cast<uint32_t>(high >> 32);
85 used = 4;
86 trim();
87 }
88
89 /// @brief Sets the value to zero.
90 void clear() noexcept
91 {
92 for (int32_t i = 0; i < used; ++i)
93 limb[i] = 0;
94 used = 0;
95 }
96
97 [[nodiscard]] bool is_zero() const noexcept { return used == 0; }
98 [[nodiscard]] int32_t limbs() const noexcept { return used; }
99 [[nodiscard]] uint32_t at(int32_t index) const noexcept { return (index < used) ? limb[index] : 0u; }
100
101 /// @brief Index of the highest set bit, or -1 when the value is zero.
102 [[nodiscard]] int32_t bit_length() const noexcept
103 {
104 if (used == 0)
105 return 0;
106 const uint32_t top = limb[used - 1];
107 int32_t bit = 0;
108 for (uint32_t probe = top; probe != 0; probe >>= 1)
109 ++bit;
110 return (used - 1) * LIMB_BITS + bit;
111 }
112
113 /// @brief Multiplies by a value that fits in a limb.
114 /// @param multiplier Value to multiply by
115 /// @return False when the product did not fit in the capacity.
116 bool mul_small(uint32_t multiplier) noexcept
117 {
118 uint64_t carry = 0;
119 for (int32_t i = 0; i < used; ++i) {
120 const uint64_t product = static_cast<uint64_t>(limb[i]) * multiplier + carry;
121 limb[i] = static_cast<uint32_t>(product);
122 carry = product >> LIMB_BITS;
123 }
124 while (carry != 0) {
125 if (used >= CAPACITY)
126 return false;
127 limb[used++] = static_cast<uint32_t>(carry);
128 carry >>= LIMB_BITS;
129 }
130 return true;
131 }
132
133 /// @brief Adds a value that fits in a limb.
134 void add_small(uint32_t addend) noexcept
135 {
136 uint64_t carry = addend;
137 for (int32_t i = 0; carry != 0; ++i) {
138 if (i >= used) {
139 if (i >= CAPACITY)
140 return;
141 limb[i] = 0;
142 used = i + 1;
143 }
144 const uint64_t sum = static_cast<uint64_t>(limb[i]) + carry;
145 limb[i] = static_cast<uint32_t>(sum);
146 carry = sum >> LIMB_BITS;
147 }
148 }
149
150 /// @brief Divides by a value that fits in a limb.
151 /// @param divisor Value to divide by, must not be zero
152 /// @return The remainder.
153 uint32_t divmod_small(uint32_t divisor) noexcept
154 {
155 uint64_t remainder = 0;
156 for (int32_t i = used - 1; i >= 0; --i) {
157 const uint64_t dividend = (remainder << LIMB_BITS) | limb[i];
158 limb[i] = static_cast<uint32_t>(dividend / divisor);
159 remainder = dividend % divisor;
160 }
161 trim();
162 return static_cast<uint32_t>(remainder);
163 }
164
165 /// @brief Multiplies in place by 10^count, in blocks that fit in a limb.
166 /// @return False when the product did not fit in the capacity.
167 bool mul_pow10(int32_t count) noexcept
168 {
169 // 10^9 is the largest power of ten below 2^32
170 while (count >= 9) {
171 if (!mul_small(1000000000u))
172 return false;
173 count -= 9;
174 }
175 return (count <= 0) || mul_small(POWERS_OF_10[count]);
176 }
177
178 /// @brief Divides in place by 10^count, reporting whether anything was discarded.
179 /// @param count Power of ten to divide by
180 /// @param sticky Set to true when a division left a non zero remainder
181 void div_pow10(int32_t count, bool& sticky) noexcept
182 {
183 while (count >= 9) {
184 sticky = (divmod_small(1000000000u) != 0) || sticky;
185 count -= 9;
186 }
187 if (count > 0)
188 sticky = (divmod_small(POWERS_OF_10[count]) != 0) || sticky;
189 }
190
191 /// @brief Shifts left, growing the value.
192 /// @return False when the result did not fit in the capacity.
193 bool shift_left(int32_t bits) noexcept
194 {
195 if (bits <= 0 || used == 0)
196 return true;
197
198 const int32_t limb_shift = bits / LIMB_BITS;
199 const int32_t bit_shift = bits % LIMB_BITS;
200 const int32_t extra = (bit_shift != 0) ? 1 : 0;
201 if (used + limb_shift + extra > CAPACITY)
202 return false;
203
204 // Copied from the top down so a source limb is read before it is overwritten.
205 for (int32_t i = used - 1 + extra; i >= 0; --i) {
206 uint32_t value = 0;
207 if (bit_shift == 0) {
208 value = (i < used) ? limb[i] : 0u;
209 } else {
210 const uint32_t high = (i < used) ? limb[i] : 0u;
211 const uint32_t low = (i > 0) ? limb[i - 1] : 0u;
212 value = static_cast<uint32_t>((high << bit_shift) | (low >> (LIMB_BITS - bit_shift)));
213 }
214 limb[i + limb_shift] = value;
215 }
216 for (int32_t i = 0; i < limb_shift; ++i)
217 limb[i] = 0;
218
219 used += limb_shift + extra;
220 trim();
221 return true;
222 }
223
224 /// @brief Shifts right, discarding the bits that fall off the bottom.
225 void shift_right(int32_t bits) noexcept
226 {
227 if (bits <= 0 || used == 0)
228 return;
229 const int32_t limb_shift = bits / LIMB_BITS;
230 const int32_t bit_shift = bits % LIMB_BITS;
231 if (limb_shift >= used) {
232 clear();
233 return;
234 }
235
236 for (int32_t i = 0; i + limb_shift < used; ++i) {
237 const uint32_t low = limb[i + limb_shift];
238 if (bit_shift == 0) {
239 limb[i] = low;
240 } else {
241 const uint32_t high = (i + limb_shift + 1 < used) ? limb[i + limb_shift + 1] : 0u;
242 limb[i] = static_cast<uint32_t>((low >> bit_shift) | (high << (LIMB_BITS - bit_shift)));
243 }
244 }
245 const int32_t remaining = used - limb_shift;
246 for (int32_t i = remaining; i < used; ++i)
247 limb[i] = 0;
248 used = remaining;
249 trim();
250 }
251
252 /// @brief Clears every bit at or above the given position.
253 void keep_low_bits(int32_t bits) noexcept
254 {
255 if (bits <= 0) {
256 clear();
257 return;
258 }
259 const int32_t limb_index = bits / LIMB_BITS;
260 const int32_t bit_index = bits % LIMB_BITS;
261 if (limb_index >= used)
262 return;
263
264 for (int32_t i = limb_index + ((bit_index != 0) ? 1 : 0); i < used; ++i)
265 limb[i] = 0;
266 if (bit_index != 0)
267 limb[limb_index] &= (1u << bit_index) - 1u;
268 trim();
269 }
270
271 /**
272 * @brief Treats the value as a fraction, multiplies it by a small value and peels off the
273 * integer part that crosses the point.
274 *
275 * The buffer holds a fraction scaled by 2^(width*32), so multiplying it produces digits above
276 * the point that no longer belong in it. Those are what the caller wants.
277 *
278 * @param multiplier Value to multiply by, small enough that the overflow fits in a limb
279 * @param width Limb count the fraction occupies
280 * @return The integer part the multiply produced.
281 */
282 uint32_t fraction_mul_extract(uint32_t multiplier, int32_t width) noexcept
283 {
284 uint64_t carry = 0;
285 for (int32_t i = 0; i < width; ++i) {
286 const uint64_t product = static_cast<uint64_t>(limb[i]) * multiplier + carry;
287 limb[i] = static_cast<uint32_t>(product);
288 carry = product >> LIMB_BITS;
289 }
290 used = width;
291 trim();
292 return static_cast<uint32_t>(carry);
293 }
294
295 /// @brief Compares the value against one half of 2^(width*32), the fraction's midpoint.
296 /// @return 1 above the midpoint, -1 below it, 0 exactly on it.
297 [[nodiscard]] int32_t compare_half(int32_t width) const noexcept
298 {
299 const uint32_t top = at(width - 1);
300 constexpr uint32_t half_limb = 1u << (LIMB_BITS - 1);
301 if (top > half_limb)
302 return 1;
303 if (top < half_limb)
304 return -1;
305 for (int32_t i = 0; i < width - 1; ++i) {
306 if (at(i) != 0)
307 return 1;
308 }
309 return 0;
310 }
311
312 /// @brief Powers of ten that fit in a limb, indexed by the exponent.
313 static constexpr uint32_t POWERS_OF_10[10] = {1u, 10u, 100u, 1000u, 10000u,
314 100000u, 1000000u, 10000000u, 100000000u, 1000000000u};
315
316private:
317 /// @brief Drops the leading zero limbs so that used is the significant limb count.
318 void trim() noexcept
319 {
320 while (used > 0 && limb[used - 1] == 0)
321 --used;
322 }
323
324 int32_t used; ///< Significant limb count.
325 uint32_t limb[CAPACITY]; ///< Limbs, least significant first.
326};
327
328/// @brief The big integer every conversion uses, 560 limbs or 17920 bits.
330
331/// @brief Largest number of significant digits any conversion here produces.
332///
333/// A binary128 needs 36 to survive a round trip, and one more is kept so that a caller asking for
334/// the maximum can still see the digit that decides the rounding.
335inline constexpr int32_t MAX_SIGNIFICANT_DIGITS = 40;
336
337/// @brief Significant digits that settle the rounding of any decimal input exactly.
338///
339/// A rounding boundary - the point halfway between two neighbouring binary128 values - is an odd
340/// multiple of a power of two no smaller than 2^-16495, so its decimal expansion ends: at most 34
341/// digits for the odd multiplier and 0.699 digits per binary place below one, about 11565 in all.
342/// Digits past this many cannot carry the value across a boundary, so they only need to be known
343/// to be non zero.
344inline constexpr int32_t MAX_EXACT_DIGITS = 11700;
345
346/// @brief The big integer that holds MAX_EXACT_DIGITS digits scaled to the smallest subnormal,
347/// about 94600 bits. Twelve kilobytes, so it is only ever allocated on the heap.
349
350/// @brief Largest number of digits to_decimal_digits() produces.
351///
352/// Enough to write any finite binary128 out in full in fixed notation, the widest of which has
353/// 4933 digits before the point. The exact expansion of a subnormal runs to 16494 places after the
354/// point instead, and a request past this cap is filled with zeros rather than continuing it.
355inline constexpr int32_t MAX_OUTPUT_DIGITS = 5000;
356
357/// @brief Limbs of the fraction buffer. 16640 bits reaches below the smallest subnormal's last bit.
358inline constexpr int32_t FRACTION_LIMBS = 520;
359
360/// @brief How to_decimal_digits() rounds the last digit it keeps.
361enum class digit_rounding : uint8_t {
362 nearest_even, ///< to the nearest digit, a tie to the even one
363 toward_zero, ///< truncate
364 away_from_zero ///< up whenever anything was discarded
365};
366
367/**
368 * @brief Correctly rounded decimal digits of a finite, non zero binary128 value.
369 *
370 * The value is decomposed into an exact integer part and an exact fractional part, and the digits
371 * of each are produced by arithmetic that cannot round: repeated division by a power of ten for
372 * the integer part, repeated multiplication for the fraction. Only the last digit kept is rounded,
373 * once, from the exact remainder.
374 *
375 * @param mantissa_low Low QWORD of the 113 bit mantissa, its leading one at bit 112
376 * @param mantissa_high High QWORD of the mantissa
377 * @param exponent Unbiased exponent, so the value is mantissa * 2^(exponent-112)
378 * @param requested Significant digits wanted, clamped to MAX_SIGNIFICANT_DIGITS
379 * @param digits Output buffer, receives `requested` digits as characters with no terminator
380 * @param exact Optional, set to true when the digits are the whole value and nothing was discarded
381 * @param direction How the last digit is rounded: digit_rounding::nearest_even, the default, or
382 * towards zero or away from it, which is what the directed rounding modes come down to once
383 * the sign of the value is known
384 * @return The decimal exponent: the value is `0.<digits>` * 10^result.
385 */
386inline int32_t to_decimal_digits(uint64_t mantissa_low, uint64_t mantissa_high, int32_t exponent, int32_t requested, char* digits,
387 bool* exact = nullptr, digit_rounding direction = digit_rounding::nearest_even) noexcept
388{
389 if (requested > MAX_OUTPUT_DIGITS)
390 requested = MAX_OUTPUT_DIGITS;
391 if (requested < 1)
392 requested = 1;
393
394 // The value is mantissa * 2^binary_exponent.
395 const int32_t binary_exponent = exponent - 112;
396
397 big_uint integer_part;
398 big_uint fraction;
399 integer_part.set(mantissa_low, mantissa_high);
400
401 if (binary_exponent >= 0) {
402 integer_part.shift_left(binary_exponent);
403 } else {
404 const int32_t below_point = -binary_exponent;
405 // The fraction buffer holds the fractional part scaled by 2^(FRACTION_LIMBS*32). That
406 // scale reaches 2^-16640, below the 2^-16494 of the smallest subnormal's last bit, so the
407 // shift is always to the left and nothing is lost.
408 fraction.set(mantissa_low, mantissa_high);
409 fraction.keep_low_bits(below_point);
410 fraction.shift_left(FRACTION_LIMBS * big_uint::LIMB_BITS - below_point);
411 integer_part.shift_right(below_point);
412 }
413
414 // Integer digits come out least significant first, nine at a time.
415 char reversed[5000];
416 int32_t integer_digits = 0;
417 while (!integer_part.is_zero() && integer_digits + 9 <= static_cast<int32_t>(sizeof(reversed))) {
418 uint32_t block = integer_part.divmod_small(1000000000u);
419 for (int32_t i = 0; i < 9; ++i) {
420 reversed[integer_digits++] = static_cast<char>('0' + (block % 10));
421 block /= 10;
422 }
423 }
424 // The last block is zero padded to nine digits, and those zeros are not part of the value.
425 while (integer_digits > 0 && reversed[integer_digits - 1] == '0')
426 --integer_digits;
427
428 // The value is 0.<digits> * 10^decimal_exponent. A value below one has no integer digits, and
429 // the zeros the fraction starts with are not significant: each one moves the exponent instead.
430 int32_t decimal_exponent = integer_digits;
431 int32_t emitted = 0;
432 char rounding_digit = '0';
433 bool have_rounding_digit = false;
434 bool rest_nonzero = false;
435 bool seen_significant = integer_digits > 0;
436
437 const auto append_digit = [&](char digit) {
438 if (emitted < requested)
439 digits[emitted++] = digit;
440 else if (!have_rounding_digit) {
441 rounding_digit = digit;
442 have_rounding_digit = true;
443 } else {
444 rest_nonzero = rest_nonzero || (digit != '0');
445 }
446 };
447
448 for (int32_t i = integer_digits - 1; i >= 0; --i)
449 append_digit(reversed[i]);
450
451 // Fraction digits, nine at a time, until the request and its rounding digit are both covered.
452 while (!fraction.is_zero() && (emitted < requested || !have_rounding_digit)) {
453 uint32_t block = fraction.fraction_mul_extract(1000000000u, FRACTION_LIMBS);
454 char block_digits[9];
455 for (int32_t i = 8; i >= 0; --i) {
456 block_digits[i] = static_cast<char>('0' + (block % 10));
457 block /= 10;
458 }
459 for (int32_t i = 0; i < 9; ++i) {
460 if (!seen_significant) {
461 if (block_digits[i] == '0') {
462 --decimal_exponent;
463 continue;
464 }
465 seen_significant = true;
466 }
467 append_digit(block_digits[i]);
468 }
469 }
470 // Anything still left in the buffer sits below every digit produced.
471 rest_nonzero = rest_nonzero || !fraction.is_zero();
472
473 // A value whose expansion ended early is padded, which is exact.
474 while (emitted < requested)
475 digits[emitted++] = '0';
476
477 if (exact != nullptr)
478 *exact = !rest_nonzero && (!have_rounding_digit || rounding_digit == '0');
479
480 // Round against the exact remainder: half to even, or in the direction asked for.
481 bool round_up = false;
482 if (direction == digit_rounding::nearest_even) {
483 if (rounding_digit > '5')
484 round_up = true;
485 else if (rounding_digit == '5')
486 round_up = rest_nonzero || ((digits[requested - 1] - '0') % 2 != 0);
487 } else if (direction == digit_rounding::away_from_zero) {
488 round_up = rest_nonzero || (have_rounding_digit && rounding_digit != '0');
489 }
490
491 if (round_up) {
492 int32_t index = requested - 1;
493 while (index >= 0 && digits[index] == '9')
494 digits[index--] = '0';
495 if (index >= 0) {
496 ++digits[index];
497 } else {
498 // Every digit was a nine, so the carry created a new leading one.
499 digits[0] = '1';
500 ++decimal_exponent;
501 }
502 }
503
504 return decimal_exponent;
505}
506
507/**
508 * @brief Reads a decimal mantissa and exponent back to the nearest binary128.
509 *
510 * The value is digits * 10^exponent10. Both directions are computed exactly - a positive power of
511 * ten by multiplication, a negative one by division with the discarded remainder kept as a sticky
512 * bit - so the 113 bit result is the correctly rounded one and never two roundings deep.
513 *
514 * @tparam Capacity Limbs of the workspace
515 * @param value Workspace, which has to hold max_kept digits scaled to the bottom of the format:
516 * a big_uint for MAX_SIGNIFICANT_DIGITS, a wide_big_uint for MAX_EXACT_DIGITS
517 * @param digits Decimal digits, most significant first, no sign and no point
518 * @param count Number of digits
519 * @param max_kept Significant digits used as such; any after them only count as a sticky bit
520 * @param exponent10 Power of ten the digits are scaled by
521 * @param mantissa_low Receives the low QWORD of the 113 bit mantissa
522 * @param mantissa_high Receives the high QWORD
523 * @param exponent Receives the unbiased exponent, so the value is mantissa * 2^(exponent-112)
524 * @param extra Optional. When given, the mantissa is not rounded: it receives the top 113 bits,
525 * truncated, and this receives the bits below them in the form float128::round_pack() takes,
526 * the first one dropped in bit 63 and anything below it jammed into bit 0. A result that
527 * turns out subnormal keeps fewer than 113 bits, so only the caller can round it once.
528 * @return False when the value is zero, or too large or too small for the format to hold, in which
529 * case the exponent says which: below -100000 for an underflow, above 100000 for an
530 * overflow.
531 */
532template <int32_t Capacity>
533inline bool decimal_to_binary(basic_big_uint<Capacity>& value, const char* digits, int32_t count, int32_t max_kept, int32_t exponent10,
534 uint64_t& mantissa_low, uint64_t& mantissa_high, int32_t& exponent, uint64_t* extra) noexcept
535{
536 mantissa_low = mantissa_high = 0;
537 exponent = 0;
538
539 // Leading zeros carry no information, trailing ones move into the exponent.
540 int32_t first = 0;
541 while (first < count && digits[first] == '0')
542 ++first;
543 if (first == count)
544 return false; // the value is zero
545 while (count > first && digits[count - 1] == '0') {
546 --count;
547 ++exponent10;
548 }
549
550 // Digits past max_kept are read as a sticky bit only: they say the value lies strictly above
551 // the prefix, not how far. from_chars() hands over at most 40 digits plus one that stands for
552 // the rest, which is exact whenever the rounding of the prefix and of the prefix one unit up
553 // agree; when they do not, it hands over MAX_EXACT_DIGITS, which is exact for every input.
554 int32_t kept = count - first;
555 bool sticky = false;
556 if (kept > max_kept) {
557 for (int32_t i = first + max_kept; i < count; ++i)
558 sticky = sticky || (digits[i] != '0');
559 exponent10 += kept - max_kept;
560 kept = max_kept;
561 }
562
563 value.clear();
564 for (int32_t i = 0; i < kept; ++i) {
565 value.mul_small(10u);
566 value.add_small(static_cast<uint32_t>(digits[first + i] - '0'));
567 }
568
569 // A rough decimal magnitude is enough to reject what cannot be represented before building an
570 // intermediate for it. log10 of the largest finite value is 4932, of the smallest subnormal
571 // -4966, and one extra digit of slack on each side keeps every borderline case on the slow
572 // path where it is decided exactly.
573 const int32_t magnitude = exponent10 + kept;
574 if (magnitude > 4935) {
575 exponent = 200000;
576 return false;
577 }
578 if (magnitude < -4970) {
579 exponent = -200000;
580 return false;
581 }
582
583 int32_t binary_exponent = 0;
584 if (exponent10 >= 0) {
585 if (!value.mul_pow10(exponent10)) {
586 exponent = 200000;
587 return false;
588 }
589 } else {
590 // Scaling up before the division leaves room for the 113 bits wanted plus a guard bit.
591 // A decimal place is log2(10) = 3.3219 bits and 10/3 is a hair more, so the shift always
592 // covers the division with the fixed 160 bits of slack left over. Rounding that factor up
593 // to four instead overshoots by 3000 limbs at the bottom of the exponent range, which is
594 // past the capacity: the conversion then failed rather than being merely wasteful.
595 const int32_t headroom = (-exponent10) * 10 / 3 + 160;
596 if (!value.shift_left(headroom)) {
597 exponent = -200000;
598 return false;
599 }
600 binary_exponent -= headroom;
601 value.div_pow10(-exponent10, sticky);
602 }
603
604 if (value.is_zero()) {
605 exponent = -200000;
606 return false;
607 }
608
609 // Take the top 113 bits, with the bit below them and everything under that.
610 const int32_t bits = value.bit_length();
611 const int32_t drop = bits - 113;
612 if (drop > 0) {
613 // The guard bit and the sticky bits have to be read before the shift discards them.
614 const int32_t guard_index = drop - 1;
615 const uint32_t guard = (value.at(guard_index / big_uint::LIMB_BITS) >> (guard_index % big_uint::LIMB_BITS)) & 1u;
616 for (int32_t i = 0; i < guard_index && !sticky; ++i)
617 sticky = ((value.at(i / big_uint::LIMB_BITS) >> (i % big_uint::LIMB_BITS)) & 1u) != 0;
618
619 for (int32_t i = 0; i < drop; ++i)
620 value.divmod_small(2);
621 binary_exponent += drop;
622
623 if (extra != nullptr) {
624 *extra = (static_cast<uint64_t>(guard) << 63) | (sticky ? 1u : 0u);
625 }
626 // round half to even
627 else if (guard != 0 && (sticky || (value.at(0) & 1u) != 0)) {
628 value.add_small(1u);
629 // A carry out of 113 bits lands on the next power of two.
630 if (value.bit_length() > 113) {
631 value.divmod_small(2);
632 ++binary_exponent;
633 }
634 }
635 } else {
636 if (drop < 0) {
637 value.shift_left(-drop);
638 binary_exponent += drop;
639 }
640 if (extra != nullptr)
641 *extra = sticky ? 1u : 0u;
642 }
643
644 mantissa_low = static_cast<uint64_t>(value.at(0)) | (static_cast<uint64_t>(value.at(1)) << 32);
645 mantissa_high = static_cast<uint64_t>(value.at(2)) | (static_cast<uint64_t>(value.at(3)) << 32);
646 // The caller's convention puts the leading one at bit 112, so the exponent counts from there.
647 exponent = binary_exponent + 112;
648 return true;
649}
650
651/**
652 * @brief Reads a decimal mantissa and exponent back to the nearest binary128.
653 *
654 * decimal_to_binary() with a big_uint of its own, keeping MAX_SIGNIFICANT_DIGITS digits and reading
655 * any after them as a sticky bit. See decimal_to_binary() for the parameters.
656 */
657inline bool from_decimal_digits(const char* digits, int32_t count, int32_t exponent10, uint64_t& mantissa_low, uint64_t& mantissa_high,
658 int32_t& exponent, uint64_t* extra = nullptr) noexcept
659{
660 big_uint value;
661 return decimal_to_binary(value, digits, count, MAX_SIGNIFICANT_DIGITS, exponent10, mantissa_low, mantissa_high, exponent, extra);
662}
663
664} // namespace detail
665} // namespace fp128
666
667#endif // FP128_DECIMAL_H
Fixed capacity unsigned big integer, 32 bit limbs, least significant first.
bool mul_small(uint32_t multiplier) noexcept
Multiplies by a value that fits in a limb.
static constexpr uint64_t LIMB_BASE
static constexpr int32_t CAPACITY
int32_t compare_half(int32_t width) const noexcept
Compares the value against one half of 2^(width*32), the fraction's midpoint.
uint32_t fraction_mul_extract(uint32_t multiplier, int32_t width) noexcept
Treats the value as a fraction, multiplies it by a small value and peels off the integer part that cr...
void keep_low_bits(int32_t bits) noexcept
Clears every bit at or above the given position.
int32_t limbs() const noexcept
uint32_t divmod_small(uint32_t divisor) noexcept
Divides by a value that fits in a limb.
bool shift_left(int32_t bits) noexcept
Shifts left, growing the value.
void shift_right(int32_t bits) noexcept
Shifts right, discarding the bits that fall off the bottom.
bool mul_pow10(int32_t count) noexcept
Multiplies in place by 10^count, in blocks that fit in a limb.
basic_big_uint() noexcept
Constructs zero.
bool is_zero() const noexcept
static constexpr uint32_t POWERS_OF_10[10]
uint32_t at(int32_t index) const noexcept
void div_pow10(int32_t count, bool &sticky) noexcept
Divides in place by 10^count, reporting whether anything was discarded.
void set(uint64_t low, uint64_t high) noexcept
Sets the value to a 128 bit integer.
void clear() noexcept
Sets the value to zero.
int32_t bit_length() const noexcept
Index of the highest set bit, or -1 when the value is zero.
static constexpr int32_t LIMB_BITS
void add_small(uint32_t addend) noexcept
Adds a value that fits in a limb.
Shared definitions, intrinsics, and helper functions for 128-bit fixed-point arithmetic.
int32_t to_decimal_digits(uint64_t mantissa_low, uint64_t mantissa_high, int32_t exponent, int32_t requested, char *digits, bool *exact=nullptr, digit_rounding direction=digit_rounding::nearest_even) noexcept
Correctly rounded decimal digits of a finite, non zero binary128 value.
constexpr int32_t FRACTION_LIMBS
Limbs of the fraction buffer. 16640 bits reaches below the smallest subnormal's last bit.
constexpr int32_t MAX_EXACT_DIGITS
Significant digits that settle the rounding of any decimal input exactly.
digit_rounding
How to_decimal_digits() rounds the last digit it keeps.
@ nearest_even
to the nearest digit, a tie to the even one
@ away_from_zero
up whenever anything was discarded
basic_big_uint< 3072 > wide_big_uint
The big integer that holds MAX_EXACT_DIGITS digits scaled to the smallest subnormal,...
basic_big_uint< 560 > big_uint
The big integer every conversion uses, 560 limbs or 17920 bits.
@ toward_zero
roundTowardZero
Definition float128.h:243
@ nearest_even
roundTiesToEven, the default
Definition float128.h:242
constexpr int32_t MAX_OUTPUT_DIGITS
Largest number of digits to_decimal_digits() produces.
constexpr int32_t MAX_SIGNIFICANT_DIGITS
Largest number of significant digits any conversion here produces.
bool decimal_to_binary(basic_big_uint< Capacity > &value, const char *digits, int32_t count, int32_t max_kept, int32_t exponent10, uint64_t &mantissa_low, uint64_t &mantissa_high, int32_t &exponent, uint64_t *extra) noexcept
Reads a decimal mantissa and exponent back to the nearest binary128.
bool from_decimal_digits(const char *digits, int32_t count, int32_t exponent10, uint64_t &mantissa_low, uint64_t &mantissa_high, int32_t &exponent, uint64_t *extra=nullptr) noexcept
Reads a decimal mantissa and exponent back to the nearest binary128.
Everything the library provides.
float128 remainder(const float128 &x, const float128 &y) noexcept
Definition float128.h:6305