cpp_bin_float truncates instead of rounding when converting from wide integers

Open
#775 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
55/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
cpp
Domain
backend

Research direction

Start with the two reproductions in the issue, then inspect the integer conversion in include/boost/multiprecision/cpp_bin_float.hpp and generic_interconvert in include/boost/multiprecision/detail/generic_interconvert.hpp. Check how wide integers are shifted and how limbs are accumulated, and validate that both conversions produce the correctly rounded values shown in the examples.

Written by the indexing model from the issue text.

Description

Against develop (8c5f883):

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

int main()
{
   using namespace boost::multiprecision;
   std::uint64_t u = (std::uint64_t(1) << 54) + 3;
   std::cout << cpp_int(cpp_bin_float_double(u)) << " vs " << std::uint64_t(double(u)) << "\n"; // 18014398509481984 vs 18014398509481988
   uint128_t v("8824422037211767488904697598367797768");
   std::cout << cpp_int(cpp_bin_float_quad(v)) << "\n"; // ...797248, correctly rounded is ...798272
}

Two causes: cpp_bin_float::operator=(const I&) right-shifts integers wider than the mantissa, and the integer-to-float generic_interconvert rounds once per limb it adds (so wide cpp_int values are also off).

Proposed patch
diff --git a/include/boost/multiprecision/cpp_bin_float.hpp b/include/boost/multiprecision/cpp_bin_float.hpp
--- a/include/boost/multiprecision/cpp_bin_float.hpp
+++ b/include/boost/multiprecision/cpp_bin_float.hpp
@@ -571,8 +571,30 @@ class cpp_bin_float
          }
          else if (shift >= bit_count)
          {
-            m_exponent = static_cast<Exponent>(shift);
-            m_data     = static_cast<ar_type>(fi >> (shift + 1 - bit_count));
+            // Round to nearest, ties to even:
+            std::size_t drop = shift + 1 - bit_count;
+            ui_type     half = static_cast<ui_type>(static_cast<ui_type>(1u) << (drop - 1));
+            ui_type     rem  = static_cast<ui_type>(fi & static_cast<ui_type>(half + half - 1u));
+            fi               = static_cast<ui_type>(fi >> drop);
+            if ((rem > half) || ((rem == half) && (fi & 1u)))
+            {
+               ++fi;
+               if (msb(fi) >= bit_count)
+               {
+                  fi >>= 1u;
+                  ++shift;
+               }
+            }
+            if (shift > max_exponent)
+            {
+               m_exponent = exponent_infinity;
+               m_data     = static_cast<limb_type>(0);
+            }
+            else
+            {
+               m_exponent = static_cast<Exponent>(shift);
+               m_data     = static_cast<ar_type>(fi);
+            }
          }
          else
          {
diff --git a/include/boost/multiprecision/detail/generic_interconvert.hpp b/include/boost/multiprecision/detail/generic_interconvert.hpp
--- a/include/boost/multiprecision/detail/generic_interconvert.hpp
+++ b/include/boost/multiprecision/detail/generic_interconvert.hpp
@@ -13,6 +13,7 @@
 #include <boost/multiprecision/detail/no_exceptions_support.hpp>
 #include <boost/multiprecision/detail/assert.hpp>
 #include <boost/multiprecision/detail/functions/trunc.hpp>
+#include <boost/multiprecision/traits/is_variable_precision.hpp>
 
 #ifdef BOOST_MSVC
 #pragma warning(push)
@@ -36,11 +37,15 @@ template <class To, class From>
 void generic_interconvert(To& to, const From& from, const std::integral_constant<int, number_kind_floating_point>& /*to_type*/, const std::integral_constant<int, number_kind_integer>& /*from_type*/)
 {
    using default_ops::eval_add;
+   using default_ops::eval_bit_test;
    using default_ops::eval_bitwise_and;
    using default_ops::eval_convert_to;
    using default_ops::eval_get_sign;
+   using default_ops::eval_increment;
    using default_ops::eval_is_zero;
    using default_ops::eval_ldexp;
+   using default_ops::eval_lsb;
+   using default_ops::eval_msb;
    using default_ops::eval_right_shift;
    // smallest unsigned type handled natively by "From" is likely to be it's limb_type:
    using l_limb_type = typename canonical<unsigned char, From>::type;
@@ -50,6 +55,23 @@ void generic_interconvert(To& to, const From& from, const std::integral_constant
    bool                                              is_neg = eval_get_sign(t) < 0;
    if (is_neg)
       t.negate();
+   //
+   // If "t" has more bits than "To", adding up the limbs below rounds more than once,
+   // so round to nearest (ties to even) first, then the sum is exact:
+   //
+   std::ptrdiff_t drop = 0;
+   if (std::numeric_limits<number<To> >::is_specialized && (std::numeric_limits<number<To> >::radix == 2) && !is_variable_precision<number<To> >::value && !eval_is_zero(t))
+   {
+      drop = static_cast<std::ptrdiff_t>(eval_msb(t)) + 1 - std::numeric_limits<number<To> >::digits;
+      if (drop > 0)
+      {
+         bool half   = eval_bit_test(t, static_cast<std::size_t>(drop - 1));
+         bool sticky = half && (static_cast<std::ptrdiff_t>(eval_lsb(t)) < drop - 1);
+         eval_right_shift(t, static_cast<std::size_t>(drop));
+         if (half && (sticky || eval_bit_test(t, 0)))
+            eval_increment(t);
+      }
+   }
    // Pick off the first limb:
    l_limb_type limb;
    l_limb_type mask = static_cast<l_limb_type>(~static_cast<l_limb_type>(0));
@@ -73,6 +95,8 @@ void generic_interconvert(To& to, const From& from, const std::integral_constant
       eval_add(to, l);
       shift += std::numeric_limits<l_limb_type>::digits;
    }
+   if (drop > 0)
+      eval_ldexp(to, to, drop);
    //
    // Finish off by setting the sign:
    //
Dominant language
C++
Stars
268
Forks
130
Avg merge
1d 15h
Merged PRs (30d)
2

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from boostorg/multiprecision

All issues in boostorg/multiprecision

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.