Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#9579 closed Bugs (fixed)

conversion error from boost cpp_rational to int

Reported by: W Randolph Franklin <boost@…> 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 j@…, 9 years ago

Component: rationalmultiprecision
Owner: changed from Jonathan Turkanis to John Maddock

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

comment:2 by anonymous, 9 years ago

I'm testing a proper fix, but the workaround would be to use:

cpp_int i = numerator(a) / denominator(a);

comment:3 by anonymous, 9 years ago

Thanks, am using that.

comment:4 by John Maddock, 9 years ago

Resolution: fixed
Status: newclosed

comment:5 by anonymous, 9 years ago

Thanks!

Note: See TracTickets for help on using tickets.