Best pi independent constant?

I know you can use:

#define _USE_MATH_DEFINES 

and then:

 M_PI 

to get the constant pi. However, if I remember correctly (comments are welcome), it depends on the compiler / platform. So, what would be the most reliable way to use the pi constant, which will not cause any problems when sending it from Linux to other systems?

I know that I could just define float / double and then set it to the rounded pi value, but I would really like to know if there is a designated mechanism.

+8
c ++ pi
source share
2 answers

Meeting C ++ contains an article on various options for generating pi: C ++ and ฯ€ , they discuss some of the options: cmath , which is not platform independent:

 double pi = M_PI; std::cout << pi << std::endl; 

and boost :

 std::cout << boost::math::constants::pi<double>() << std::endl 

and using atan as constexpr is removed as SchighSchagh indicates that it is not platform independent:

  double const_pi() { return std::atan(1)*4; } 

I collected all the methods in a live example :

 #include <iostream> #include <cmath> #include <boost/math/constants/constants.hpp> double piFunc() { return std::atan(1)*4; } int main() { double pi = M_PI; std::cout << pi << std::endl; std::cout << boost::math::constants::pi<double>() << std::endl ; std::cout << piFunc() << std::endl; } 
+9
source share

The function below computes pi without relying on any libraries.

In addition, the type of its result is a template parameter.

The ueber-independent platform is a little stifled because it only works with fractional types with fixed precision - the calculated value should converge and remain constant for 2 iterations.

So, if you specify a class of rational accuracy or a floating point of arbitrary precision, which will automatically increase its accuracy as necessary, the call to this function will not end well.

 #include <iostream> #include <iomanip> namespace golf { template <typename T> inline T calc_pi() { T sum=T(0), k8=T(0), fac=T(1); for(;;) { const T next = sum + fac*(T(4)/(k8+T(1))-T(2)/(k8+T(4))-T(1)/(k8+T(5))-T(1)/(k8+T(6))); if(sum == next) return sum; sum=next; fac /= T(16); k8 += T(8); } } static const auto PI = calc_pi<double>(); } int main() { std::cout << std::setprecision(16) << golf::PI << std::endl; return 0; } 
+2
source share

All Articles