cpp_bin_float truncates instead of rounding when converting from wide integers

オープン
#775 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
55/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
cpp
領域
backend

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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:
    //
主要言語
C++
スター
268
フォーク
130
平均マージ
1日 15時間
マージ済み PR(30日)
2

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

boostorg/multiprecision のほかの issue

boostorg/multiprecision の issue をすべて見る

似ている issue

C++ の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。