1

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

bladzio
  • 414
  • 3
  • 15
  • `123456789.123456789` can't be represented in a binary form as seen in the decimal form. If you remove `* scalar` from your program, you see that it's rounded to `123456789.12345679104328155517578125`. – 273K Aug 05 '22 at 06:25
  • See https://www.boost.org/doc/libs/1_79_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html – Alan Birtles Aug 05 '22 at 06:29

2 Answers2

6

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"};
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
1

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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60