5

正如Boost Multiprecision 库文档中所述,从 a 转换为 a 很boost::multiprecision::cpp_int简单boost::multiprecision::cpp_dec_float

// Some interconversions between number types are completely generic,
// and are always available, albeit the conversions are always explicit:

cpp_int cppi(2);
cpp_dec_float_50 df(cppi);    // OK, int to float // <-- But fails with cpp_dec_float<0>!

从 a 转换cpp_int为固定宽度浮点类型(即 a cpp_dec_float_50)的能力让人希望可以在库中从 a 转换cpp_int任意宽度的浮点类型 - 即 a cpp_dec_float<0>。但是,这不起作用;我在 Visual Studio 2013 中的转换失败,如以下简单示例程序所示:

#include <boost/multiprecision/number.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>

int main()
{
    boost::multiprecision::cpp_int n{ 0 };
    boost::multiprecision::cpp_dec_float<0> f{ n }; // Compile error in MSVC 2013
}

正如预期的那样,它确实成功转换为cpp_dec_float_50,但如前所述,我希望转换为任意精度的浮点类型:cpp_dec_float<0>.

错误出现在文件中内部 Boost Multiprecision 代码的以下代码片段中<boost/multiprecision/detail/default_ops.hpp>

template <class R, class T>
inline bool check_in_range(const T& t)
{
   // Can t fit in an R?
   if(std::numeric_limits<R>::is_specialized && std::numeric_limits<R>::is_bounded
      && (t > (std::numeric_limits<R>::max)()))
      return true;
   return false;
}

错误信息是:

错误 C2784: 'enable_if::result_type,detail::expression::result_type>,bool>::type boost::multiprecision::operator >(const boost::multiprecision::detail::expression &,const boost::multiprecision ::detail::expression &)' : 无法从 'const next_type' 推导出 'const boost::multiprecision::detail::expression &' 的模板参数

是否可以将 a 转换boost::multiprecision::cpp_int为 a boost::multiprecision::cpp_dec_float<0>(而不是转换为具有固定小数精度的浮点类型,如cpp_dec_float_50)?

(请注意,在我的程序中,任何时候都只实例化一个浮点数实例,并且不经常更新,所以我可以让这个实例占用大量内存并且需要很长时间才能真正支持巨大的数字。)

谢谢!

4

1 回答 1

6

我对 Boost Multiprecision 没有太多经验,但在我看来,模板类cpp_dec_float<>就是他们所说的backend,您需要将其包装在number<>适配器中才能将其用作算术类型。

这是我的看法:Live On Coliru

#include <boost/multiprecision/number.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>

namespace mp = boost::multiprecision;

int main()
{
    using Int = mp::cpp_int;

    // let's think of a nice large number
    Int n = 1;
    for (Int f = 42; f>0; --f)
        n *= f;

    std::cout << n << "\n\n"; // print it for vanity 

    // let's convert it to cpp_dec_float
    // and... do something with it
    using Dec = mp::number<mp::cpp_dec_float<0> >;
    std::cout << n.convert_to<Dec>();
}

输出:

1405006117752879898543142606244511569936384000000000

1.40501e+51

如果convert_to<>允许,那么显式转换构造函数也将起作用,我希望:

Dec decfloat(n);
于 2014-04-12T09:25:11.790 回答