简体   繁体   中英

boost int 128 division to floating point number

I am new in boost. I have 128 bit integer (int128_t boost/multiprecision/cpp_int.hpp ) in my project, which I need to divide to floating point number. In my current platform I have limitation and can't use boost/multiprecision/float128.hpp . It's still not supported in clang now https://github.com/boostorg/math/issues/181

Is there any way to this with boost math lib?

Perhaps split the int128 into 64-bit numbers?

i128 = h64 * (1<<64) + l64 Then you could easily load those values shift and sum them on the 64bit floating point to get the equivalent number.

Or, as the floating point hardware is actually only 64 bit precision anyway, you could just shift down your int128 until it fits in 64 bit, cast that to float and then shift it back up, but the former may actually be faster because it is simpler.

Although you can't use float128 , Boost has several other implementations of long floating-point types:

  • cpp_bin_float
  • cpp_dec_float
  • gmp_float
  • mpfr_float

In particular, if you need binary high-precision floating-point type without dependencies on external libraries like GMP, you can use cpp_bin_float . Example:

#include <iomanip>
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>

int main()
{
    using LongFloat=boost::multiprecision::cpp_bin_float_quad;

    const auto x=boost::multiprecision::int128_t(1234123521);
    const auto y=LongFloat(34532.52346246234);
    const auto z=LongFloat(x)/y;
    std::cout << "Ratio: " << std::setprecision(10) << z << "\n";
}

Here we've used a built-in typedef for 113-bit floating-point number, which has the same precision and range as IEEE 754 binary128. You can choose other parameters for the precision and range, see the docs I've linked to above for details.

Note though, that int128_t has more precision than any kind of float128 , because some bits of the latter are used to store its exponent. If that's an issue, be sure to use higher precision.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM