Incorrect result with cpp_dec_float division

94 views Asked by At

I'm having a problem with boost cpp_dec_float division producing wrong results.

#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>

int main()
{
   using namespace boost::multiprecision;
   using namespace std;

   cpp_dec_float_50 a = 15;  // exactly 5 * 3
   cpp_dec_float_50 b = 3;
   cpp_dec_float_50 c = a / b;  // should be exactly 5
   cpp_dec_float_50 d = 5;
   cout << setprecision(std::numeric_limits<cpp_dec_float_50>::max_digits10);
   cout << "c: " << c << endl;
   cout << "d: " << d << endl;
   cout << "c == d: " << (c == d ? "true" : "false") << endl;
   return 0;
}

This produces

c: 4.999999999999999999999999999999999999999999999999999999999999999999999995
d: 5
c == d: false

I saw this question which discusses it for a fractional result. While some comments there were trying to explain it as an effect of truncation, that was not convincing IMO.

And in my case, all values, including the result, are integers, so if there is a decimal arithmetic performed, no truncation should happen.

Any ideas to make boost produce the correct/expected results?

0

There are 0 answers