Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point math going wrong using cpp_bin_float from boost::multiprecision

I tried the following:

#include <cmath>
#include <iostream>
#include <boost/multiprecision/cpp_bin_float.hpp>

using float256 = boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<192,
                  boost::multiprecision::backends::digit_base_2, void, long long int>, boost::multiprecision::et_off>;

void Test()
{
   double a = exp(-0.5);
   double b = boost::multiprecision::exp(float256(-0.5)).convert_to<double>();
   cout << a << endl << b << endl;
}

Unfortunately this doesn't work. I am getting 0.606531 for a but 1 for b.

I'm running: boost 1.58, Linux, gcc 5.4.0.

Any idea what I am doing wrong?

like image 869
Silicomancer Avatar asked Apr 28 '26 14:04

Silicomancer


1 Answers

This looks like a bug in boost. When the exponent template argument is a 64-bit integer type, the result of exp is rounded to an integer. This doesn't happen when int is used in place of long long int.

Edit: I have tracked the bug to the faulty implementation of floor and ceil functions. The offending line in both instances is:

if((arg.exponent() > (int)cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::max_exponent) || (shift <= 0))
//                    --- <=== !!!!

in include/boost/multiprecision/cpp_bin_float.hpp.

like image 93
n. 1.8e9-where's-my-share m. Avatar answered Apr 30 '26 07:04

n. 1.8e9-where's-my-share m.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!