如何使用 boost::multiprecision 更改运行时数字精度

how to change at runtime number precision with boost::multiprecision

我读过 boost::multiprecision documentation:

Depending upon the number type, precision may be arbitrarily large (limited only by available memory), fixed at compile time (for example 50 or 100 decimal digits), or a variable controlled at run-time by member functions. The types are expression-template-enabled for better performance than naive user-defined types.

我阅读了更多文档,但没有发现任何关于在运行时更改精度的信息。我只看到允许我在编译时设置精度的模板,这不是我想要的(我想创建一个使用非常高的缩放因子缩放分形的程序)。

如何创建允许我在运行时更改其精度的双精度类型?

大多数号码后端只有固定容量可选

还要注意一些后端(值得注意的是 cpp 后端)采用分配器,因此它们/隐式/根据需要增长(直到给定限制):

Normally cpp_bin_float allocates no memory: all of the space required for its digits are allocated directly within the class. As a result care should be taken not to use the class with too high a digit count as stack space requirements can grow out of control. If that represents a problem then providing an allocator as a template parameter causes cpp_bin_float to dynamically allocate the memory it needs

让我查看最流行后端的文档:

  • gmp 的 mpf_float 坚持这一点:

    typedef number<gmp_float<0> >     mpf_float;
    

    Type gmp_float can be used at fixed precision by specifying a non-zero Digits10 template parameter, or at variable precision by setting the template argument to zero.

    The typedef mpf_float provides a variable precision type whose precision can be controlled via the numbers member functions.

  • MPFR 后端类似:

    Type mpfr_float_backend can be used at fixed precision by specifying a non-zero Digits10 template parameter, or at variable precision by setting the template argument to zero.

    The typedef mpfr_float provides a variable precision type whose precision can be controlled via the numbers member functions.

动态精度用法示例:

// Operations at variable precision and no numeric_limits support:
mpfr_float a = 2;
mpfr_float::default_precision(1000);
std::cout << mpfr_float::default_precision() << std::endl;
std::cout << sqrt(a) << std::endl; // print root-2

它将留下 numeric_limits 未定义