簡體   English   中英

使用 MPFR 時如何在 Boost Multiprecision 中設置舍入模式

[英]How to set rounding mode in Boost Multiprecision when using MPFR

我試圖弄清楚如何在 Boost Multiprecision 中使用舍入模式格式化 mpfr_float 數字。 在下面的示例中,我預計 1.55 會根據使用的舍入模式舍入為 1.5 或 1.6,但對於所有情況,它都會輸出 1.5。 如何在 Boost with MPFR 中實現這個簡單的功能?

#include <iostream>
#include <boost/multiprecision/mpfr.hpp>

void setRoundingMode(boost::multiprecision::mpfr_float m, mpfr_rnd_t r)
{
    mpfr_t tmp;
    mpfr_init(tmp);
    mpfr_set(tmp, m.backend().data(), r);
    mpfr_clear(tmp);
}

int main()
{
    using namespace boost::multiprecision;
    using std::cout;
    using std::endl;
    using std::setprecision;

    mpfr_float::default_precision(50);
    mpfr_float a("1.55");

    setRoundingMode(a, MPFR_RNDN); /* round to nearest, with ties to even */
    cout << setprecision(2) << a << endl;

    setRoundingMode(a, MPFR_RNDZ); /* round toward zero */
    cout << setprecision(2) << a << endl;

    setRoundingMode(a, MPFR_RNDU); /* round toward +Inf */
    cout << setprecision(2) << a << endl;

    setRoundingMode(a, MPFR_RNDD); /* round toward -Inf */
    cout << setprecision(2) << a << endl;

    setRoundingMode(a, MPFR_RNDA); /* round away from zero */
    cout << setprecision(2) << a << endl;

    setRoundingMode(a, MPFR_RNDF); /* faithful rounding */
    cout << setprecision(2) << a << endl;

    setRoundingMode(a, MPFR_RNDNA); /* round to nearest, with ties away from zero (mpfr_round) */
    cout << setprecision(2) << a << endl;

    return 0;
}

文檔說:

所有轉換均由底層 MPFR 庫執行

但是 mpfr 浮動后端的文檔指出:

使用這種類型時你應該知道的事情:

  • 默認構造的 mpfr_float_backend 設置為零(請注意,這不是默認的 MPFR 行為)。
  • 所有操作都使用四舍五入到最近

(強調我的)

我發現 MPFR 沒有全局默認舍入覆蓋,因此只有特定操作(賦值和精度更改)需要mpfr_rnd_t

您意識到了這一點,因此您的:

void setRoundingMode(boost::multiprecision::mpfr_float m, mpfr_rnd_t r)
{
    mpfr_t tmp;
    mpfr_init(tmp);
    mpfr_set(tmp, m.backend().data(), r);
    mpfr_clear(tmp);
}

但是,這不會“設置”“RoundingMode”。 相反,它將一個值復制到一個臨時值,如果需要,使用該舍入模式,然后忘記臨時值。

那是......沒有有效地做任何事情。

所以...

IO 是如何工作的?

operator<<調用:

template <class Backend, expression_template_option ExpressionTemplates>
inline std::ostream& operator<<(std::ostream& os, const number<Backend, ExpressionTemplates>& r)
{
   std::streamsize d  = os.precision();
   std::string     s  = r.str(d, os.flags());
   std::streamsize ss = os.width();
   if (ss > static_cast<std::streamsize>(s.size()))
   {
      char fill = os.fill();
      if ((os.flags() & std::ios_base::left) == std::ios_base::left)
         s.append(static_cast<std::string::size_type>(ss - s.size()), fill);
      else
         s.insert(static_cast<std::string::size_type>(0), static_cast<std::string::size_type>(ss - s.size()), fill);
   }
   return os << s;
}

到目前為止,一切都很好。 肉在

std::string     s  = r.str(d, os.flags());

str(...)實現從前端( number<> )中繼到后端,並最終做了(在很多不同的事情中):

 char* ps = mpfr_get_str(0, &e, 10, static_cast<std::size_t>(digits), m_data, GMP_RNDN);

