2

Division with boost::multiprecision::cpp_dec_float have some kind of rounding error, as follows:

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

using my_t = boost::multiprecision::number<boost::multiprecision::cpp_dec_float<20, std::int32_t>>;

int main()
{
    my_t a = 150;
    my_t b = 300;
    my_t c = a / b;
    std::cout << c.str() << std::endl;
    std::cout << ((c==my_t(0.5))?"==":"!=") << std::endl;
    return 0;
}

Output:

0.5000000000000000000000000000000000000000136852
!=

Is this expected?

Are there other types which are more appropriate, considering a really need the decimal value?

Am i expected to truncate or round to a magical number of decimal digits?

Gabriel
  • 2,841
  • 4
  • 33
  • 43
  • 1
    N.B.: this is NOT a duplicate of "Is floating point math broken". – Sneftel Jul 17 '19 at 12:21
  • Why a single decimal digit? Note that 150 requires 7 bits binary significand while a single decimal digit probably allocates only 3 or 4 bits. See for example https://github.com/boostorg/multiprecision/issues/127 . Still, 300 should be rounded to exactly same significand as 150, and result should be exactly 0.5. I suspect that last digits output by str() are garbage, but source code is hard to follow... i recommend trying step by step thru debugger. – aka.nice Jul 17 '19 at 13:25
  • 1
    According to [boost docs](https://www.boost.org/doc/libs/1_66_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_dec_float.html) "*Operations involving cpp_dec_float are always truncating*" And also "*However, note that since their are guard digits in effect, in practice this has no real impact on accuracy for most use cases.*" You see this in your code: you set 20 digits and boost use 45. If you truncate to 20 digits you get the accuracy you wish. – Ripi2 Jul 23 '19 at 22:37

0 Answers0