Search code examples
c++boostmultiprecisionboost-multiprecision

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


I've read from the 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.

I've read some more documentation but I've not found anything regarding changing precision at runtime. I've seen only templates that allows me to set precision at compile time, that's not what I want (I want to create a program for zooming fractals using very high zoom factor).

How can I create a double type that allows me to change its precision at runtime?


Solution

  • 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