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

折月煮酒 提交于 2019-12-01 19:45:56

Most of the number backends have a fixed capacity only optionally.

Also note some backends (notable the cpp ones) take an allocator, so they /implicitly/ grow as required (until the given limit):

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

Let me check the documentation for the most popular backends:

  • gmp's mpf_float adheres to this:

    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.

  • Similar for MPFR backends:

    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.

A sample of the dynamic precision usage:

// 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

It will leave numeric_limits undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!