因此,我們有它。 它只是硬編碼的。

如果您願意做出一些假設,您可以編寫自己的簡化 output 例程(見下文),但實際上我懷疑您是否非常關心舍入是否只是為了顯示。

假設性能不是主要問題(因為它是字符串 IO 無論如何,這很少或需要快速),我將假設能夠實際獲得四舍五入的數字有價值,因此您可以使用現有的圖書館設施。

什么是四舍五入,真的嗎?

MPFR 中的四舍五入並不是您認為的那樣:它不會四舍五入到小數位。 它在表示中四舍五入為二進制數字。

讓我們通過實現 MPFR 方式的舍入來證明這一點:

住在科利魯

#include <iostream>
#include <boost/multiprecision/mpfr.hpp>

namespace bmp = boost::multiprecision;

namespace detail {
    template <
        unsigned srcDigits10, bmp::mpfr_allocation_type srcAlloc,
        unsigned dstDigits10, bmp::mpfr_allocation_type dstAlloc
    >
    void round(
            bmp::mpfr_float_backend<srcDigits10, srcAlloc> const& src, 
            mpfr_rnd_t r,
            bmp::mpfr_float_backend<dstDigits10, dstAlloc>& dst)
    {
        mpfr_set(dst.data(), src.data(), r);
    }

    template <unsigned dstDigits10, unsigned srcDigits10, bmp::mpfr_allocation_type alloc>
    auto round(bmp::mpfr_float_backend<srcDigits10, alloc> const& src, mpfr_rnd_t r) {
        bmp::mpfr_float_backend<dstDigits10, alloc> dst;
        round(src, r, dst);
        return dst;
    }
}

template <unsigned dstDigits10, typename Number>
auto round(Number const& src, mpfr_rnd_t r) {
    auto dst = detail::round<dstDigits10>(src.backend(), r);
    return bmp::number<decltype(dst)>(dst);
}

int main() {
    using bmp::mpfr_float;
    mpfr_float::default_precision(50);
    mpfr_float const a("1.55");

    std::cout << std::setprecision(20) << std::fixed;

    for (mpfr_rnd_t r : {
             MPFR_RNDN, /* round to nearest, with ties to even */
             MPFR_RNDZ, /* round toward zero */
             MPFR_RNDU, /* round toward +Inf */
             MPFR_RNDD, /* round toward -Inf */
             MPFR_RNDA, /* round away from zero */
             MPFR_RNDF, /* faithful rounding */
             MPFR_RNDNA, /* round to nearest, with ties away from zero (mpfr_round) */
         })
    {
        std::cout << round<2>(a, r) << std::endl;
    }
}

印刷

1.54687500000000000000
1.54687500000000000000
1.55468750000000000000
1.54687500000000000000
1.55468750000000000000
1.55468750000000000000
1.55468750000000000000

那么,我們期待什么呢?

讓我們重新實現字符串化:

住在科利魯

#include <iostream>
#include <boost/multiprecision/mpfr.hpp>

namespace bmp = boost::multiprecision;

