Home > Back-end >  Precision rounding problem with boost multiprecision
Precision rounding problem with boost multiprecision

Time:08-06

I want to multiply number 123456789.123456789 by 1000000000.0 and as a result of this operation I expect 123456789123456789 as int or float 123456789123456789.0, but I got:

res: 123456789123456791.04328155517578125
int_res: 123456789123456791

Should I do it in other way ?

#include <iostream>

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

namespace bmp = boost::multiprecision;

int main() 
{
    bmp::cpp_dec_float_100 scalar{1000000000.0};
    bmp::cpp_dec_float_100 a{123456789.123456789};
    bmp::cpp_dec_float_100 res = a * scalar;    
    bmp::cpp_int int_res = res.convert_to<bmp::cpp_int>();
    std::cout << "    res: " << res.str() << std::endl;
    std::cout << "int_res: " << int_res.str() << std::endl;
    return 0;
}

Code: https://wandbox.org/permlink/xB8yBWuzzGvQugg7

CodePudding user response:

See https://www.boost.org/doc/libs/1_79_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html.

You are initialising a with a double literal. 123456789.123456789 can't be represented by a double so you get the closest approximation which is 123456789.12345679104328155517578125. If you want to initialise precisely use a string literal instead:

bmp::cpp_dec_float_100 a{"123456789.123456789"};

CodePudding user response:

You are using the double literal to initialise a which can't give you the value you want for the obvious reason, use String literal instead, it will be good to go.

  • Related