#9579 closed Bugs (fixed)
conversion error from boost cpp_rational to int
| Reported by: | Owned by: | John Maddock | |
|---|---|---|---|
| Milestone: | To Be Determined | Component: | multiprecision | 
| Version: | Boost 1.55.0 | Severity: | Problem | 
| Keywords: | cpp_rational conversion | Cc: | 
Description
boost cpp_rational seems to convert wrong to int when the numerator and denominator have many digits.
 #include <iostream>  #include <boost/multiprecision/cpp_int.hpp>
 using namespace boost::multiprecision;
 using namespace std;
 int main() {
  cpp_rational a("4561231231235/123123123123");
  std::cout << "bad convert: " << a << ' '  << 
     float(a) << ' ' << int(a) << ' ' << 
     a.convert_to<int>() << endl;
  a = (cpp_rational)"456/123";
  std::cout << "good convert: " << a << ' '  <<
     float(a) << ' ' << int(a) << ' ' << 
     a.convert_to<int>() << endl;
 }
The output is:
bad convert: 651604461605/17589017589 37.0461 -3 -3 good convert: 152/41 3.70732 3 3
Also, attempts to convert cpp_rational to cpp_int fail to compile, e.g., using
cpp_int b = static_cast<cpp_int> (a); cpp_int b = a.convert_to<cpp_int>();
What I want to happen is to divide and round down and never get it wrong even close to an int.
Help? Thanks.
Change History (5)
comment:1 by , 9 years ago
| Component: | rational → multiprecision | 
|---|---|
| Owner: | changed from to | 
comment:2 by , 9 years ago
I'm testing a proper fix, but the workaround would be to use:
cpp_int i = numerator(a) / denominator(a);
comment:4 by , 9 years ago
| Resolution: | → fixed | 
|---|---|
| Status: | new → closed | 
The fix has gone into Git develop: https://github.com/boostorg/multiprecision/commit/9a05e24994e268035184df35643b690c1c749cdc
  Note:
 See   TracTickets
 for help on using tickets.
    

I think you have selected the wrong component. I am going to change it to multiprecision.