template <unsigned srcDigits10, bmp::mpfr_allocation_type alloc>
auto to_string(bmp::mpfr_float_backend<srcDigits10, alloc> const& src,
               unsigned digits, mpfr_rnd_t r, std::ios::fmtflags fmtflags) {
    std::streamsize org_digits(digits);
    std::string result;

    mpfr_exp_t e = 0;
    char* ps = mpfr_get_str(0, &e, 10, static_cast<std::size_t>(digits),
                            src.data(), r);
    --e; // To match with what our formatter expects.
    if (e != -1) {
        // Oops we actually need a different number of digits to what we asked
        // for:
        mpfr_free_str(ps);
        digits += e + 1;
        if (digits == 0) {
            // We need to get *all* the digits and then possibly round up,
            // we end up with either "0" or "1" as the result.
            ps = mpfr_get_str(0, &e, 10, 0, src.data(), r);
            --e;
            unsigned offset = *ps == '-' ? 1 : 0;
            if (ps[offset] > '5') {
                ++e;
                ps[offset] = '1';
                ps[offset + 1] = 0;
            } else if (ps[offset] == '5') {
                unsigned i = offset + 1;
                bool round_up = false;
                while (ps[i] != 0) {
                    if (ps[i] != '0') {
                        round_up = true;
                        break;
                    }
                    ++i;
                }
                if (round_up) {
                    ++e;
                    ps[offset] = '1';
                    ps[offset + 1] = 0;
                } else {
                    ps[offset] = '0';
                    ps[offset + 1] = 0;
                }
            } else {
                ps[offset] = '0';
                ps[offset + 1] = 0;
            }
        } else if (digits > 0) {
            mp_exp_t old_e = e;
            ps = mpfr_get_str(0, &e, 10, static_cast<std::size_t>(digits),
                              src.data(), r);
            --e; // To match with what our formatter expects.
            if (old_e > e) {
                // in some cases, when we ask for more digits of precision, it
                // will change the number of digits to the left of the decimal,
                // if that happens, account for it here. example: cout << fixed
                // << setprecision(3) << mpf_float_50("99.9809")
                digits -= old_e - e;
                ps = mpfr_get_str(0, &e, 10, static_cast<std::size_t>(digits),
                                  src.data(), r);
                --e; // To match with what our formatter expects.
            }
        } else {
            ps = mpfr_get_str(0, &e, 10, 1, src.data(), r);
            --e;
            unsigned offset = *ps == '-' ? 1 : 0;
            ps[offset] = '0';
            ps[offset + 1] = 0;
        }
    }
    result = ps ? ps : "0";
    if (ps)
        mpfr_free_str(ps);
    bmp::detail::format_float_string(result, e, org_digits, fmtflags,
                                     0 != mpfr_zero_p(src.data()));
    return result;
}

template <unsigned srcDigits10, bmp::mpfr_allocation_type alloc>
auto to_string(
    bmp::number<bmp::mpfr_float_backend<srcDigits10, alloc>> const& src,
    unsigned digits, mpfr_rnd_t r,
    std::ios::fmtflags fmtflags = std::ios::fixed) {
    return to_string(src.backend(), digits, r, fmtflags);
}

int main() {
    using bmp::mpfr_float;
    mpfr_float::default_precision(50);
    mpfr_float const a("1.55");

    std::cout << std::setprecision(20) << std::fixed;

    for (mpfr_rnd_t r : {
             MPFR_RNDN, /* round to nearest, with ties to even */
             MPFR_RNDZ, /* round toward zero */
             MPFR_RNDU, /* round toward +Inf */
             MPFR_RNDD, /* round toward -Inf */
             MPFR_RNDA, /* round away from zero */
             MPFR_RNDF, /* faithful rounding */
             MPFR_RNDNA, /* round to nearest, with ties away from zero (mpfr_round) */
         })
    {
        std::cout
            << " -- " << to_string(a, 2, r)
            << ", " << to_string(a, 1, r)
            << " -- "  <<  to_string(a, 2, r, std::ios::scientific)
            << ", "  <<  to_string(a, 1, r, std::ios::scientific) << std::endl;
    }
}

印刷

 -- 1.55, 1.5 -- 1.55e+00, 1.5e+00
 -- 1.54, 1.5 -- 1.54e+00, 1.5e+00
 -- 1.55, 1.6 -- 1.55e+00, 1.6e+00
 -- 1.54, 1.5 -- 1.54e+00, 1.5e+00
 -- 1.55, 1.6 -- 1.55e+00, 1.6e+00
 -- 1.55, 1.5 -- 1.55e+00, 1.5e+00
 -- 1.55, 1.5 -- 1.55e+00, 1.5e+00

免責聲明:我最初放棄了一些代碼以放棄科學記數法支持,所以事情可能不會 100% 達到標准。 此外,未使用次正態、無窮大、nan 進行測試。 YMMV

結束的想法

如果確實不是關於演示,而是對 memory 中的數字進行四舍五入,那么您可以從字符串表示中構造一個新的 mpfr_float。

在這種情況下,我的期望實際上是您首先想要一個十進制浮點數(例如cpp_dec_float )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM