creating math constants of variable precision using Boost mpfr_float, such as pi or e
Asked Answered
H

1

0

I am using Boost.Multiprecision for wrappers around the mpfr backend, and I am having some trouble creating pi (and e or any other math constant) to my desired precision. I feel like what I want to do should be possible, because of the use of Boost.Math for constants on a tutorial page for Boost.Multiprecision. In the tutorial, they use fixed-precision numbers of types such as cpp_dec_float_50 -- I want to do it with variable_precision mpfr_float. Check out the following code:

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

...
int main() {
    boost::multiprecision::mpfr_float::default_precision(1000);
    boost::multiprecision::mpfr_float pi = boost::math::constants::pi<boost::multiprecision::mpfr_float>();
    std::cout << std::fixed;
    std::cout.precision(1000);
    std::cout << pi.precision() << " " << pi << std::endl;
}

The result is a number, pi, which has precision 1000, but only has ~165 digits of pi, as evidenced by the result of the output statements, which confirm that my pi is of precision 1000, and prints about 165 correct digits, and ~835 zeros. this is clearly wrong.

is it possible to make a boost::multiprecision::mpfr_float at high precision populated with constants from boost::math::constants?

Note that I need to use a variable precision type, and that other high-but-fixed-precision types are not an option. I must be able to change precision on the fly at runtime.

Hullda answered 13/2, 2015 at 3:2 Comment(0)
G
2

The constants embedded in the Boost headers have a limited precision, and you've hit that limit. If you need a higher-precision version of pi (for instance), you'll need to bring it yourself.

For instance, the definition of boost::math::constants::pi in the headers is:

  BOOST_DEFINE_MATH_CONSTANT(pi, 3.141592653589793238462643383279502884e+00, "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651e+00")

https://github.com/boostorg/math/blob/master/include/boost/math/constants/constants.hpp

(This definition only gives 110 digits past the decimal place, by the way. Any digits you're getting beyond that are likely to be incorrect!)

Ginsburg answered 13/2, 2015 at 3:12 Comment(1)
this does indeed solve my problem, and points to misleading information in the boost tutorial documentation, which naively leads me to believe that if I were using a long fixed-precision number, i would be able to fully populate it with those constants... thanks for referencing the documentation. do you think this merits a filing bugreport with boost? or is this solely up to me?Hullda

© 2022 - 2024 — McMap. All rights reserved.