xrpld
Loading...
Searching...
No Matches
tests/libxrpl/basics/Number.cpp
1#include <xrpl/basics/Number.h>
2
3#include <xrpl/beast/utility/Zero.h>
4#include <xrpl/protocol/IOUAmount.h>
5#include <xrpl/protocol/Issue.h>
6#include <xrpl/protocol/STAmount.h>
7#include <xrpl/protocol/SystemParameters.h>
8#include <xrpl/protocol/XRPAmount.h>
9
10// NOLINTNEXTLINE(misc-include-cleaner)
11#include <boost/multiprecision/cpp_dec_float.hpp>
12#include <boost/multiprecision/number.hpp>
13
14#include <gtest/gtest.h>
15
16#include <algorithm>
17#include <array>
18#include <cctype>
19#include <cstdint>
20#include <functional>
21#include <iomanip>
22#include <limits>
23#include <map>
24#include <ranges>
25#include <sstream>
26#include <stdexcept>
27#include <string>
28#include <tuple>
29#include <utility>
30#include <vector>
31
32namespace xrpl {
33
34using BigInt = boost::multiprecision::cpp_int;
35using Dec = boost::multiprecision::cpp_dec_float_50;
36
37static std::string
38fmt(BigInt const& value)
39{
40 auto s = to_string(value);
41 std::string out;
42 int count = 0;
43 for (char const& ch : std::views::reverse(s))
44 {
45 if (count != 0 && count % 3 == 0 && (isdigit(ch) != 0))
46 out.insert(out.begin(), '_');
47 out.insert(out.begin(), ch);
48 ++count;
49 }
50 return out;
51}
52
55{
56 BigInt v = n.mantissa();
57 auto e = n.exponent();
58
59 for (; e > 0; --e)
60 v *= 10;
61 for (; e < 0; ++e)
62 {
63 EXPECT_EQ(v % 10, 0);
64 v /= 10;
65 }
66 return v;
67}
68
69template <class T = Dec>
70static T
71pow10(int n)
72{
73 if (n == 0)
74 return 1;
75 if (n == 1)
76 return 10;
77
78 if (n > 1)
79 {
80 auto r = pow10<T>(n / 2);
81 r *= r;
82 if (n % 2 != 0)
83 r *= 10;
84 return r;
85 }
86
87 T p = 1;
88 p /= pow10<T>(-n);
89 return p;
90}
91
92static std::string
93fmt(Dec const& value)
94{
96 os << std::setprecision(40) << value;
97 return os.str();
98}
99
100TEST(NumberTest, zero)
101{
102 for (auto const mantissaScale : MantissaRange::getAllScales())
103 {
104 NumberMantissaScaleGuard const sg(mantissaScale);
105
106 for (Number const& z : {Number{0, 0}, Number{0}})
107 {
108 EXPECT_EQ(z.mantissa(), 0);
109 EXPECT_EQ(z.exponent(), Number{}.exponent());
110
111 EXPECT_EQ((z + z), z);
112 EXPECT_EQ((z - z), z);
113 EXPECT_EQ(z, -z);
114 }
115 }
116}
117
118TEST(NumberTest, limits)
119{
120 for (auto const mantissaScale : MantissaRange::getAllScales())
121 {
122 NumberMantissaScaleGuard const sg(mantissaScale);
123
124 auto const scale = Number::getMantissaScale();
125 bool caught = false;
126 auto const minMantissa = Number::minMantissa();
127 try
128 {
129 [[maybe_unused]] Number const x =
130 Number{false, minMantissa * 10, 32768, Number::Normalized{}};
131 }
132 catch (std::overflow_error const&)
133 {
134 caught = true;
135 }
136 EXPECT_TRUE(caught);
137
138 auto const test = [](auto const& x, auto const& y, int line) {
139 auto const result = x == y;
141 ss << x << " == " << y << " -> " << (result ? "true" : "false");
142 EXPECT_TRUE(result) << ss.str() << " (" << __FILE__ << ":" << line << ")";
143 };
144
145 test(
146 Number{false, minMantissa * 10, 32767, Number::Normalized{}},
147 Number{false, minMantissa, 32768, Number::Normalized{}},
148 __LINE__);
149 test(Number{false, minMantissa, -32769, Number::Normalized{}}, Number{}, __LINE__);
150 test(
151 Number{false, minMantissa, 32000, Number::Normalized{}} * 1'000 +
152 Number{false, 1'500, 32000, Number::Normalized{}},
153 Number{false, minMantissa + 2, 32003, Number::Normalized{}},
154 __LINE__);
155 // 9,223,372,036,854,775,808
156
157 test(
160 ? Number{-9'223'372'036'854'776, 3}
161 : Number{true, 9'223'372'036'854'775'808ULL, 0, Number::Normalized{}},
162 __LINE__);
163 test(
165 scale == MantissaRange::MantissaScale::Small ? Number{-9'223'372'036'854'776, 3}
166 : Number{-9'223'372'036'854'775'807},
167 __LINE__);
168 test(
170 Number{
172 ? 9'223'372'036'854'776
174 18 - Number::mantissaLog()},
175 __LINE__);
176 caught = false;
177 try
178 {
179 [[maybe_unused]]
180 Number const q = Number{false, minMantissa, 32767, Number::Normalized{}} * 100;
181 }
182 catch (std::overflow_error const&)
183 {
184 caught = true;
185 }
186 EXPECT_TRUE(caught);
187
188 try
189 {
190 Number{1, 2000000, Number::Normalized{}};
191 ADD_FAILURE();
192 }
193 catch (std::overflow_error const& e)
194 {
195 std::string const expected = "Number::normalize 2";
196 EXPECT_EQ(e.what(), expected) << e.what();
197 }
198
200 {
201 // Normalization with the other scales, including the older large mantissa scales, will
202 // overflow.
204 // The display of large exponents won't go above kMaxExponent
205 EXPECT_EQ(to_string(bigNum), "9223372036854775810e32768") << bigNum;
206 // Perhaps surprisingly, this is ok, because the exponent range is related to when the
207 // number is _normalized_, and for mantissas > kMaxRep, the accessors return values that
208 // are not normalized.
209 EXPECT_EQ(bigNum.mantissa(), 922337203685477581ULL) << bigNum.mantissa();
210 EXPECT_EQ(bigNum.exponent(), 32769) << bigNum.exponent();
211 }
212 else
213 {
214 try
215 {
217 ADD_FAILURE();
218 }
219 catch (std::overflow_error const& e)
220 {
221 std::string const expected =
222 (scale == MantissaRange::MantissaScale::Small ? "Number::normalize 1"
223 : "Number::normalize 1.5");
224 EXPECT_EQ(e.what(), expected) << e.what();
225 }
226 }
227 }
228}
229
230TEST(NumberTest, add)
231{
232 for (auto const mantissaScale : MantissaRange::getAllScales())
233 {
234 NumberMantissaScaleGuard const sg(mantissaScale);
235
236 auto const scale = Number::getMantissaScale();
237
240
242 // TODO: Move these to the blocks where they're used
243 auto const cSmall = std::to_array<Case>({
244 {
245 Number{1'000'000'000'000'000, -15},
246 Number{6'555'555'555'555'555, -29},
247 Number{1'000'000'000'000'066, -15},
248 __LINE__,
249 },
250 {
251 Number{-1'000'000'000'000'000, -15},
252 Number{-6'555'555'555'555'555, -29},
253 Number{-1'000'000'000'000'066, -15},
254 __LINE__,
255 },
256 {
257 Number{-1'000'000'000'000'000, -15},
258 Number{6'555'555'555'555'555, -29},
259 Number{-9'999'999'999'999'344, -16},
260 __LINE__,
261 },
262 {
263 Number{-6'555'555'555'555'555, -29},
264 Number{1'000'000'000'000'000, -15},
265 Number{9'999'999'999'999'344, -16},
266 __LINE__,
267 },
268 {Number{}, Number{5}, Number{5}, __LINE__},
269 {Number{5}, Number{}, Number{5}, __LINE__},
270 {
271 Number{5'555'555'555'555'555, -32768},
272 Number{-5'555'555'555'555'554, -32768},
273 Number{0},
274 __LINE__,
275 },
276 {
277 Number{-9'999'999'999'999'999, -31},
278 Number{1'000'000'000'000'000, -15},
279 Number{9'999'999'999'999'990, -16},
280 __LINE__,
281 },
282 });
283 auto const cLarge = std::to_array<Case>(
284 // Note that items with extremely large mantissas need to be
285 // calculated, because otherwise they overflow uint64. Items from C
286 // with larger mantissa
287 {
288 {
289 Number{1'000'000'000'000'000, -15},
290 Number{6'555'555'555'555'555, -29},
291 Number{1'000'000'000'000'065'556, -18},
292 __LINE__,
293 },
294 {
295 Number{-1'000'000'000'000'000, -15},
296 Number{-6'555'555'555'555'555, -29},
297 Number{-1'000'000'000'000'065'556, -18},
298 __LINE__,
299 },
300 {
301 Number{-1'000'000'000'000'000, -15},
302 Number{6'555'555'555'555'555, -29},
303 Number{true, 9'999'999'999'999'344'444ULL, -19, Number::Normalized{}},
304 __LINE__,
305 },
306 {
307 Number{-6'555'555'555'555'555, -29},
308 Number{1'000'000'000'000'000, -15},
309 Number{false, 9'999'999'999'999'344'444ULL, -19, Number::Normalized{}},
310 __LINE__,
311 },
312 {Number{}, Number{5}, Number{5}, __LINE__},
313 {Number{5}, Number{}, Number{5}, __LINE__},
314 {
315 Number{5'555'555'555'555'555'000, -32768},
316 Number{-5'555'555'555'555'554'000, -32768},
317 Number{0},
318 __LINE__,
319 },
320 {
321 Number{-9'999'999'999'999'999, -31},
322 Number{1'000'000'000'000'000, -15},
323 Number{9'999'999'999'999'990, -16},
324 __LINE__,
325 },
326 // Items from cSmall expanded for the larger mantissa
327 {
328 Number{1'000'000'000'000'000'000, -18},
329 Number{6'555'555'555'555'555'555, -35},
330 Number{1'000'000'000'000'000'066, -18},
331 __LINE__,
332 },
333 {
334 Number{-1'000'000'000'000'000'000, -18},
335 Number{-6'555'555'555'555'555'555, -35},
336 Number{-1'000'000'000'000'000'066, -18},
337 __LINE__,
338 },
339 {
340 Number{-1'000'000'000'000'000'000, -18},
341 Number{6'555'555'555'555'555'555, -35},
342 Number{true, 9'999'999'999'999'999'344ULL, -19, Number::Normalized{}},
343 __LINE__,
344 },
345 {
346 Number{-6'555'555'555'555'555'555, -35},
347 Number{1'000'000'000'000'000'000, -18},
348 Number{false, 9'999'999'999'999'999'344ULL, -19, Number::Normalized{}},
349 __LINE__,
350 },
351 {Number{}, Number{5}, Number{5}, __LINE__},
352 {
353 Number{5'555'555'555'555'555'555, -32768},
354 Number{-5'555'555'555'555'555'554, -32768},
355 Number{0},
356 __LINE__,
357 },
358 {
359 Number{true, 9'999'999'999'999'999'999ULL, -37, Number::Normalized{}},
360 Number{1'000'000'000'000'000'000, -18},
361 Number{false, 9'999'999'999'999'999'990ULL, -19, Number::Normalized{}},
362 __LINE__,
363 },
364 {Number{Number::kMaxRep - 1}, Number{1, 0}, Number{Number::kMaxRep}, __LINE__},
365 // Test extremes
366 {
367 // Each Number operand rounds up, so the actual mantissa is
368 // minMantissa
369 Number{false, 9'999'999'999'999'999'999ULL, 0, Number::Normalized{}},
370 Number{false, 9'999'999'999'999'999'999ULL, 0, Number::Normalized{}},
371 Number{2, 19},
372 __LINE__,
373 },
374 {
375 // Does not round. Mantissas are going to be > kMaxRep, so if
376 // added together as uint64_t's, the result will overflow.
377 // With addition using uint128_t, there's no problem. After
378 // normalizing, the resulting mantissa ends up less than
379 // kMaxRep.
380 Number{false, 9'999'999'999'999'999'990ULL, 0, Number::Normalized{}},
381 Number{false, 9'999'999'999'999'999'990ULL, 0, Number::Normalized{}},
382 Number{false, 1'999'999'999'999'999'998ULL, 1, Number::Normalized{}},
383 __LINE__,
384 },
385 });
386 auto const cLargeLegacy = std::to_array<Case>({
387 {Number{Number::kMaxRep}, Number{6, -1}, Number{Number::kMaxRep / 10, 1}, __LINE__},
388 });
389 auto const cLarge320 = std::to_array<Case>({
390 {
392 Number{6, -1},
393 Number{(Number::kMaxRep / 10) + 1, 1},
394 __LINE__,
395 },
396 });
397 auto const cLargeCorrected = std::to_array<Case>({
398 {Number{Number::kMaxRep}, Number{6, -1}, Number{Number::kMaxRep}, __LINE__},
399 });
400 auto const test = [](auto const& c) {
401 for (auto const& [x, y, z, line] : c)
402 {
403 auto const result = x + y;
405 ss << x << " + " << y << " = " << result << ". Expected: " << z;
406 EXPECT_EQ(result, z) << ss.str() << " Line: " << line;
407 }
408 };
410 {
411 test(cSmall);
412 }
413 else
414 {
415 test(cLarge);
417 {
418 test(cLargeLegacy);
419 }
421 {
422 test(cLarge320);
423 }
424 else
425 {
426 test(cLargeCorrected);
427
428 // This has to be created in this block, because normalization with the other
429 // scales, including the older large mantissa scales, will overflow.
430 Number const bigResult{
432 auto const cBigNums = std::to_array<Case>({
433 {
434 // Add 3 to the mantissa to avoid rounding
435 Number::max(),
437 bigResult,
438 __LINE__,
439 },
440 });
441 test(cBigNums);
442 }
443 }
444 {
445 bool caught = false;
446 try
447 {
448 Number{false, Number::maxMantissa(), 32768, Number::Normalized{}} +
449 Number{false, Number::minMantissa(), 32767, Number::Normalized{}} * 5;
450 }
451 catch (std::overflow_error const&)
452 {
453 caught = true;
454 }
455 EXPECT_TRUE(caught);
456 }
457 }
458}
459
460TEST(NumberTest, add_sub_extreme_exponents)
461{
462 for (auto const mantissaScale : MantissaRange::getAllScales())
463 {
464 NumberMantissaScaleGuard const sg(mantissaScale);
465
466 auto const scale = Number::getMantissaScale();
467
470
471 // Special cases: Exponents at each end of the allowable range
472 for (auto const round : {
477 })
478 {
479 NumberRoundModeGuard const rg{round};
480
481 auto const bigMantissa = std::invoke([scale, round] {
482 auto m = Number::maxMantissa();
484 {
485 // At the large scales, the maxMantissa is not representable, so we need to
486 // shrink it down to a representable value.
487 m /= 10;
488 }
489 if (round == Number::RoundingMode::Upward)
490 {
491 // Rounding upward will overflow if the mantissa is at maxMantissa. Subtract an
492 // arbitrary small value to keep the mantissa near the limit, but with a
493 // little room to grow. 67 has no meaning, except that it's, you know,
494 // six seven.
495 m -= 67;
496 }
497 return m;
498 });
499 auto const params = {
501 // At the large scales, the maxMantissa is not representable, so we need to shrink
502 // it down to a representable value. Rounding upward will overflow if the mantissa
503 // is right at the all nines value. To keep things a little simpler, do those
504 // modifications unconditionally.
505 std::make_pair(bigMantissa, 1),
506 };
507 for (auto const& [mantissa, exponentOffset] : params)
508 {
509 auto const x = Number{mantissa, Number::kMaxExponent, Number::Normalized{}};
510 auto const y =
511 Number{mantissa, Number::kMinExponent + exponentOffset, Number::Normalized{}};
512
514 detail << "Scale: " << to_string(scale) << ", round: " << to_string(round)
515 << ", x: " << x << ", y: " << y;
516
517 EXPECT_EQ(x.mantissa(), mantissa);
518 EXPECT_EQ(x.exponent(), Number::kMaxExponent);
519 EXPECT_NE(x, beast::kZero);
520 EXPECT_EQ(y.mantissa(), mantissa);
521 EXPECT_EQ(y.exponent(), Number::kMinExponent + exponentOffset);
522 EXPECT_NE(y, beast::kZero);
523
524 {
525 // x + y
526 auto const result = x + y;
527
528 if (round == Number::RoundingMode::Upward)
529 {
530 // Rounding upward will take that little x-bit and round result up to the
531 // next representable value.
532 EXPECT_NE(result, x);
533 EXPECT_EQ(result, (Number{x.mantissa() + 1, x.exponent()}));
534 }
535 else
536 {
537 EXPECT_EQ(result, x);
538 }
539 }
540 {
541 // x - y
542 auto const result = x - y;
543
544 switch (round)
545 {
548 {
549 // Rounding TowardsZero was broken before Large330.
550 EXPECT_EQ(result, x) << detail.str();
551 break;
552 }
553 [[fallthrough]];
555 // Rounding downward (or toward zero in Large330) will take that little
556 // x-bit and round result down to the next representable value.
557 EXPECT_NE(result, x) << detail.str();
558 EXPECT_EQ(result, (Number{x.mantissa() - 1, x.exponent()}))
559 << detail.str();
560 break;
561 default:
562 // Rounding up and toNearest rounds back to the original value
563 EXPECT_EQ(result, x) << detail.str();
564 }
565 }
566 {
567 // y + x
568 auto const result = y + x;
569
570 if (round == Number::RoundingMode::Upward)
571 {
572 // Rounding upward will take that little x-bit and round result up to the
573 // next representable value.
574 EXPECT_NE(result, x);
575 EXPECT_EQ(result, (Number{x.mantissa() + 1, x.exponent()}));
576 }
577 else
578 {
579 EXPECT_EQ(result, x);
580 }
581 }
582 {
583 // y - x
584 auto const result = y - x;
585
586 switch (round)
587 {
590 {
591 // Rounding TowardsZero was broken before Large330.
592 EXPECT_EQ(result, -x) << detail.str();
593 break;
594 }
595 [[fallthrough]];
597 // Rounding upward (or toward zero in Large330) will take that little
598 // x-bit and round result up to the next representable negative value.
599 EXPECT_NE(result, -x) << detail.str();
600 EXPECT_EQ(result, (Number{-x.mantissa() + 1, x.exponent()}))
601 << detail.str();
602 break;
603 default:
604 // Rounding up and toNearest rounds back to the original value
605 EXPECT_EQ(result, -x) << detail.str();
606 }
607 }
608 }
609 }
610 }
611}
612
613TEST(NumberTest, sub)
614{
615 for (auto const mantissaScale : MantissaRange::getAllScales())
616 {
617 NumberMantissaScaleGuard const sg(mantissaScale);
618
619 auto const scale = Number::getMantissaScale();
620
622 auto const cSmall = std::to_array<Case>({
623 {
624 Number{1'000'000'000'000'000, -15},
625 Number{6'555'555'555'555'555, -29},
626 Number{9'999'999'999'999'344, -16},
627 __LINE__,
628 },
629 {
630 Number{6'555'555'555'555'555, -29},
631 Number{1'000'000'000'000'000, -15},
632 Number{-9'999'999'999'999'344, -16},
633 __LINE__,
634 },
635 {
636 Number{1'000'000'000'000'000, -15},
637 Number{1'000'000'000'000'000, -15},
638 Number{0},
639 __LINE__,
640 },
641 {
642 Number{1'000'000'000'000'000, -15},
643 Number{1'000'000'000'000'001, -15},
644 Number{-1'000'000'000'000'000, -30},
645 __LINE__,
646 },
647 {
648 Number{1'000'000'000'000'001, -15},
649 Number{1'000'000'000'000'000, -15},
650 Number{1'000'000'000'000'000, -30},
651 __LINE__,
652 },
653 });
654 auto const cLargeAll = std::to_array<Case>(
655 // Note that items with extremely large mantissas need to be
656 // calculated, because otherwise they overflow uint64. Items from C
657 // with larger mantissa
658 {
659 {
660 Number{1'000'000'000'000'000, -15},
661 Number{6'555'555'555'555'555, -29},
662 Number{false, 9'999'999'999'999'344'444ULL, -19, Number::Normalized{}},
663 __LINE__,
664 },
665 {
666 Number{6'555'555'555'555'555, -29},
667 Number{1'000'000'000'000'000, -15},
668 Number{true, 9'999'999'999'999'344'444ULL, -19, Number::Normalized{}},
669 __LINE__,
670 },
671 {
672 Number{1'000'000'000'000'000, -15},
673 Number{1'000'000'000'000'000, -15},
674 Number{0},
675 __LINE__,
676 },
677 {
678 Number{1'000'000'000'000'000, -15},
679 Number{1'000'000'000'000'001, -15},
680 Number{-1'000'000'000'000'000, -30},
681 __LINE__,
682 },
683 {
684 Number{1'000'000'000'000'001, -15},
685 Number{1'000'000'000'000'000, -15},
686 Number{1'000'000'000'000'000, -30},
687 __LINE__,
688 },
689 // Items from cSmall expanded for the larger mantissa
690 {
691 Number{1'000'000'000'000'000'000, -18},
692 Number{6'555'555'555'555'555'555, -32},
693 Number{false, 9'999'999'999'999'344'444ULL, -19, Number::Normalized{}},
694 __LINE__,
695 },
696 {
697 Number{6'555'555'555'555'555'555, -32},
698 Number{1'000'000'000'000'000'000, -18},
699 Number{true, 9'999'999'999'999'344'444ULL, -19, Number::Normalized{}},
700 __LINE__,
701 },
702 {
703 Number{1'000'000'000'000'000'000, -18},
704 Number{1'000'000'000'000'000'000, -18},
705 Number{0},
706 __LINE__,
707 },
708 {
709 Number{1'000'000'000'000'000'000, -18},
710 Number{1'000'000'000'000'000'001, -18},
711 Number{-1'000'000'000'000'000'000, -36},
712 __LINE__,
713 },
714 {
715 Number{1'000'000'000'000'000'001, -18},
716 Number{1'000'000'000'000'000'000, -18},
717 Number{1'000'000'000'000'000'000, -36},
718 __LINE__,
719 },
720 {Number{Number::kMaxRep}, Number{6, -1}, Number{Number::kMaxRep - 1}, __LINE__},
721 });
722 // Note that items with extremely large mantissas need to be
723 // calculated, because otherwise they overflow uint64. Items from C
724 // with larger mantissa
725 auto const cLarge = std::to_array<Case>({
726 // Anything larger than kMaxRep rounds up
727 {
728 Number{false, Number::kMaxRep + 1, 0, Number::Normalized{}},
729 Number{1, 0},
730 Number{(Number::kMaxRep / 10) + 1, 1},
731 __LINE__,
732 },
733 {
734 Number{false, Number::kMaxRep + 1, 0, Number::Normalized{}},
735 Number{3, 0},
737 __LINE__,
738 },
739 {
740 Number{false, Number::kMaxRep + 2, 0, Number::Normalized{}},
741 Number{1, 0},
742 Number{(Number::kMaxRep / 10) + 1, 1},
743 __LINE__,
744 },
745 {
746 Number{false, Number::kMaxRep + 2, 0, Number::Normalized{}},
747 Number{3, 0},
749 __LINE__,
750 },
751 {power(2, 63), Number{3, 0}, Number{Number::kMaxRep}, __LINE__},
752 });
753 auto const cLarge330 = std::to_array<Case>({
754 // kMaxRep + 1 is below the half-way point, so it rounds down to kMaxRep when the Number
755 // is created.
756 {
757 Number{false, Number::kMaxRep + 1, 0, Number::Normalized{}},
758 Number{1, 0},
760 __LINE__,
761 },
762 {
763 Number{false, Number::kMaxRep + 1, 0, Number::Normalized{}},
764 Number{3, 0},
766 __LINE__,
767 },
768 // kMaxRepUp -1 is above the half-way point, so it rounds up to kMaxRepUp when the
769 // Number is created. Subtracting 1 from that rounds up again. A little non-intuitive.
770 {
772 Number{1, 0},
773 Number{(Number::kMaxRep / 10) + 1, 1},
774 __LINE__,
775 },
776 // Subtracting 3 gets back down to kMaxRep
777 {
779 Number{3, 0},
781 __LINE__,
782 },
783 // 2^63 is the same as kMaxRep+1
784 {power(2, 63), Number{3, 0}, Number{Number::kMaxRep - 3}, __LINE__},
785 });
786 auto const test = [](auto const& c) {
787 for (auto const& [x, y, z, line] : c)
788 {
789 auto const result = x - y;
791 ss << x << " - " << y << " = " << result << ". Expected: " << z;
792 EXPECT_EQ(result, z) << ss.str() << " Line: " << line;
793 }
794 };
795 switch (scale)
796 {
798 test(cSmall);
799 break;
802 test(cLargeAll);
803 test(cLarge);
804 break;
806 test(cLargeAll);
807 test(cLarge330);
808 break;
809 default:
810 ADD_FAILURE();
811 break;
812 }
813 }
814}
815
816TEST(NumberTest, mul)
817{
818 for (auto const mantissaScale : MantissaRange::getAllScales())
819 {
820 NumberMantissaScaleGuard const sg(mantissaScale);
821
822 auto const scale = Number::getMantissaScale();
823
825 auto test = [](auto const& c) {
826 for (auto const& [x, y, z] : c)
827 {
828 auto const result = x * y;
830 ss << x << " * " << y << " = " << result << ". Expected: " << z;
831 EXPECT_EQ(result, z) << ss.str();
832 }
833 };
834 auto const tests = [&](auto const& cSmall, auto const& cLarge) {
836 {
837 test(cSmall);
838 }
839 else
840 {
841 test(cLarge);
842 }
843 };
844 auto const maxMantissa = Number::maxMantissa();
845
847 {
848 auto const cSmall = std::to_array<Case>({
849 {Number{7}, Number{8}, Number{56}},
850 {
851 Number{1414213562373095, -15},
852 Number{1414213562373095, -15},
853 Number{2000000000000000, -15},
854 },
855 {
856 Number{-1414213562373095, -15},
857 Number{1414213562373095, -15},
858 Number{-2000000000000000, -15},
859 },
860 {
861 Number{-1414213562373095, -15},
862 Number{-1414213562373095, -15},
863 Number{2000000000000000, -15},
864 },
865 {
866 Number{3214285714285706, -15},
867 Number{3111111111111119, -15},
868 Number{1000000000000000, -14},
869 },
870 {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}},
871 // Maximum mantissa range
872 {
873 Number{9'999'999'999'999'999, 0},
874 Number{9'999'999'999'999'999, 0},
875 Number{9'999'999'999'999'998, 16},
876 },
877 });
878 auto const cLarge = std::to_array<Case>({
879 // Note that items with extremely large mantissas need to be
880 // calculated, because otherwise they overflow uint64. Items
881 // from C with larger mantissa
882 {Number{7}, Number{8}, Number{56}},
883 {
884 Number{1414213562373095, -15},
885 Number{1414213562373095, -15},
886 Number{1999999999999999862, -18},
887 },
888 {
889 Number{-1414213562373095, -15},
890 Number{1414213562373095, -15},
891 Number{-1999999999999999862, -18},
892 },
893 {
894 Number{-1414213562373095, -15},
895 Number{-1414213562373095, -15},
896 Number{1999999999999999862, -18},
897 },
898 {
899 Number{3214285714285706, -15},
900 Number{3111111111111119, -15},
901 Number{false, 9'999'999'999'999'999'579ULL, -18, Number::Normalized{}},
902 },
903 {
904 Number{1000000000000000000, -32768},
905 Number{1000000000000000000, -32768},
906 Number{0},
907 },
908 // Items from cSmall expanded for the larger mantissa,
909 // except duplicates. Sadly, it looks like sqrt(2)^2 != 2
910 // with higher precision
911 {
912 Number{1414213562373095049, -18},
913 Number{1414213562373095049, -18},
914 Number{2000000000000000001, -18},
915 },
916 {
917 Number{-1414213562373095048, -18},
918 Number{1414213562373095048, -18},
919 Number{-1999999999999999998, -18},
920 },
921 {
922 Number{-1414213562373095048, -18},
923 Number{-1414213562373095049, -18},
924 Number{1999999999999999999, -18},
925 },
926 {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{10, 0}},
927 // Maximum mantissa range - rounds up to 1e19
928 {
929 Number{false, maxMantissa, 0, Number::Normalized{}},
930 Number{false, maxMantissa, 0, Number::Normalized{}},
931 Number{1, 38},
932 },
933 // Maximum int64 range
934 {
937 Number{85'070'591'730'234'615'85, 19},
938 },
939 });
940 tests(cSmall, cLarge);
941 }
943 {
944 auto const cSmall = std::to_array<Case>({
945 {Number{7}, Number{8}, Number{56}},
946 {
947 Number{1414213562373095, -15},
948 Number{1414213562373095, -15},
949 Number{1999999999999999, -15},
950 },
951 {
952 Number{-1414213562373095, -15},
953 Number{1414213562373095, -15},
954 Number{-1999999999999999, -15},
955 },
956 {
957 Number{-1414213562373095, -15},
958 Number{-1414213562373095, -15},
959 Number{1999999999999999, -15},
960 },
961 {
962 Number{3214285714285706, -15},
963 Number{3111111111111119, -15},
964 Number{9999999999999999, -15},
965 },
966 {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}},
967 });
968 auto const cLarge = std::to_array<Case>(
969 // Note that items with extremely large mantissas need to be
970 // calculated, because otherwise they overflow uint64. Items
971 // from C with larger mantissa
972 {
973 {Number{7}, Number{8}, Number{56}},
974 {
975 Number{1414213562373095, -15},
976 Number{1414213562373095, -15},
977 Number{1999999999999999861, -18},
978 },
979 {
980 Number{-1414213562373095, -15},
981 Number{1414213562373095, -15},
982 Number{-1999999999999999861, -18},
983 },
984 {
985 Number{-1414213562373095, -15},
986 Number{-1414213562373095, -15},
987 Number{1999999999999999861, -18},
988 },
989 {
990 Number{3214285714285706, -15},
991 Number{3111111111111119, -15},
992 Number{false, 9999999999999999579ULL, -18, Number::Normalized{}},
993 },
994 {
995 Number{1000000000000000000, -32768},
996 Number{1000000000000000000, -32768},
997 Number{0},
998 },
999 // Items from cSmall expanded for the larger mantissa,
1000 // except duplicates. Sadly, it looks like sqrt(2)^2 != 2
1001 // with higher precision
1002 {
1003 Number{1414213562373095049, -18},
1004 Number{1414213562373095049, -18},
1005 Number{2, 0},
1006 },
1007 {
1008 Number{-1414213562373095048, -18},
1009 Number{1414213562373095048, -18},
1010 Number{-1999999999999999997, -18},
1011 },
1012 {
1013 Number{-1414213562373095048, -18},
1014 Number{-1414213562373095049, -18},
1015 Number{1999999999999999999, -18},
1016 },
1017 {
1018 Number{3214285714285714278, -18},
1019 Number{3111111111111111119, -18},
1020 Number{10, 0},
1021 },
1022 // Maximum mantissa range - rounds down to maxMantissa/10e1
1023 // 99'999'999'999'999'999'800'000'000'000'000'000'100
1024 {
1025 Number{false, maxMantissa, 0, Number::Normalized{}},
1026 Number{false, maxMantissa, 0, Number::Normalized{}},
1027 Number{false, (maxMantissa / 10) - 1, 20, Number::Normalized{}},
1028 },
1029 // Maximum int64 range
1030 // 85'070'591'730'234'615'847'396'907'784'232'501'249
1031 {
1034 Number{85'070'591'730'234'615'84, 19},
1035 },
1036 });
1037 tests(cSmall, cLarge);
1038 }
1040 {
1041 auto const cSmall = std::to_array<Case>({
1042 {Number{7}, Number{8}, Number{56}},
1043 {
1044 Number{1414213562373095, -15},
1045 Number{1414213562373095, -15},
1046 Number{1999999999999999, -15},
1047 },
1048 {
1049 Number{-1414213562373095, -15},
1050 Number{1414213562373095, -15},
1051 Number{-2000000000000000, -15},
1052 },
1053 {
1054 Number{-1414213562373095, -15},
1055 Number{-1414213562373095, -15},
1056 Number{1999999999999999, -15},
1057 },
1058 {
1059 Number{3214285714285706, -15},
1060 Number{3111111111111119, -15},
1061 Number{9999999999999999, -15},
1062 },
1063 {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}},
1064 });
1065 auto const cLarge = std::to_array<Case>(
1066 // Note that items with extremely large mantissas need to be
1067 // calculated, because otherwise they overflow uint64. Items
1068 // from C with larger mantissa
1069 {
1070 {Number{7}, Number{8}, Number{56}},
1071 {
1072 Number{1414213562373095, -15},
1073 Number{1414213562373095, -15},
1074 Number{1999999999999999861, -18},
1075 },
1076 {
1077 Number{-1414213562373095, -15},
1078 Number{1414213562373095, -15},
1079 Number{-1999999999999999862, -18},
1080 },
1081 {
1082 Number{-1414213562373095, -15},
1083 Number{-1414213562373095, -15},
1084 Number{1999999999999999861, -18},
1085 },
1086 {
1087 Number{3214285714285706, -15},
1088 Number{3111111111111119, -15},
1089 Number{false, 9'999'999'999'999'999'579ULL, -18, Number::Normalized{}},
1090 },
1091 {
1092 Number{1000000000000000000, -32768},
1093 Number{1000000000000000000, -32768},
1094 Number{0},
1095 },
1096 // Items from cSmall expanded for the larger mantissa,
1097 // except duplicates. Sadly, it looks like sqrt(2)^2 != 2
1098 // with higher precision
1099 {
1100 Number{1414213562373095049, -18},
1101 Number{1414213562373095049, -18},
1102 Number{2, 0},
1103 },
1104 {
1105 Number{-1414213562373095048, -18},
1106 Number{1414213562373095048, -18},
1107 Number{-1999999999999999998, -18},
1108 },
1109 {
1110 Number{-1414213562373095048, -18},
1111 Number{-1414213562373095049, -18},
1112 Number{1999999999999999999, -18},
1113 },
1114 {
1115 Number{3214285714285714278, -18},
1116 Number{3111111111111111119, -18},
1117 Number{10, 0},
1118 },
1119 // Maximum mantissa range - rounds down to maxMantissa/10e1
1120 // 99'999'999'999'999'999'800'000'000'000'000'000'100
1121 {
1122 Number{false, maxMantissa, 0, Number::Normalized{}},
1123 Number{false, maxMantissa, 0, Number::Normalized{}},
1124 Number{false, (maxMantissa / 10) - 1, 20, Number::Normalized{}},
1125 },
1126 // Maximum int64 range
1127 // 85'070'591'730'234'615'847'396'907'784'232'501'249
1128 {
1131 Number{85'070'591'730'234'615'84, 19},
1132 },
1133 });
1134 tests(cSmall, cLarge);
1135 }
1137 {
1138 auto const cSmall = std::to_array<Case>({
1139 {Number{7}, Number{8}, Number{56}},
1140 {
1141 Number{1414213562373095, -15},
1142 Number{1414213562373095, -15},
1143 Number{2000000000000000, -15},
1144 },
1145 {
1146 Number{-1414213562373095, -15},
1147 Number{1414213562373095, -15},
1148 Number{-1999999999999999, -15},
1149 },
1150 {
1151 Number{-1414213562373095, -15},
1152 Number{-1414213562373095, -15},
1153 Number{2000000000000000, -15},
1154 },
1155 {
1156 Number{3214285714285706, -15},
1157 Number{3111111111111119, -15},
1158 Number{1000000000000000, -14},
1159 },
1160 {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}},
1161 });
1162 auto const cLarge = std::to_array<Case>(
1163 // Note that items with extremely large mantissas need to be
1164 // calculated, because otherwise they overflow uint64. Items
1165 // from C with larger mantissa
1166 {
1167 {Number{7}, Number{8}, Number{56}},
1168 {
1169 Number{1414213562373095, -15},
1170 Number{1414213562373095, -15},
1171 Number{1999999999999999862, -18},
1172 },
1173 {
1174 Number{-1414213562373095, -15},
1175 Number{1414213562373095, -15},
1176 Number{-1999999999999999861, -18},
1177 },
1178 {
1179 Number{-1414213562373095, -15},
1180 Number{-1414213562373095, -15},
1181 Number{1999999999999999862, -18},
1182 },
1183 {
1184 Number{3214285714285706, -15},
1185 Number{3111111111111119, -15},
1186 Number{999999999999999958, -17},
1187 },
1188 {
1189 Number{1000000000000000000, -32768},
1190 Number{1000000000000000000, -32768},
1191 Number{0},
1192 },
1193 // Items from cSmall expanded for the larger mantissa,
1194 // except duplicates. Sadly, it looks like sqrt(2)^2 != 2
1195 // with higher precision
1196 {
1197 Number{1414213562373095049, -18},
1198 Number{1414213562373095049, -18},
1199 Number{2000000000000000001, -18},
1200 },
1201 {
1202 Number{-1414213562373095048, -18},
1203 Number{1414213562373095048, -18},
1204 Number{-1999999999999999997, -18},
1205 },
1206 {
1207 Number{-1414213562373095048, -18},
1208 Number{-1414213562373095049, -18},
1209 Number{2, 0},
1210 },
1211 {
1212 Number{3214285714285714278, -18},
1213 Number{3111111111111111119, -18},
1214 Number{1000000000000000001, -17},
1215 },
1216 // Maximum mantissa range - rounds up to minMantissa*10
1217 // 1e19*1e19=1e38
1218 {
1219 Number{false, maxMantissa, 0, Number::Normalized{}},
1220 Number{false, maxMantissa, 0, Number::Normalized{}},
1221 Number{1, 38},
1222 },
1223 // Maximum int64 range
1224 // 85'070'591'730'234'615'847'396'907'784'232'501'249
1225 {
1228 Number{85'070'591'730'234'615'85, 19},
1229 },
1230 });
1231 tests(cSmall, cLarge);
1232 }
1233 {
1234 bool caught = false;
1235 try
1236 {
1237 Number{false, maxMantissa, 32768, Number::Normalized{}} *
1238 Number{false, Number::minMantissa() * 5, 32767, Number::Normalized{}};
1239 }
1240 catch (std::overflow_error const&)
1241 {
1242 caught = true;
1243 }
1244 EXPECT_TRUE(caught);
1245 }
1246 }
1247}
1248
1249TEST(NumberTest, div)
1250{
1251 for (auto const mantissaScale : MantissaRange::getAllScales())
1252 {
1253 NumberMantissaScaleGuard const sg(mantissaScale);
1254
1255 auto const scale = Number::getMantissaScale();
1256
1258 auto test = [](auto const& c) {
1259 for (auto const& [x, y, z] : c)
1260 {
1261 auto const result = x / y;
1263 ss << x << " / " << y << " = " << result << ". Expected: " << z;
1264 EXPECT_EQ(result, z) << ss.str();
1265 }
1266 };
1267 auto const maxMantissa = Number::maxMantissa();
1268 auto const tests = [&](auto const& cSmall, auto const& cLarge) {
1270 {
1271 test(cSmall);
1272 }
1273 else
1274 {
1275 test(cLarge);
1276 }
1277 };
1279 {
1280 auto const cSmall = std::to_array<Case>({
1281 {Number{1}, Number{2}, Number{5, -1}},
1282 {Number{1}, Number{10}, Number{1, -1}},
1283 {Number{1}, Number{-10}, Number{-1, -1}},
1284 {Number{0}, Number{100}, Number{0}},
1285 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1286 {
1287 Number{9'999'999'999'999'999},
1288 Number{1'000'000'000'000'000},
1289 Number{9'999'999'999'999'999, -15},
1290 },
1291 {Number{2}, Number{3}, Number{6'666'666'666'666'667, -16}},
1292 {Number{-2}, Number{3}, Number{-6'666'666'666'666'667, -16}},
1293 {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}},
1294 });
1295 auto const cLarge = std::to_array<Case>(
1296 // Note that items with extremely large mantissas need to be
1297 // calculated, because otherwise they overflow uint64. Items
1298 // from C with larger mantissa
1299 {
1300 {Number{1}, Number{2}, Number{5, -1}},
1301 {Number{1}, Number{10}, Number{1, -1}},
1302 {Number{1}, Number{-10}, Number{-1, -1}},
1303 {Number{0}, Number{100}, Number{0}},
1304 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1305 {
1306 Number{9'999'999'999'999'999},
1307 Number{1'000'000'000'000'000},
1308 Number{9'999'999'999'999'999, -15},
1309 },
1310 {Number{2}, Number{3}, Number{6'666'666'666'666'666'667, -19}},
1311 {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'667, -19}},
1312 {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}},
1313 // Items from cSmall expanded for the larger mantissa, except
1314 // duplicates.
1315 {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}},
1316 {
1317 Number{false, maxMantissa, 0, Number::Normalized{}},
1318 Number{1'000'000'000'000'000'000},
1319 Number{false, maxMantissa, -18, Number::Normalized{}},
1320 },
1321 });
1322 tests(cSmall, cLarge);
1323 }
1325 {
1326 auto const cSmall = std::to_array<Case>({
1327 {Number{1}, Number{2}, Number{5, -1}},
1328 {Number{1}, Number{10}, Number{1, -1}},
1329 {Number{1}, Number{-10}, Number{-1, -1}},
1330 {Number{0}, Number{100}, Number{0}},
1331 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1332 {
1333 Number{9'999'999'999'999'999},
1334 Number{1'000'000'000'000'000},
1335 Number{9'999'999'999'999'999, -15},
1336 },
1337 {Number{2}, Number{3}, Number{6'666'666'666'666'666, -16}},
1338 {Number{-2}, Number{3}, Number{-6'666'666'666'666'666, -16}},
1339 {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}},
1340 });
1341 auto const cLarge = std::to_array<Case>(
1342 // Note that items with extremely large mantissas need to be
1343 // calculated, because otherwise they overflow uint64. Items
1344 // from C with larger mantissa
1345 {
1346 {Number{1}, Number{2}, Number{5, -1}},
1347 {Number{1}, Number{10}, Number{1, -1}},
1348 {Number{1}, Number{-10}, Number{-1, -1}},
1349 {Number{0}, Number{100}, Number{0}},
1350 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1351 {
1352 Number{9'999'999'999'999'999},
1353 Number{1'000'000'000'000'000},
1354 Number{9'999'999'999'999'999, -15},
1355 },
1356 {Number{2}, Number{3}, Number{6'666'666'666'666'666'666, -19}},
1357 {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'666, -19}},
1358 {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}},
1359 // Items from cSmall expanded for the larger mantissa, except
1360 // duplicates.
1361 {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}},
1362 {
1363 Number{false, maxMantissa, 0, Number::Normalized{}},
1364 Number{1'000'000'000'000'000'000},
1365 Number{false, maxMantissa, -18, Number::Normalized{}},
1366 },
1367 });
1368 tests(cSmall, cLarge);
1369 }
1371 {
1372 auto const cSmall = std::to_array<Case>({
1373 {Number{1}, Number{2}, Number{5, -1}},
1374 {Number{1}, Number{10}, Number{1, -1}},
1375 {Number{1}, Number{-10}, Number{-1, -1}},
1376 {Number{0}, Number{100}, Number{0}},
1377 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1378 {
1379 Number{9'999'999'999'999'999},
1380 Number{1'000'000'000'000'000},
1381 Number{9'999'999'999'999'999, -15},
1382 },
1383 {Number{2}, Number{3}, Number{6'666'666'666'666'666, -16}},
1384 {Number{-2}, Number{3}, Number{-6'666'666'666'666'667, -16}},
1385 {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}},
1386 });
1387 auto const cLarge = std::to_array<Case>(
1388 // Note that items with extremely large mantissas need to be
1389 // calculated, because otherwise they overflow uint64. Items
1390 // from C with larger mantissa
1391 {
1392 {Number{1}, Number{2}, Number{5, -1}},
1393 {Number{1}, Number{10}, Number{1, -1}},
1394 {Number{1}, Number{-10}, Number{-1, -1}},
1395 {Number{0}, Number{100}, Number{0}},
1396 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1397 {
1398 Number{9'999'999'999'999'999},
1399 Number{1'000'000'000'000'000},
1400 Number{9'999'999'999'999'999, -15},
1401 },
1402 {Number{2}, Number{3}, Number{6'666'666'666'666'666'666, -19}},
1403 {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'667, -19}},
1404 {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}},
1405 // Items from cSmall expanded for the larger mantissa, except
1406 // duplicates.
1407 {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}},
1408 {
1409 Number{false, maxMantissa, 0, Number::Normalized{}},
1410 Number{1'000'000'000'000'000'000},
1411 Number{false, maxMantissa, -18, Number::Normalized{}},
1412 },
1413 });
1414 tests(cSmall, cLarge);
1415 }
1417 {
1418 auto const cSmall = std::to_array<Case>({
1419 {Number{1}, Number{2}, Number{5, -1}},
1420 {Number{1}, Number{10}, Number{1, -1}},
1421 {Number{1}, Number{-10}, Number{-1, -1}},
1422 {Number{0}, Number{100}, Number{0}},
1423 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1424 {
1425 Number{9'999'999'999'999'999},
1426 Number{1'000'000'000'000'000},
1427 Number{9'999'999'999'999'999, -15},
1428 },
1429 {Number{2}, Number{3}, Number{6'666'666'666'666'667, -16}},
1430 {Number{-2}, Number{3}, Number{-6'666'666'666'666'666, -16}},
1431 {Number{1}, Number{7}, Number{1'428'571'428'571'429, -16}},
1432 });
1433 auto const cLarge = std::to_array<Case>(
1434 // Note that items with extremely large mantissas need to be
1435 // calculated, because otherwise they overflow uint64. Items
1436 // from C with larger mantissa
1437 {
1438 {Number{1}, Number{2}, Number{5, -1}},
1439 {Number{1}, Number{10}, Number{1, -1}},
1440 {Number{1}, Number{-10}, Number{-1, -1}},
1441 {Number{0}, Number{100}, Number{0}},
1442 {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}},
1443 {
1444 Number{9'999'999'999'999'999},
1445 Number{1'000'000'000'000'000},
1446 Number{9'999'999'999'999'999, -15},
1447 },
1448 {Number{2}, Number{3}, Number{6'666'666'666'666'666'667, -19}},
1449 {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'666, -19}},
1450 {Number{1}, Number{7}, Number{1'428'571'428'571'428'572, -19}},
1451 // Items from cSmall expanded for the larger mantissa, except
1452 // duplicates.
1453 {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}},
1454 {
1455 Number{false, maxMantissa, 0, Number::Normalized{}},
1456 Number{1'000'000'000'000'000'000},
1457 Number{false, maxMantissa, -18, Number::Normalized{}},
1458 },
1459 });
1460 tests(cSmall, cLarge);
1461 }
1462 bool caught = false;
1463 try
1464 {
1465 Number{1000000000000000, -15} / Number{0};
1466 }
1467 catch (std::overflow_error const&)
1468 {
1469 caught = true;
1470 }
1471 EXPECT_TRUE(caught);
1472 }
1473}
1474
1475TEST(NumberTest, root)
1476{
1477 for (auto const mantissaScale : MantissaRange::getAllScales())
1478 {
1479 NumberMantissaScaleGuard const sg(mantissaScale);
1480
1482 auto const test = [](auto const& c) {
1483 for (auto const& [x, y, z] : c)
1484 {
1485 auto const result = root(x, y);
1487 ss << "root(" << x << ", " << y << ") = " << result << ". Expected: " << z;
1488 EXPECT_EQ(result, z) << ss.str();
1489 }
1490 };
1491 auto const cSmall = std::to_array<Case>({
1492 {Number{2}, 2, Number{1414213562373095049, -18}},
1493 {Number{2'000'000}, 2, Number{1414213562373095049, -15}},
1494 {Number{2, -30}, 2, Number{1414213562373095049, -33}},
1495 {Number{-27}, 3, Number{-3}},
1496 {Number{1}, 5, Number{1}},
1497 {Number{-1}, 0, Number{1}},
1498 {Number{5, -1}, 0, Number{0}},
1499 {Number{0}, 5, Number{0}},
1500 {Number{5625, -4}, 2, Number{75, -2}},
1501 });
1502 auto const cLarge = std::to_array<Case>({
1503 {
1504 Number{false, Number::maxMantissa() - 9, -1, Number::Normalized{}},
1505 2,
1506 Number{false, 999'999'999'999'999'999, -9, Number::Normalized{}},
1507 },
1508 {
1509 Number{false, Number::maxMantissa() - 9, 0, Number::Normalized{}},
1510 2,
1511 Number{false, 3'162'277'660'168'379'330, -9, Number::Normalized{}},
1512 },
1513 {
1515 2,
1516 Number{false, 3'037'000'499'976049692, -9, Number::Normalized{}},
1517 },
1518 {
1520 4,
1521 Number{false, 55'108'98747006743627, -14, Number::Normalized{}},
1522 },
1523 });
1524 test(cSmall);
1526 {
1528 test(cLarge);
1529 }
1530 bool caught = false;
1531 try
1532 {
1533 (void)root(Number{-2}, 0);
1534 }
1535 catch (std::overflow_error const&)
1536 {
1537 caught = true;
1538 }
1539 EXPECT_TRUE(caught);
1540 caught = false;
1541 try
1542 {
1543 (void)root(Number{-2}, 4);
1544 }
1545 catch (std::overflow_error const&)
1546 {
1547 caught = true;
1548 }
1549 EXPECT_TRUE(caught);
1550 }
1551}
1552
1553TEST(NumberTest, root2)
1554{
1555 for (auto const mantissaScale : MantissaRange::getAllScales())
1556 {
1557 NumberMantissaScaleGuard const sg(mantissaScale);
1558
1559 auto const test = [](auto const& c) {
1560 for (auto const& x : c)
1561 {
1562 auto const expected = root(x, 2);
1563 auto const result = root2(x);
1565 ss << "root2(" << x << ") = " << result << ". Expected: " << expected;
1566 EXPECT_EQ(result, expected) << ss.str();
1567 }
1568 };
1569
1570 auto const cSmall = std::to_array<Number>({
1571 Number{2},
1572 Number{2'000'000},
1573 Number{2, -30},
1574 Number{27},
1575 Number{1},
1576 Number{5, -1},
1577 Number{0},
1578 Number{5625, -4},
1580 });
1581 test(cSmall);
1582 bool caught = false;
1583 try
1584 {
1585 (void)root2(Number{-2});
1586 }
1587 catch (std::overflow_error const&)
1588 {
1589 caught = true;
1590 }
1591 EXPECT_TRUE(caught);
1592 }
1593}
1594
1595TEST(NumberTest, power1)
1596{
1597 for (auto const mantissaScale : MantissaRange::getAllScales())
1598 {
1599 NumberMantissaScaleGuard const sg(mantissaScale);
1600
1602 Case const c[]{
1603 {Number{64}, 0, Number{1}},
1604 {Number{64}, 1, Number{64}},
1605 {Number{64}, 2, Number{4096}},
1606 {Number{-64}, 2, Number{4096}},
1607 {Number{64}, 3, Number{262144}},
1608 {Number{-64}, 3, Number{-262144}},
1609 {Number{64}, 11, Number{false, 7378697629483820646ULL, 1, Number::Normalized{}}},
1610 {Number{-64}, 11, Number{true, 7378697629483820646ULL, 1, Number::Normalized{}}},
1611 };
1612 for (auto const& [x, y, z] : c)
1613 EXPECT_EQ(power(x, y), z);
1614 }
1615}
1616
1617TEST(NumberTest, power2)
1618{
1619 for (auto const mantissaScale : MantissaRange::getAllScales())
1620 {
1621 NumberMantissaScaleGuard const sg(mantissaScale);
1622
1624 Case const c[]{
1625 {Number{1}, 3, 7, Number{1}},
1626 {Number{-1}, 1, 0, Number{1}},
1627 {Number{-1, -1}, 1, 0, Number{0}},
1628 {Number{16}, 0, 5, Number{1}},
1629 {Number{34}, 3, 3, Number{34}},
1630 {Number{4}, 3, 2, Number{8}},
1631 };
1632 for (auto const& [x, n, d, z] : c)
1633 EXPECT_EQ(power(x, n, d), z);
1634 bool caught = false;
1635 try
1636 {
1637 (void)power(Number{7}, 0, 0);
1638 }
1639 catch (std::overflow_error const&)
1640 {
1641 caught = true;
1642 }
1643 EXPECT_TRUE(caught);
1644 caught = false;
1645 try
1646 {
1647 (void)power(Number{7}, 1, 0);
1648 }
1649 catch (std::overflow_error const&)
1650 {
1651 caught = true;
1652 }
1653 EXPECT_TRUE(caught);
1654 caught = false;
1655 try
1656 {
1657 (void)power(Number{-1, -1}, 3, 2);
1658 }
1659 catch (std::overflow_error const&)
1660 {
1661 caught = true;
1662 }
1663 EXPECT_TRUE(caught);
1664 }
1665}
1666
1667TEST(NumberTest, conversions)
1668{
1669 for (auto const mantissaScale : MantissaRange::getAllScales())
1670 {
1671 NumberMantissaScaleGuard const sg(mantissaScale);
1672
1673 IOUAmount const x{5, 6};
1674 Number const y = x;
1675 EXPECT_EQ(y, (Number{5, 6}));
1676 IOUAmount const z{y};
1677 EXPECT_EQ(x, z);
1678 XRPAmount const xrp{500};
1679 STAmount const st = xrp;
1680 Number const n = st;
1681 EXPECT_EQ(XRPAmount{n}, xrp);
1682 IOUAmount const x0{0, 0};
1683 Number const y0 = x0;
1684 EXPECT_EQ(y0, Number{0});
1685 IOUAmount const z0{y0};
1686 EXPECT_EQ(x0, z0);
1687 XRPAmount const xrp0{0};
1688 Number const n0 = xrp0;
1689 EXPECT_EQ(n0, Number{0});
1690 XRPAmount const xrp1{n0}; // NOLINT misc-confusable-identifiers
1691 EXPECT_EQ(xrp1, xrp0);
1692 }
1693}
1694
1695TEST(NumberTest, to_integer)
1696{
1697 for (auto const mantissaScale : MantissaRange::getAllScales())
1698 {
1699 NumberMantissaScaleGuard const sg(mantissaScale);
1700
1703 {
1704 Case const c[]{
1705 {Number{0}, 0},
1706 {Number{1}, 1},
1707 {Number{2}, 2},
1708 {Number{3}, 3},
1709 {Number{-1}, -1},
1710 {Number{-2}, -2},
1711 {Number{-3}, -3},
1712 {Number{10}, 10},
1713 {Number{99}, 99},
1714 {Number{1155}, 1155},
1715 {Number{9'999'999'999'999'999, 0}, 9'999'999'999'999'999},
1716 {Number{9'999'999'999'999'999, 1}, 99'999'999'999'999'990},
1717 {Number{9'999'999'999'999'999, 2}, 999'999'999'999'999'900},
1718 {Number{-9'999'999'999'999'999, 2}, -999'999'999'999'999'900},
1719 {Number{15, -1}, 2},
1720 {Number{14, -1}, 1},
1721 {Number{16, -1}, 2},
1722 {Number{25, -1}, 2},
1723 {Number{6, -1}, 1},
1724 {Number{5, -1}, 0},
1725 {Number{4, -1}, 0},
1726 {Number{-15, -1}, -2},
1727 {Number{-14, -1}, -1},
1728 {Number{-16, -1}, -2},
1729 {Number{-25, -1}, -2},
1730 {Number{-6, -1}, -1},
1731 {Number{-5, -1}, 0},
1732 {Number{-4, -1}, 0},
1733 };
1734 for (auto const& [x, y] : c)
1735 {
1736 auto j = static_cast<std::int64_t>(x);
1737 EXPECT_EQ(j, y);
1738 }
1739 }
1741 EXPECT_EQ(prevMode, Number::RoundingMode::ToNearest);
1742 {
1743 Case const c[]{
1744 {Number{0}, 0},
1745 {Number{1}, 1},
1746 {Number{2}, 2},
1747 {Number{3}, 3},
1748 {Number{-1}, -1},
1749 {Number{-2}, -2},
1750 {Number{-3}, -3},
1751 {Number{10}, 10},
1752 {Number{99}, 99},
1753 {Number{1155}, 1155},
1754 {Number{9'999'999'999'999'999, 0}, 9'999'999'999'999'999},
1755 {Number{9'999'999'999'999'999, 1}, 99'999'999'999'999'990},
1756 {Number{9'999'999'999'999'999, 2}, 999'999'999'999'999'900},
1757 {Number{-9'999'999'999'999'999, 2}, -999'999'999'999'999'900},
1758 {Number{15, -1}, 1},
1759 {Number{14, -1}, 1},
1760 {Number{16, -1}, 1},
1761 {Number{25, -1}, 2},
1762 {Number{6, -1}, 0},
1763 {Number{5, -1}, 0},
1764 {Number{4, -1}, 0},
1765 {Number{-15, -1}, -1},
1766 {Number{-14, -1}, -1},
1767 {Number{-16, -1}, -1},
1768 {Number{-25, -1}, -2},
1769 {Number{-6, -1}, 0},
1770 {Number{-5, -1}, 0},
1771 {Number{-4, -1}, 0},
1772 };
1773 for (auto const& [x, y] : c)
1774 {
1775 auto j = static_cast<std::int64_t>(x);
1776 EXPECT_EQ(j, y);
1777 }
1778 }
1780 EXPECT_EQ(prevMode, Number::RoundingMode::TowardsZero);
1781 {
1782 Case const c[]{
1783 {Number{0}, 0},
1784 {Number{1}, 1},
1785 {Number{2}, 2},
1786 {Number{3}, 3},
1787 {Number{-1}, -1},
1788 {Number{-2}, -2},
1789 {Number{-3}, -3},
1790 {Number{10}, 10},
1791 {Number{99}, 99},
1792 {Number{1155}, 1155},
1793 {Number{9'999'999'999'999'999, 0}, 9'999'999'999'999'999},
1794 {Number{9'999'999'999'999'999, 1}, 99'999'999'999'999'990},
1795 {Number{9'999'999'999'999'999, 2}, 999'999'999'999'999'900},
1796 {Number{-9'999'999'999'999'999, 2}, -999'999'999'999'999'900},
1797 {Number{15, -1}, 1},
1798 {Number{14, -1}, 1},
1799 {Number{16, -1}, 1},
1800 {Number{25, -1}, 2},
1801 {Number{6, -1}, 0},
1802 {Number{5, -1}, 0},
1803 {Number{4, -1}, 0},
1804 {Number{-15, -1}, -2},
1805 {Number{-14, -1}, -2},
1806 {Number{-16, -1}, -2},
1807 {Number{-25, -1}, -3},
1808 {Number{-6, -1}, -1},
1809 {Number{-5, -1}, -1},
1810 {Number{-4, -1}, -1},
1811 };
1812 for (auto const& [x, y] : c)
1813 {
1814 auto j = static_cast<std::int64_t>(x);
1815 EXPECT_EQ(j, y);
1816 }
1817 }
1819 EXPECT_EQ(prevMode, Number::RoundingMode::Downward);
1820 {
1821 Case const c[]{
1822 {Number{0}, 0},
1823 {Number{1}, 1},
1824 {Number{2}, 2},
1825 {Number{3}, 3},
1826 {Number{-1}, -1},
1827 {Number{-2}, -2},
1828 {Number{-3}, -3},
1829 {Number{10}, 10},
1830 {Number{99}, 99},
1831 {Number{1155}, 1155},
1832 {Number{9'999'999'999'999'999, 0}, 9'999'999'999'999'999},
1833 {Number{9'999'999'999'999'999, 1}, 99'999'999'999'999'990},
1834 {Number{9'999'999'999'999'999, 2}, 999'999'999'999'999'900},
1835 {Number{-9'999'999'999'999'999, 2}, -999'999'999'999'999'900},
1836 {Number{15, -1}, 2},
1837 {Number{14, -1}, 2},
1838 {Number{16, -1}, 2},
1839 {Number{25, -1}, 3},
1840 {Number{6, -1}, 1},
1841 {Number{5, -1}, 1},
1842 {Number{4, -1}, 1},
1843 {Number{-15, -1}, -1},
1844 {Number{-14, -1}, -1},
1845 {Number{-16, -1}, -1},
1846 {Number{-25, -1}, -2},
1847 {Number{-6, -1}, 0},
1848 {Number{-5, -1}, 0},
1849 {Number{-4, -1}, 0},
1850 };
1851 for (auto const& [x, y] : c)
1852 {
1853 auto j = static_cast<std::int64_t>(x);
1854 EXPECT_EQ(j, y);
1855 }
1856 }
1857 bool caught = false;
1858 try
1859 {
1860 (void)static_cast<std::int64_t>(Number{9223372036854776, 3});
1861 }
1862 catch (std::overflow_error const&)
1863 {
1864 caught = true;
1865 }
1866 EXPECT_TRUE(caught);
1867 }
1868}
1869
1870TEST(NumberTest, squelch)
1871{
1872 for (auto const mantissaScale : MantissaRange::getAllScales())
1873 {
1874 NumberMantissaScaleGuard const sg(mantissaScale);
1875
1876 Number const limit{1, -6};
1877 EXPECT_EQ(squelch(Number{2, -6}, limit), (Number{2, -6}));
1878 EXPECT_EQ(squelch(Number{1, -6}, limit), (Number{1, -6}));
1879 EXPECT_EQ(squelch(Number{9, -7}, limit), Number{0});
1880 EXPECT_EQ(squelch(Number{-2, -6}, limit), (Number{-2, -6}));
1881 EXPECT_EQ(squelch(Number{-1, -6}, limit), (Number{-1, -6}));
1882 EXPECT_EQ(squelch(Number{-9, -7}, limit), Number{0});
1883 }
1884}
1885
1886TEST(NumberTest, to_string)
1887{
1888 for (auto const mantissaScale : MantissaRange::getAllScales())
1889 {
1890 NumberMantissaScaleGuard const sg(mantissaScale);
1891
1892 auto const scale = Number::getMantissaScale();
1893
1894 auto const test = [](Number const& n, std::string const& expected, int line) {
1895 auto const result = to_string(n);
1897 ss << "to_string(" << result << "). Expected: " << expected;
1898 EXPECT_EQ(result, expected) << ss.str() << " Line: " << line;
1899 };
1900
1901 test(Number(-2, 0), "-2", __LINE__);
1902 test(Number(0, 0), "0", __LINE__);
1903 test(Number(2, 0), "2", __LINE__);
1904 test(Number(25, -3), "0.025", __LINE__);
1905 test(Number(-25, -3), "-0.025", __LINE__);
1906 test(Number(25, 1), "250", __LINE__);
1907 test(Number(-25, 1), "-250", __LINE__);
1908 test(Number(2, 20), "2e20", __LINE__);
1909 test(Number(-2, -20), "-2e-20", __LINE__);
1910 // Test the edges
1911 // ((exponent < -(25)) || (exponent > -(5)))))
1912 // or ((exponent < -(28)) || (exponent > -(8)))))
1913 test(Number(2, -10), "0.0000000002", __LINE__);
1914 test(Number(2, -11), "2e-11", __LINE__);
1915
1916 test(Number(-2, 10), "-20000000000", __LINE__);
1917 test(Number(-2, 11), "-2e11", __LINE__);
1918 test(Number(-2, 11) - 1, "-200000000001", __LINE__);
1919
1920 switch (scale)
1921 {
1923
1924 test(Number::min(), "1e-32753", __LINE__);
1925 test(Number::max(), "9999999999999999e32768", __LINE__);
1926 test(Number::lowest(), "-9999999999999999e32768", __LINE__);
1927 {
1929
1930 auto const maxMantissa = Number::maxMantissa();
1931 EXPECT_EQ(maxMantissa, 9'999'999'999'999'999);
1932 test(
1933 Number{false, (maxMantissa * 1000) + 999, -3, Number::Normalized()},
1934 "9999999999999999",
1935 __LINE__);
1936 test(
1937 Number{true, (maxMantissa * 1000) + 999, -3, Number::Normalized()},
1938 "-9999999999999999",
1939 __LINE__);
1940
1941 test(
1943 "9223372036854775",
1944 __LINE__);
1945 test(
1947 "-9223372036854775",
1948 __LINE__);
1949
1950 test(
1952 "-9223372036854775e3",
1953 __LINE__);
1954 test(
1956 "9223372036854775e3",
1957 __LINE__);
1958 }
1959 break;
1960 default:
1961 // Test the edges
1962 // ((exponent < -(28)) || (exponent > -(8)))))
1963 test(Number::min(), "1e-32750", __LINE__);
1964 test(Number::max(), "9223372036854775807e32768", __LINE__);
1965 test(Number::lowest(), "-9223372036854775807e32768", __LINE__);
1966 {
1968
1969 auto const maxMantissa = Number::maxMantissa();
1970 EXPECT_EQ(maxMantissa, 9'999'999'999'999'999'999ULL);
1971 test(
1972 Number{false, maxMantissa, 0, Number::Normalized{}},
1973 "9999999999999999990",
1974 __LINE__);
1975 test(
1976 Number{true, maxMantissa, 0, Number::Normalized{}},
1977 "-9999999999999999990",
1978 __LINE__);
1979
1980 test(
1982 "9223372036854775807",
1983 __LINE__);
1984 test(
1986 "-9223372036854775807",
1987 __LINE__);
1988
1989 switch (scale)
1990 {
1992 // Because the absolute value of min() is larger than max(), it
1993 // will be rounded down toward max()
1994 test(
1996 "-9223372036854775807",
1997 __LINE__);
1998 test(
2000 "9223372036854775807",
2001 __LINE__);
2002 break;
2003 default:
2004 // Because the absolute value of min() is larger than max(), it
2005 // will be scaled down to fit under max(). Since we're
2006 // rounding towards zero, the 8 at the end is dropped.
2007 test(
2009 "-9223372036854775800",
2010 __LINE__);
2011 test(
2013 "9223372036854775800",
2014 __LINE__);
2015 break;
2016 }
2017 }
2018
2019 switch (scale)
2020 {
2022 // Rounding to nearest, since the mantissa is below the halfway point from
2023 // kMaxRep to kMaxRepUp, it will be rounded down to kMaxRep
2024 test(
2026 "9223372036854775807",
2027 __LINE__);
2028 test(
2030 "-9223372036854775807",
2031 __LINE__);
2032 break;
2033 default:
2034 // Rounding to nearest, since the mantissa is bigger than kMaxRep, the 8
2035 // will be dropped, and since that is bigger than 5, the result will be
2036 // rounded up from 0 to 1.
2037 test(
2039 "9223372036854775810",
2040 __LINE__);
2041 test(
2043 "-9223372036854775810",
2044 __LINE__);
2045 break;
2046 }
2047 // Rounding to nearest, will be rounded up to kMaxRepUp, but for different reasons
2048 // depending on the scale. If older than "Large", it rounds up for the same reason
2049 // "+1" rounds up. For "Large", since the mantissa is above the halfway point from
2050 // kMaxRep to kMaxRepUp, it will be rounded up to kMaxRepUp.
2051 test(
2053 "9223372036854775810",
2054 __LINE__);
2055 test(
2057 "-9223372036854775810",
2058 __LINE__);
2059 break;
2060 }
2061 }
2062}
2063
2064TEST(NumberTest, relationals)
2065{
2066 for (auto const mantissaScale : MantissaRange::getAllScales())
2067 {
2068 NumberMantissaScaleGuard const sg(mantissaScale);
2069
2070 {
2071 auto const test = [](auto const& nums) {
2072 EXPECT_TRUE(std::ranges::is_sorted(nums));
2073
2074 for (auto iter1 = nums.begin(); iter1 != nums.end(); ++iter1)
2075 {
2076 auto iter2 = iter1;
2077 for (++iter2; iter2 != nums.end(); ++iter2)
2078 {
2079 Number const& smaller = *iter1;
2080 Number const& larger = *iter2;
2082 ss << smaller << " < " << larger;
2083 auto const str = ss.str();
2084
2085 // The ==/!= operators use a completely different code path than <, etc.
2086 // This helps detect a breakage in one but not the other. It also helps
2087 // verify that the values are being ordered correctly.
2088 EXPECT_TRUE(smaller != larger) << str << " (!=)";
2089 EXPECT_FALSE(smaller == larger) << str << " (==)";
2090
2091 // true results using operator< and derived operators
2092 EXPECT_TRUE(smaller < larger) << str << " (<)";
2093 EXPECT_TRUE(larger > smaller) << str << " (>)";
2094 EXPECT_TRUE(larger >= smaller) << str << " (>=)";
2095 EXPECT_TRUE(smaller <= larger) << str << " (<=)";
2096
2097 // false results using operator< and derived operators
2098 EXPECT_FALSE(larger < smaller) << str << " (! <)";
2099 EXPECT_FALSE(smaller > larger) << str << " (! >)";
2100 EXPECT_FALSE(smaller >= larger) << str << " (! >=)";
2101 EXPECT_FALSE(larger <= smaller) << str << " (! <=)";
2102 }
2103 }
2104 };
2105
2106 auto const intNums = [] {
2107 // Inequality test cases are built from a list of sorted integers
2108 auto const values =
2109 std::to_array<int>({-100, -50, -20, -10, -1, 0, 1, 10, 20, 50, 100});
2110 // Check this list is sorted before converting it to Numbers.
2111 // That way if any of the other tests fail, we know it's because of code and not the
2112 // source data.
2113 EXPECT_TRUE(std::ranges::is_sorted(values));
2114
2115 std::vector<Number> result;
2116 result.reserve(values.size());
2117 for (auto const v : values)
2118 result.emplace_back(v);
2119 return result;
2120 }();
2121
2122 auto const otherNums = std::to_array<Number>({
2123 Number{-5, 100},
2124 Number{-1, 100},
2125 Number{-7, -10},
2126 Number{-2, -10},
2127 Number{0},
2128 Number{2, -10},
2129 Number{7, -10},
2130 Number{1, 100},
2131 Number{5, 100},
2132 });
2133
2134 test(intNums);
2135 test(otherNums);
2136 }
2137
2138 {
2139 // Equality test cases are <Number, __LINE__>. Number will be compared against itself
2140 using Case = std::pair<Number, int>;
2141 auto const c = std::to_array<Case>({
2142 {700, __LINE__},
2143 {50, __LINE__},
2144 {1, __LINE__},
2145 {0, __LINE__},
2146 {-1, __LINE__},
2147 {-30, __LINE__},
2148 {-600, __LINE__},
2149 });
2150 for (auto const& [n, line] : c)
2151 {
2152 auto const str = to_string(n);
2153 auto const location =
2154 std::string{" ("} + __FILE__ + ":" + std::to_string(line) + ")";
2155
2156 // NOLINTBEGIN(misc-redundant-expression) Explicitly testing operators with
2157 // equivalent values
2158 EXPECT_TRUE(n == n) << str << " ==" << location;
2159 EXPECT_FALSE(n != n) << str << " !=" << location;
2160
2161 EXPECT_FALSE(n < n) << str << " <" << location;
2162 EXPECT_FALSE(n > n) << str << " >" << location;
2163 EXPECT_TRUE(n >= n) << str << " >=" << location;
2164 EXPECT_TRUE(n <= n) << str << " <=" << location;
2165 // NOLINTEND(misc-redundant-expression)
2166 }
2167 }
2168 }
2169}
2170
2171TEST(NumberTest, stream)
2172{
2173 for (auto const mantissaScale : MantissaRange::getAllScales())
2174 {
2175 NumberMantissaScaleGuard const sg(mantissaScale);
2176
2177 Number const x{100};
2179 os << x;
2180 EXPECT_EQ((os.str()), (to_string(x)));
2181 }
2182}
2183
2184TEST(NumberTest, inc_dec)
2185{
2186 for (auto const mantissaScale : MantissaRange::getAllScales())
2187 {
2188 NumberMantissaScaleGuard const sg(mantissaScale);
2189
2190 Number x{100};
2191 Number const y = +x;
2192 EXPECT_EQ((x), (y));
2193 EXPECT_EQ((x++), (y));
2194 EXPECT_EQ((x), (Number{101}));
2195 EXPECT_EQ((x--), (Number{101}));
2196 EXPECT_EQ((x), (y));
2197 }
2198}
2199
2200TEST(NumberTest, to_st_amount)
2201{
2202 for (auto const mantissaScale : MantissaRange::getAllScales())
2203 {
2204 NumberMantissaScaleGuard const sg(mantissaScale);
2205
2206 Issue const issue;
2207 Number const n{7'518'783'80596, -5};
2209 auto res2 = STAmount{issue, n};
2210 EXPECT_EQ((res2), (STAmount{7518784}));
2211
2213 res2 = STAmount{issue, n};
2214 EXPECT_EQ((res2), (STAmount{7518783}));
2215
2217 res2 = STAmount{issue, n};
2218 EXPECT_EQ((res2), (STAmount{7518783}));
2219
2221 res2 = STAmount{issue, n};
2222 EXPECT_EQ((res2), (STAmount{7518784}));
2223 }
2224}
2225
2226TEST(NumberTest, truncate)
2227{
2228 for (auto const mantissaScale : MantissaRange::getAllScales())
2229 {
2230 NumberMantissaScaleGuard const sg(mantissaScale);
2231
2232 EXPECT_EQ((Number(25, +1).truncate()), (Number(250, 0)));
2233 EXPECT_EQ((Number(25, 0).truncate()), (Number(25, 0)));
2234 EXPECT_EQ((Number(25, -1).truncate()), (Number(2, 0)));
2235 EXPECT_EQ((Number(25, -2).truncate()), (Number(0, 0)));
2236 EXPECT_EQ((Number(99, -2).truncate()), (Number(0, 0)));
2237
2238 EXPECT_EQ((Number(-25, +1).truncate()), (Number(-250, 0)));
2239 EXPECT_EQ((Number(-25, 0).truncate()), (Number(-25, 0)));
2240 EXPECT_EQ((Number(-25, -1).truncate()), (Number(-2, 0)));
2241 EXPECT_EQ((Number(-25, -2).truncate()), (Number(0, 0)));
2242 EXPECT_EQ((Number(-99, -2).truncate()), (Number(0, 0)));
2243
2244 EXPECT_EQ((Number(0, 0).truncate()), (Number(0, 0)));
2245 EXPECT_EQ((Number(0, 30000).truncate()), (Number(0, 0)));
2246 EXPECT_EQ((Number(0, -30000).truncate()), (Number(0, 0)));
2247 EXPECT_EQ((Number(100, -30000).truncate()), (Number(0, 0)));
2248 EXPECT_EQ((Number(100, -30000).truncate()), (Number(0, 0)));
2249 EXPECT_EQ((Number(-100, -30000).truncate()), (Number(0, 0)));
2250 EXPECT_EQ((Number(-100, -30000).truncate()), (Number(0, 0)));
2251 }
2252}
2253
2254TEST(NumberTest, rounding)
2255{
2256 for (auto const mantissaScale : MantissaRange::getAllScales())
2257 {
2258 NumberMantissaScaleGuard const sg(mantissaScale);
2259
2260 // Test that rounding works as expected.
2261
2262 using NumberRoundings = std::map<Number::RoundingMode, std::int64_t>;
2263
2264 std::map<Number, NumberRoundings> const expected{
2265 // Positive numbers
2266 {
2267 Number{13, -1},
2268 {
2273 },
2274 },
2275 {
2276 Number{23, -1},
2277 {
2282 },
2283 },
2284 {
2285 Number{15, -1},
2286 {
2291 },
2292 },
2293 {
2294 Number{25, -1},
2295 {
2300 },
2301 },
2302 {
2303 Number{152, -2},
2304 {
2309 },
2310 },
2311 {
2312 Number{252, -2},
2313 {
2318 },
2319 },
2320 {
2321 Number{17, -1},
2322 {
2327 },
2328 },
2329 {
2330 Number{27, -1},
2331 {
2336 },
2337 },
2338
2339 // Negative numbers
2340 {
2341 Number{-13, -1},
2342 {
2347 },
2348 },
2349 {
2350 Number{-23, -1},
2351 {
2356 },
2357 },
2358 {
2359 Number{-15, -1},
2360 {
2365 },
2366 },
2367 {
2368 Number{-25, -1},
2369 {
2374 },
2375 },
2376 {
2377 Number{-152, -2},
2378 {
2383 },
2384 },
2385 {
2386 Number{-252, -2},
2387 {
2392 },
2393 },
2394 {
2395 Number{-17, -1},
2396 {
2401 },
2402 },
2403 {
2404 Number{-27, -1},
2405 {
2410 },
2411 },
2412 };
2413
2414 for (auto const& [num, roundings] : expected)
2415 {
2416 for (auto const& [mode, val] : roundings)
2417 {
2418 NumberRoundModeGuard const g{mode};
2419 auto const res = static_cast<std::int64_t>(num);
2420 EXPECT_EQ((res), (val)) << to_string(num) + " with mode " +
2421 std::to_string(static_cast<int>(mode)) + " expected " +
2422 std::to_string(val) + " got " + std::to_string(res);
2423 }
2424 }
2425 }
2426}
2427
2428TEST(NumberTest, int64)
2429{
2430 for (auto const mantissaScale : MantissaRange::getAllScales())
2431 {
2432 NumberMantissaScaleGuard const sg(mantissaScale);
2433
2434 auto const scale = Number::getMantissaScale();
2435
2436 // Control case
2437 EXPECT_GT((Number::maxMantissa()), (10));
2438 Number const ten{10};
2439 EXPECT_LE((ten.exponent()), (0));
2440
2442 {
2443 EXPECT_GT((std::numeric_limits<std::int64_t>::max()), (kInitialXrp.drops()));
2444 EXPECT_LT((Number::maxMantissa()), (kInitialXrp.drops()));
2445 Number const initalXrp{kInitialXrp};
2446 EXPECT_GT((initalXrp.exponent()), (0));
2447
2448 Number const maxInt64{Number::kMaxRep};
2449 EXPECT_GT((maxInt64.exponent()), (0));
2450 // 85'070'591'730'234'615'865'843'651'857'942'052'864 - 38 digits
2451 EXPECT_EQ((power(maxInt64, 2)), (Number{85'070'591'730'234'62, 22}));
2452
2453 Number const max = Number{false, Number::maxMantissa(), 0, Number::Normalized{}};
2454 EXPECT_LE(max.exponent(), 0);
2455 // 99'999'999'999'999'980'000'000'000'000'001 - 32 digits
2456 EXPECT_EQ(power(max, 2), (Number{99'999'999'999'999'98, 16}));
2457 }
2458 else
2459 {
2460 EXPECT_GT((std::numeric_limits<std::int64_t>::max()), (kInitialXrp.drops()));
2461 EXPECT_GT((Number::maxMantissa()), (kInitialXrp.drops()));
2462 Number const initalXrp{kInitialXrp};
2463 EXPECT_LE((initalXrp.exponent()), (0));
2464
2465 Number const maxInt64{Number::kMaxRep};
2466 EXPECT_LE((maxInt64.exponent()), (0));
2467 // 85'070'591'730'234'615'847'396'907'784'232'501'249 - 38 digits
2468 EXPECT_EQ((power(maxInt64, 2)), (Number{85'070'591'730'234'615'85, 19}));
2469
2471
2472 auto const maxMantissa = Number::maxMantissa();
2473 Number const max = Number{false, maxMantissa, 0, Number::Normalized{}};
2474 EXPECT_EQ((max.mantissa()), (maxMantissa / 10));
2475 EXPECT_EQ((max.exponent()), (1));
2476 // 99'999'999'999'999'999'800'000'000'000'000'000'100 - also 38
2477 // digits
2478 EXPECT_EQ(
2479 (power(max, 2)), (Number{false, (maxMantissa / 10) - 1, 20, Number::Normalized{}}));
2480 }
2481 }
2482}
2483
2484TEST(NumberTest, upward_rounding_produces_value_not_below_exact_at_k_max_rep_cusp)
2485{
2486 for (auto const mantissaScale : MantissaRange::getAllScales())
2487 {
2488 NumberMantissaScaleGuard const mg{mantissaScale};
2490
2491 auto const scale = Number::getMantissaScale();
2492
2493 constexpr std::int64_t kAValue = 1'000'000'000'000'049'863LL;
2494 constexpr std::int64_t kBValue = 9'223'372'036'854'315'903LL;
2495
2496 Number const a = kAValue;
2497 Number const b = kBValue;
2498 Number const product = a * b;
2499
2500 // Exact reference in BigInt.
2501 BigInt const exactProduct = BigInt(kAValue) * BigInt(kBValue);
2502
2503 // What Number actually stored.
2504 BigInt const storedValue = toBigInt(product);
2505
2506 BigInt const signedDifference = storedValue - exactProduct;
2507
2508 auto const message = [&] {
2510 os << " a = " << fmt(BigInt(kAValue)) << "\n"
2511 << " b = " << fmt(BigInt(kBValue)) << "\n"
2512 << " exact a*b = " << fmt(exactProduct) << "\n"
2513 << " stored = " << fmt(storedValue) << "\n"
2514 << " stored - exact = " << fmt(signedDifference) << "\n"
2515 << " upward = " << (signedDifference >= 0 ? "held" : "VIOLATED") << "\n"
2516 << " stored.mantissa = " << product.mantissa() << "\n"
2517 << " stored.exponent = " << product.exponent() << "\n\n";
2518 return os.str();
2519 };
2520
2521 switch (scale)
2522 {
2525 EXPECT_TRUE(signedDifference >= 0) << message();
2526 EXPECT_TRUE(signedDifference < pow10<BigInt>(product.exponent())) << message();
2527 EXPECT_EQ(product.mantissa(), (std::numeric_limits<std::int64_t>::max() / 10) + 1);
2528 EXPECT_EQ(product.exponent(), 19);
2529 break;
2530
2532 EXPECT_TRUE(signedDifference < 0) << message();
2533 EXPECT_EQ(
2534 product.mantissa(), (std::numeric_limits<std::int64_t>::max() / 100) * 100);
2535 EXPECT_EQ(product.exponent(), 18);
2536 break;
2537
2539 // The seemingly weird rounding here is because a & b are both
2540 // normalized, and both round up when being converted to Number,
2541 // so you're really getting
2542 // 1_000_000_000_000_050 * 9_223_372_036_854_316.
2543 EXPECT_TRUE(signedDifference >= 0) << message();
2544 EXPECT_EQ(
2545 product.mantissa(), (std::numeric_limits<std::int64_t>::max() / 1000) + 3);
2546 EXPECT_EQ(product.exponent(), 21);
2547 break;
2548 }
2549 }
2550}
2551
2552/*
2553 * Companion regression for the kMaxRep cusp behavior, but for `operator/=` on
2554 * the cusp-fix-ENABLED `Large` scale.
2555 *
2556 * Before the dropped-remainder fix, `operator/=` with Upward rounding could
2557 * return a value STRICTLY LESS than the exact quotient, violating Upward's
2558 * directional invariant.
2559 *
2560 * Mechanism (fix-enabled path):
2561 * 1. `operator/=` computes `numerator = nm * 10^17` and
2562 * `zm = numerator / dm` (integer division, truncates remainder).
2563 * 2. If `remainder != 0`, the correction block runs:
2564 * zm *= 100000
2565 * correction = (remainder * 100000) / dm // also truncates
2566 * zm += correction
2567 * ze -= 5
2568 * The truncation in `correction` discards a sub-1/100000 residual.
2569 * 3. `normalize`'s shift loop reduces zm to fit, but the discarded residual
2570 * is BELOW the Guard's visibility, so the Guard sees fraction = 0.
2571 * 4. Under Upward + positive, `round()` returns -1 (no round-up), and the
2572 * algorithm returns the truncated zm.
2573 */
2574TEST(NumberTest, upward_division_returns_value_not_below_exact_on_large_scale)
2575{
2576 for (auto const mantissaScale : MantissaRange::getAllScales())
2577 {
2578 NumberMantissaScaleGuard const mg{mantissaScale};
2580
2581 auto const scale = Number::getMantissaScale();
2582
2583 constexpr std::int64_t kAValue = 2LL;
2584 constexpr std::int64_t kBValue = 1'000'000'000'000'000'007LL;
2585 // kBValue = 10^18 + 7 (prime, in [minMantissa, kMaxRep]).
2586
2587 Number const a{kAValue, 0};
2588 Number const b{kBValue, 0};
2589 Number const quotient = a / b;
2590
2591 Dec const exact = Dec(kAValue) / Dec(kBValue);
2592 Dec const stored = Dec(quotient.mantissa()) * pow10(quotient.exponent());
2593 Dec const diff = stored - exact;
2594
2595 auto const message = [&] {
2597 os << " a = " << kAValue << "\n"
2598 << " b = " << kBValue << "\n"
2599 << " exact a/b = " << fmt(exact) << "\n"
2600 << " stored a/b = " << fmt(stored) << "\n"
2601 << " stored - exact = " << fmt(diff)
2602 << " (negative => Upward gave value BELOW truth)\n"
2603 << " quotient.mantissa = " << quotient.mantissa() << "\n"
2604 << " quotient.exponent = " << quotient.exponent() << "\n\n";
2605 return os.str();
2606 };
2607
2608 // Upward invariant: stored >= exact. Bug: stored < exact.
2609 switch (scale)
2610 {
2613 EXPECT_TRUE(stored >= exact) << message();
2614 EXPECT_TRUE(diff < pow10(quotient.exponent())) << message();
2615 break;
2616
2618 EXPECT_TRUE(stored < exact) << message();
2619 EXPECT_TRUE(diff >= -pow10(quotient.exponent())) << message();
2620 break;
2621
2623 // Small mantissa doesn't have the correction for dropped remainders.
2624 EXPECT_TRUE(stored < exact) << message();
2625 break;
2626 }
2627 }
2628}
2629
2630// Companion test case for Upward positive operator/=: Downward negative.
2631TEST(NumberTest, downward_division_returns_value_not_above_exact_on_large_scale)
2632{
2633 for (auto const mantissaScale : MantissaRange::getAllScales())
2634 {
2635 NumberMantissaScaleGuard const mg{mantissaScale};
2637
2638 auto const scale = Number::getMantissaScale();
2639
2640 constexpr std::int64_t kAValue = -2LL;
2641 constexpr std::int64_t kBValue = 1'000'000'000'000'000'007LL;
2642 // kBValue = 10^18 + 7 (prime, in [minMantissa, kMaxRep]).
2643
2644 Number const a{kAValue, 0};
2645 Number const b{kBValue, 0};
2646 Number const quotient = a / b;
2647
2648 Dec const exact = Dec(kAValue) / Dec(kBValue);
2649 Dec const stored = Dec(quotient.mantissa()) * pow10(quotient.exponent());
2650 Dec const diff = stored - exact;
2651
2652 auto const message = [&] {
2654 os << " a = " << kAValue << "\n"
2655 << " b = " << kBValue << "\n"
2656 << " exact a/b = " << fmt(exact) << "\n"
2657 << " stored a/b = " << fmt(stored) << "\n"
2658 << " stored - exact = " << fmt(diff)
2659 << " (positive => Downward gave value ABOVE truth)\n"
2660 << " quotient.mantissa = " << quotient.mantissa() << "\n"
2661 << " quotient.exponent = " << quotient.exponent() << "\n\n";
2662 return os.str();
2663 };
2664
2665 // invariant: stored <= exact. Bug: stored > exact.
2666 switch (scale)
2667 {
2670 EXPECT_TRUE(stored <= exact) << message();
2671 EXPECT_TRUE(diff > -pow10(quotient.exponent())) << message();
2672 break;
2673
2675 EXPECT_TRUE(stored > exact) << message();
2676 EXPECT_TRUE(diff <= pow10(quotient.exponent())) << message();
2677 break;
2678
2680 // Small mantissa doesn't have the correction for dropped remainders.
2681 EXPECT_TRUE(stored < exact) << message();
2682 break;
2683 }
2684 }
2685}
2686
2687/*
2688 * Companion test case for Upward positive operator/=: ToNearest.
2689 *
2690 * With ToNearest, if the dropped digits are exactly "5", then the mantissa will
2691 * be rounded to even. The numbers below result in a value where the unrounded
2692 * mantissa ends in an even digit, and "infinite precision" would drop
2693 * "500000000000000000145...", but doNormalize only sees "5". Without the
2694 * rounding fix, doNormalize rounds down to the even value. With the rounding
2695 * fix, doNormalize knows there are more digits beyond "5", and so rounds _up_
2696 * to the odd value.
2697 */
2698TEST(NumberTest, to_nearest_division_uses_dropped_digits_on_large_scale)
2699{
2700 for (auto const mantissaScale : MantissaRange::getAllScales())
2701 {
2702 NumberMantissaScaleGuard const mg{mantissaScale};
2704
2705 auto const scale = Number::getMantissaScale();
2706
2707 constexpr std::int64_t kAValue = 1'269'917'268'816'087'809LL;
2708 constexpr std::int64_t kBValue = 3'458'525'013'821'685'511LL;
2709 // kBValue is prime and in [minMantissa, kMaxRep].
2710
2711 Number const a{kAValue, 0};
2712 Number const b{kBValue, 0};
2713 Number const quotient = a / b;
2714
2715 Dec const exact = Dec(kAValue) / Dec(kBValue);
2716 Dec const stored = Dec(quotient.mantissa()) * pow10(quotient.exponent());
2717 Dec const diff = stored - exact;
2718
2719 auto const message = [&] {
2721 os << " a = " << kAValue << "\n"
2722 << " b = " << kBValue << "\n"
2723 << " exact a/b = " << fmt(exact) << "\n"
2724 << " stored a/b = " << fmt(stored) << "\n"
2725 << " stored - exact = " << fmt(diff)
2726 << " (negative => ToNearest gave value BELOW truth)\n"
2727 << " quotient.mantissa = " << quotient.mantissa() << "\n"
2728 << " quotient.exponent = " << quotient.exponent() << "\n\n";
2729 return os.str();
2730 };
2731
2732 // invariant: stored >= exact. Bug: stored < exact.
2733 switch (scale)
2734 {
2737 EXPECT_TRUE(stored >= exact) << message();
2738 EXPECT_TRUE(diff < pow10(quotient.exponent())) << message();
2739 break;
2740
2742 EXPECT_TRUE(stored < exact) << message();
2743 EXPECT_TRUE(diff >= -pow10(quotient.exponent())) << message();
2744 break;
2745
2747 // Small mantissa doesn't have the correction for dropped remainders.
2748 EXPECT_TRUE(stored < exact) << message();
2749 break;
2750 }
2751 }
2752}
2753
2754TEST(NumberTest, subtraction_rounding)
2755{
2756 for (auto const mantissaScale : MantissaRange::getAllScales())
2757 {
2758 NumberMantissaScaleGuard const mg{mantissaScale};
2760
2761 auto const scale = Number::getMantissaScale();
2762
2763 auto const exp = Number::mantissaLog();
2764 // SubCase is <offset, extraB, aString, bString>
2765 // * offset: offset from exp
2766 // * extraB: whether to include 1e"exp" in "b"
2767 // * aString: expected string value for "a"
2768 // * bString: expected string value for "b"
2769 // There aren't too many valid combinations for test cases here. If extraB is true,
2770 // offset can really only be 2, because any larger and the mantissa can't be represented
2771 // without loss. Offset can't be less than 2, or there's no error.
2773 auto const c = std::to_array<SubCase>({
2774 {
2775 2,
2776 true,
2777 scale == MantissaRange::MantissaScale::Small ? "100000000000000000"
2778 : "100000000000000000000",
2779 scale == MantissaRange::MantissaScale::Small ? "-1000000000000001"
2780 : "-1000000000000000001",
2781 },
2782 {
2783 2,
2784 false,
2785 scale == MantissaRange::MantissaScale::Small ? "100000000000000000"
2786 : "100000000000000000000",
2787 "-1",
2788 },
2789 {
2790 30,
2791 false,
2793 ? "1000000000000000000000000000000000000000000000"
2794 : "1000000000000000000000000000000000000000000000000",
2795 "-1",
2796 },
2797 });
2798
2799 for (auto const& [offset, extraB, aString, bString] : c)
2800 {
2801 Number const a{1LL, exp + offset};
2802 Number const b{-((extraB ? Number{1, exp} : kNumZero) + 1)};
2803
2804 auto const bigA = toBigInt(a);
2805 auto const bigB = toBigInt(b);
2806
2807 EXPECT_EQ(bigA, BigInt{aString});
2808 EXPECT_EQ(bigB, BigInt{bString});
2809
2810 auto construct = [&a, &b](Number::RoundingMode r) {
2811 NumberRoundModeGuard const roundGuard{r};
2812 auto const sum = a + b;
2813 BigInt const stored = toBigInt(sum);
2814 return std::make_pair(r, std::make_pair(stored, sum));
2815 };
2816
2817 BigInt const exact = bigA + bigB;
2818
2819 auto const sums = [&] {
2825 return r;
2826 }();
2827
2828 auto const message = [&](auto const& r, auto const& sum) {
2830 os << " a = " << a << " (" << fmt(bigA) << ")\n b = " << b
2831 << " (" << fmt(bigB) << ")\n exact a + b = " << fmt(exact) << "\n";
2832
2833 auto const diff = sum.first - exact;
2834 auto const rLabel = to_string(r);
2835 os << std::string(15 - rLabel.length(), ' ') << rLabel << " = " << fmt(sum.first)
2836 << "\n difference = " << fmt(diff) << "\n\n";
2837
2838 return os.str();
2839 };
2840
2841 auto const expectedExponent =
2842 offset - (scale == MantissaRange::MantissaScale::Small && extraB ? 1 : 0);
2843 auto const epsilon = pow10<BigInt>(expectedExponent);
2844 for (auto const& [r, sum] : sums)
2845 {
2846 auto const diff = sum.first - exact;
2847 switch (scale)
2848 {
2852 // Without the fix, all the results but one round up
2854 {
2855 // Downward works because the Guard sign is negative, and Downward
2856 // returns Up instead of Down if negative and there's a remainder,
2857 // whereas TowardsZero always returns Down.
2858 EXPECT_LT(sum.first, exact) << message(r, sum);
2859 EXPECT_EQ(diff, -(epsilon - 1)) << message(r, sum);
2860 }
2861 else
2862 {
2863 EXPECT_GT(sum.first, exact) << message(r, sum);
2864 EXPECT_EQ(diff, 1) << message(r, sum);
2865 }
2866 break;
2867 }
2868 default: {
2869 EXPECT_LE(sum.second.exponent(), expectedExponent) << message(r, sum);
2870 switch (r)
2871 {
2874 EXPECT_GT(sum.first, exact) << message(r, sum);
2875 EXPECT_EQ(diff, 1) << message(r, sum);
2876 break;
2877 default:
2878 EXPECT_LT(sum.first, exact) << message(r, sum);
2879 EXPECT_EQ(diff, -(epsilon - 1)) << message(r, sum);
2880 }
2881 }
2882 }
2883 }
2884 }
2885 }
2886}
2887
2888TEST(NumberTest, normalization_cusp_tonearest_and_downward)
2889{
2890 for (auto const mantissaScale : MantissaRange::getAllScales())
2891 {
2892 NumberMantissaScaleGuard const mg{mantissaScale};
2894
2895 auto const scale = Number::getMantissaScale();
2896
2897 constexpr auto kMaxRep = Number::kMaxRep;
2898
2899 // Both ToNearest and Downward should round to `below`
2900 auto constexpr actual = static_cast<std::uint64_t>(kMaxRep) + 1;
2901 Number const below{static_cast<std::int64_t>(kMaxRep), 0};
2902 Number const above{false, static_cast<std::uint64_t>(kMaxRep) + 3, 0, Number::Normalized{}};
2903
2904 auto const construct = [](Number::RoundingMode mode) {
2905 NumberRoundModeGuard const roundGuard{mode};
2906 return Number(false, actual, 0, Number::Normalized{});
2907 };
2908 Number const upward = construct(Number::RoundingMode::Upward);
2909
2910 Number const toNearest = construct(Number::RoundingMode::ToNearest);
2911
2912 Number const downward = construct(Number::RoundingMode::Downward);
2913
2914 auto const message = [&] {
2916 log << " actual = " << actual << " (kMaxRep + 1)\n"
2917 << " below = " << below << " (kMaxRep, distance 1)\n"
2918 << " above = " << above << " (kMaxRep + 3, distance 2)\n"
2919 << " Upward = " << upward << "\n"
2920 << " ToNearest = " << toNearest << "\n"
2921 << " Downward = " << downward << "\n\n";
2922 return log.str();
2923 };
2924
2925 switch (scale)
2926 {
2928 // With the small mantissa, everything but Downward rounds UP, including the
2929 // reference values, "above" and "below"
2930
2931 EXPECT_EQ(below, above) << message();
2932 EXPECT_EQ(upward, above) << message();
2933 EXPECT_EQ(toNearest, above) << message();
2934
2935 EXPECT_LT(downward, below) << message();
2936
2937 break;
2938
2941 // Upward round UP
2942 EXPECT_EQ(upward, above) << message();
2943
2944 // ToNearest rounds UP when the DOWN neighbor is strictly closer
2945 EXPECT_EQ(toNearest, above) << message();
2946 EXPECT_GT(toNearest, below) << message();
2947
2948 // Downward undershoots: it returns a value below `below`
2949 EXPECT_LT(downward, below) << message();
2950
2951 // Both should have given the same answer, but they differ
2952 EXPECT_GT(toNearest, downward) << message();
2953
2954 break;
2955 default:
2956 // Covers "Large" and any newly added scales
2957
2958 // Upward round UP
2959 EXPECT_EQ(upward, above) << message();
2960
2961 // ToNearest rounds to the strictly closer DOWN neighbor
2962 EXPECT_NE(toNearest, above) << message();
2963 EXPECT_EQ(toNearest, below) << message();
2964
2965 // Downward also rounds to `below`
2966 EXPECT_EQ(downward, below) << message();
2967
2968 // ToNearest rounds to downward
2969 EXPECT_EQ(toNearest, downward) << message();
2970 break;
2971 }
2972 }
2973}
2974
2975TEST(NumberTest, number_add_directed_sign_wrong)
2976{
2977 for (auto const mantissaScale : MantissaRange::getAllScales())
2978 {
2979 NumberMantissaScaleGuard const mg{mantissaScale};
2981
2982 auto const scale = Number::getMantissaScale();
2983 {
2984 // Two negative numbers with the same exponent
2985 Number const a{-6, Number::mantissaLog()};
2986 Number const b{a - 3};
2987 EXPECT_TRUE(a.exponent() == b.exponent() && abs(b) > abs(a));
2988
2989 BigInt const exact = toBigInt(a) + toBigInt(b);
2991 {
2992 EXPECT_EQ(exact, BigInt{"-12000000000000003"});
2993 }
2994 else
2995 {
2996 EXPECT_EQ(exact, BigInt{"-12000000000000000003"});
2997 }
2998
2999 Number down, up;
3000 {
3002 down = a + b;
3003 }
3004 {
3006 up = a + b;
3007 }
3008
3009 auto const valueDown = toBigInt(down);
3010 auto const valueUp = toBigInt(up);
3011 auto const message = [&] {
3013 log << " exact = " << fmt(exact) << "\n downward = " << fmt(valueDown)
3014 << " (correct rounding: <= exact)"
3015 << "\n upward = " << fmt(valueUp) << " (correct rounding: >= exact)\n\n";
3016 return log.str();
3017 };
3018
3020 {
3021 EXPECT_LE(valueDown, exact) << message(); // Downward should round away from zero
3022 EXPECT_GE(valueUp, exact) << message(); // Upward should round toward 0
3023 }
3024 else
3025 {
3026 EXPECT_GT(valueDown, exact)
3027 << message(); // Downward rounded toward zero (too high)
3028 EXPECT_LT(valueUp, exact) << message(); // Upward rounded toward -inf (too low)
3029 }
3030 }
3031
3032 {
3033 // Positive control: the same magnitudes with a positive result round
3034 Number const pa{6, Number::mantissaLog()};
3035 Number const pb{pa + 3};
3036 EXPECT_TRUE(pa.exponent() == pb.exponent() && abs(pb) > abs(pa));
3037 BigInt const pexact = toBigInt(pa) + toBigInt(pb); // 12'000'000'000'000'000'003
3038
3039 Number pdown, pup;
3040 {
3042 pdown = pa + pb;
3043 }
3044 {
3046 pup = pa + pb;
3047 }
3048 auto const valuePDown = toBigInt(pdown);
3049 auto const valuePUp = toBigInt(pup);
3050 auto const message = [&] {
3052 log << " exact = " << fmt(pexact) << "\n downward = " << fmt(valuePDown)
3053 << " (correct rounding: <= exact)"
3054 << "\n upward = " << fmt(valuePUp)
3055 << " (correct rounding: >= exact)\n\n";
3056 return log.str();
3057 };
3058
3059 EXPECT_LE(valuePDown, pexact) << message(); // correct for positive results
3060 EXPECT_GE(valuePUp, pexact) << message();
3061 }
3062
3063 {
3064 // Mixed sign numbers with the same exponent: negative second value
3065 Number const a{1, Number::mantissaLog()};
3066 Number const b{Number{-9, Number::mantissaLog()} - 3};
3067 EXPECT_TRUE(a.exponent() == b.exponent() && abs(b) > abs(a));
3068
3069 BigInt const exact = toBigInt(a) + toBigInt(b);
3071 {
3072 EXPECT_EQ(exact, BigInt{"-8000000000000003"});
3073 }
3074 else
3075 {
3076 EXPECT_EQ(exact, BigInt{"-8000000000000000003"});
3077 }
3078
3079 Number down, up;
3080 {
3082 down = a + b;
3083 }
3084 {
3086 up = a + b;
3087 }
3088
3089 auto const valueDown = toBigInt(down);
3090 auto const valueUp = toBigInt(up);
3091 auto const message = [&] {
3093 log << " exact = " << fmt(exact) << "\n downward = " << fmt(valueDown)
3094 << " (correct rounding: <= exact)"
3095 << "\n upward = " << fmt(valueUp) << " (correct rounding: >= exact)\n\n";
3096 return log.str();
3097 };
3098
3099 EXPECT_LE(valueDown, exact) << message(); // Downward should round away from zero
3100 EXPECT_GE(valueUp, exact) << message(); // Upward should round toward 0
3101 }
3102
3103 {
3104 // Mixed sign numbers with the same exponent: negative first value
3105 Number const a{-1, Number::mantissaLog()};
3106 Number const b{Number{9, Number::mantissaLog()} + 3};
3107 EXPECT_TRUE(a.exponent() == b.exponent() && abs(b) > abs(a));
3108
3109 BigInt const exact = toBigInt(a) + toBigInt(b);
3111 {
3112 EXPECT_EQ(exact, BigInt{"8000000000000003"});
3113 }
3114 else
3115 {
3116 EXPECT_EQ(exact, BigInt{"8000000000000000003"});
3117 }
3118
3119 Number down, up;
3120 {
3122 down = a + b;
3123 }
3124 {
3126 up = a + b;
3127 }
3128
3129 auto const valueDown = toBigInt(down);
3130 auto const valueUp = toBigInt(up);
3131 auto const message = [&] {
3133 log << " exact = " << fmt(exact) << "\n downward = " << fmt(valueDown)
3134 << " (correct rounding: <= exact)"
3135 << "\n upward = " << fmt(valueUp) << " (correct rounding: >= exact)\n\n";
3136 return log.str();
3137 };
3138
3139 EXPECT_LE(valueDown, exact) << message(); // Downward should round away from zero
3140 EXPECT_GE(valueUp, exact) << message(); // Upward should round toward 0
3141 }
3142 }
3143}
3144
3145TEST(NumberTest, number_add_to_nearest_picks_farther)
3146{
3147 for (auto const mantissaScale : MantissaRange::getAllScales())
3148 {
3149 NumberMantissaScaleGuard const mg{mantissaScale};
3151
3152 auto const scale = Number::getMantissaScale();
3153
3154 // Case is <y, expected q>
3156
3157 auto const c = std::to_array<Case>({
3158 {Number{5'175'909'259'972'499'745LL, 22}, -1'074'951'375'311'646'003},
3159 {Number{1}, -1'074'956'551'220'905'975},
3160 {Number{1, 10}, -1'074'956'551'220'905'975},
3161 {Number{1, 20}, -1'074'956'551'220'905'975},
3162 {Number{1, 27}, -1'074'956'551'220'905'975},
3163 {Number{1, 28}, -1'074'956'551'220'905'974},
3164 {Number{1, 31}, -1'074'956'551'220'904'975},
3165 });
3166
3167 for (auto const& [y, expectedQ] : c)
3168 {
3169 Number const x{-1'074'956'551'220'905'975LL, 28};
3170 Number const res = x + y;
3171
3172 BigInt const exact = toBigInt(x) + toBigInt(y);
3173 BigInt const vres = toBigInt(res);
3174
3175 BigInt ulp = 1;
3176 for (int i = 0; i < res.exponent(); ++i)
3177 ulp *= 10;
3178
3179 BigInt const q = (exact - ulp / 2) / ulp;
3180 Number const normalizedExact{static_cast<std::int64_t>(q), res.exponent()};
3181 BigInt const norm = toBigInt(normalizedExact);
3182
3183 auto const message = [&](auto const& comp) {
3185 log << fmt(q) + " != " + fmt(comp) << "\n"
3186 << " x = " << x << "\n y = " << y
3187 << "\n exact = " << fmt(exact)
3188 << "\n result (x + y) = " << fmt(vres)
3189 << "\n normalize(exact) = " << fmt(norm) << "\n\n";
3190 return log.str();
3191 };
3192
3194 {
3195 auto const comp = toBigInt(Number{expectedQ, -3});
3196 EXPECT_EQ(q, comp) << message(comp);
3197 }
3198 else
3199 {
3200 EXPECT_EQ(q, expectedQ) << message(BigInt(expectedQ));
3201 }
3202 EXPECT_EQ(normalizedExact, res);
3203 }
3204 }
3205}
3206
3207TEST(NumberTest, number_cusp_rounding_with_fractional_parts)
3208{
3209 for (auto const mantissaScale : MantissaRange::getAllScales())
3210 {
3211 NumberMantissaScaleGuard const mg{mantissaScale};
3212
3213 auto const scale = Number::getMantissaScale();
3214
3215 Number const below{static_cast<std::int64_t>(Number::kMaxRep), 0};
3216 Number const above{false, Number::kMaxRepUp, 0, Number::Normalized{}};
3217
3218 auto header = [&] {
3220 log << "Scale: " << to_string(mantissaScale) << ", Below: " << below
3221 << ", Above: " << above << "\n";
3222 return log.str();
3223 };
3224
3225 auto const zeroPointFour = Number(4, -1);
3226 auto const zeroPointFive = Number(5, -1);
3227 auto const zeroPointSix = Number(6, -1);
3228 auto const onePointFour = Number(14, -1);
3229 auto const onePointFive = Number(15, -1);
3230 auto const onePointSix = Number(16, -1);
3231 auto const twoPointFour = Number(24, -1);
3232 auto const twoPointFive = Number(25, -1);
3233 auto const twoPointSix = Number(26, -1);
3234
3235 auto const operands = std::to_array<Number>({
3236 zeroPointFour,
3237 zeroPointFive,
3238 zeroPointSix,
3239 onePointFour,
3240 onePointFive,
3241 onePointSix,
3242 twoPointFour,
3243 twoPointFive,
3244 twoPointSix,
3245 });
3246
3247 auto const modes = std::to_array<Number::RoundingMode>({
3252 });
3253
3254 // Addition cases test kMaxRep + Operand
3255 for (auto const& mode : modes)
3256 {
3257 for (auto const& operand : operands)
3258 {
3259 NumberRoundModeGuard const rg{mode};
3260
3261 auto const expectedValue = [&] {
3262 // Returns "above" by default. The checks here are for exceptions.
3264 {
3265 if (mode == Number::RoundingMode::ToNearest && operand < onePointFive)
3266 return below;
3269 return below;
3270 }
3272 {
3274 {
3275 if (operand < zeroPointFive)
3276 return below;
3277 }
3280 {
3281 if (operand >= onePointFour)
3282 return below - 7;
3283 return below;
3284 }
3285 }
3287 {
3289 {
3290 if (operand < zeroPointFive)
3291 return below;
3292 if (operand <= zeroPointSix)
3293 return below - 7;
3294 }
3297 {
3298 if (operand >= onePointFour)
3299 return below - 7;
3300 return below;
3301 }
3302 if (mode == Number::RoundingMode::Upward && operand <= zeroPointSix)
3303 return below - 7;
3304 }
3307 return above + 1000;
3308 return above;
3309 }();
3310
3311 Number const actual = below + operand;
3312
3313 auto const message = [&] {
3315 ss << header() << "kMaxRep + " << operand << " rounded " << to_string(mode)
3316 << " to " << actual << ". Expected: " << expectedValue;
3317 return ss.str();
3318 };
3319 EXPECT_EQ(actual, expectedValue) << message();
3320 }
3321 }
3322
3323 // Subtraction cases test kMaxRepUp - Operand
3324 for (auto const& mode : modes)
3325 {
3326 for (auto const& operand : operands)
3327 {
3328 NumberRoundModeGuard const rg{mode};
3329
3330 auto const expectedValue = [&] {
3332 {
3333 if (mode == Number::RoundingMode::ToNearest && operand > onePointFive)
3334 return below;
3337 return below;
3338 }
3341 {
3343 {
3344 if (operand >= twoPointSix)
3345 return below;
3346 }
3348 {
3349 if (operand >= onePointFour)
3350 return below - 7;
3351 }
3353 {
3354 if (operand <= onePointSix)
3355 return below - 7;
3356 return below;
3357 }
3358 }
3360 {
3362 return below - 1000;
3363 if (mode == Number::RoundingMode::Upward)
3364 return below;
3365 }
3366 return above;
3367 }();
3368
3369 Number const actual = above - operand;
3370
3371 auto const message = [&] {
3373 ss << header() << "kMaxRepUp - " << operand << " rounded " << to_string(mode)
3374 << " to " << actual << ". Expected: " << expectedValue;
3375 return ss.str();
3376 };
3377 EXPECT_EQ(actual, expectedValue) << message();
3378 }
3379 }
3380 }
3381}
3382
3383} // namespace xrpl
T begin(T... args)
Floating point representation of amounts with high dynamic range.
Definition IOUAmount.h:26
A currency issued by an account.
Definition Issue.h:18
Sets the new scale and restores the old scale when it leaves scope.
Definition Number.h:967
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
constexpr rep mantissa() const noexcept
Returns the mantissa of the external view of the Number.
Definition Number.h:696
static InternalRep maxMantissa()
Definition Number.h:568
static constexpr InternalRep kMaxRepUp
Definition Number.h:367
static constexpr int kMinExponent
Definition Number.h:361
static RoundingMode setround(RoundingMode inMode)
static constexpr InternalRep kMaxRep
Definition Number.h:364
static Number max() noexcept
Definition Number.h:823
static RoundingMode getround()
static MantissaRange::MantissaScale getMantissaScale()
Returns which mantissa scale is currently in use for normalization.
static InternalRep minMantissa()
Definition Number.h:562
static constexpr int kMaxExponent
Definition Number.h:362
constexpr int exponent() const noexcept
Returns the exponent of the external view of the Number.
Definition Number.h:718
static Number min() noexcept
Definition Number.h:817
static Number lowest() noexcept
Definition Number.h:829
static int mantissaLog()
Definition Number.h:574
T emplace_back(T... args)
T emplace(T... args)
T insert(T... args)
T invoke(T... args)
T is_sorted(T... args)
T make_pair(T... args)
T max(T... args)
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
static constexpr Number kNumZero
Definition Number.h:667
static auto sum(TCollection const &col)
TEST(FileUtilitiesTest, get_file_contents)
boost::multiprecision::cpp_dec_float_50 Dec
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
Number root(Number f, unsigned d)
boost::multiprecision::cpp_int BigInt
Number power(Number const &f, unsigned n)
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
static std::string fmt(BigInt const &value)
Number root2(Number f)
constexpr Number abs(Number x) noexcept
Definition Number.h:880
BigInt toBigInt(Number const &n)
constexpr Number squelch(Number const &x, Number const &limit) noexcept
Definition Number.h:911
static T pow10(int n)
constexpr XRPAmount kInitialXrp
Configure the native currency.
T reserve(T... args)
T setprecision(T... args)
T str(T... args)
static std::set< MantissaScale > const & getAllScales()
Definition Number.h:178
T to_string(T... args)
T what(T... args)