Boost logo

Boost Users :

Subject: Re: [Boost-users] boost::rational does not maintain its invariant in case of overflow
From: Robert Ramey (ramey_at_[hidden])
Date: 2018-04-11 14:28:42


On 4/11/18 6:11 AM, Frédéric via Boost-users wrote:
> With the program shown below, I obtained the following output:
> std::numeric_limits<long>::max() == 9223372036854775807
> r == boost::rational<long>(4294967296, 1853020188851841) ==
> 4294967296/1853020188851841
> r * r == 0/8733086111712066817
>
> Clearly there are 2 overflows but this leads to the invariant of the
> class not being maintained, i.e. the faction is not simplified to 0/1
> (gcd(num, den) != 1).
>
> F
>
> #include <boost/rational.hpp>
>
> #include <iostream>
>
> int main() {
> std::cout << "std::numeric_limits<long>::max() == "
> << std::numeric_limits<long>::max() << '\n';
> boost::rational<long> r(4294967296, 1853020188851841);
> std::cout << "r == boost::rational<long>(4294967296, 1853020188851841) == "
> << r << '\n';
> std::cout << "r * r == " << (r * r) << '\n';
> return 0;
> }
>

safe_numerics can address this.

Robert Ramey


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net