[ET Trac] #2925: overflow in rat<int64> in Arith
Roland Haas
trac-noreply at einsteintoolkit.org
Thu Mar 26 12:08:20 CDT 2026
#2925: overflow in rat<int64> in Arith
Reporter: Roland Haas
Status: new
Milestone:
Version:
Type: bug
Priority: minor
Component:
Comment (by Roland Haas):
Following up on the discussion, one can do the multiplication manually:
```
// TODO: need special code to handle the case if a or b is int64_min since -int64_min > int64_max (https://en.cppreference.com/w/cpp/numeric/math/abs#Notes)
int64_t save_mult(int64_t a, int64_t b) {
uint64_t abs_a = std::abs(a);
uint64_t abs_b = std::abs(b);
auto upper = [](uint64_t x) -> uint32_t { return (x >> 32) & 0xffffffffu; };
auto lower = [](uint64_t x) -> uint32_t { return (x >> 0) & 0xffffffffu; };
assert(upper(abs_a) * upper(abs_b) == 0);
assert(upper(upper(abs_a) * lower(abs_b)) == 0);
assert(upper(lower(abs_a) * upper(abs_b)) == 0);
// so far: no overflow for uint64_t, now check that we are not exceeding int64_max (~ 1/2 of uint64_max)
assert(abs_a * abs_b <= std::numeric_limits<int64_t>::max());
return a*b;
}
```
this does require knowing the bit-width at compile though (so is difficult with the templated `rational`) and has to handle corner cases.
--
Ticket URL: https://bitbucket.org/einsteintoolkit/tickets/issues/2925/overflow-in-rat-in-arith
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.einsteintoolkit.org/pipermail/trac/attachments/20260326/c2243592/attachment.htm>
More information about the Trac
mailing list