| 1 | // Copyright (c) 2018 Robert Ramey |
|---|---|
| 2 | // |
| 3 | // Distributed under the Boost Software License, Version 1.0. (See |
| 4 | // accompanying file LICENSE_1_0.txt or copy at |
| 5 | // http://www.boost.org/LICENSE_1_0.txt) |
| 6 | |
| 7 | #include <iostream> |
| 8 | #include <limits> |
| 9 | |
| 10 | #include <boost/rational.hpp> |
| 11 | #include <boost/safe_numerics/safe_integer.hpp> |
| 12 | |
| 13 | int main(int, const char *[]){ |
| 14 | // simple demo of rational library |
| 15 | const boost::rational<int> r {1, 2}; |
| 16 | std::cout << "r = "<< r << std::endl; |
| 17 | const boost::rational<int> q {-2, 4}; |
| 18 | std::cout << "q = "<< q << std::endl; |
| 19 | // display the product |
| 20 | std::cout << "r * q = "<< r * q << std::endl; |
| 21 | |
| 22 | // problem: rational doesn't handle integer overflow well |
| 23 | const boost::rational<int> c {1, INT_MAX}; |
| 24 | std::cout << "c = "<< c << std::endl; |
| 25 | const boost::rational<int> d {1, 2}; |
| 26 | std::cout << "d = "<< d << std::endl; |
| 27 | // display the product - wrong answer |
| 28 | std::cout << "c * d = "<< c * d << std::endl; |
| 29 | |
| 30 | // solution: use safe integer in rational definition |
| 31 | using safe_rational = boost::rational< |
| 32 | boost::safe_numerics::safe<int> |
| 33 | >; |
| 34 | |
| 35 | // use rationals created with safe_t |
| 36 | const safe_rational sc {1, std::numeric_limits<int>::max()}; |
| 37 | |
| 38 | std::cout << "c = "<< sc << std::endl; |
| 39 | const safe_rational sd {1, 2}; |
| 40 | std::cout << "d = "<< sd << std::endl; |
| 41 | std::cout << "c * d = "; |
| 42 | try { |
| 43 | // multiply them. This will overflow |
| 44 | std::cout << (sc * sd) << std::endl; |
| 45 | } |
| 46 | catch (std::exception const& e) { |
| 47 | // catch exception due to multiplication overflow |
| 48 | std::cout << e.what() << std::endl; |
| 49 | } |
| 50 | |
| 51 | return 0; |
| 52 | } |
| 53 |
