I know that you can use:
#define _USE_MATH_DEFINES
and then:
M_PI
to get the constant pi. However, if I remember correctly (comments welcome) this is compiler/platform dependent. So, what would be the most reliable way to use a pi constant that won't cause any problems when I port it from Linux to other systems?
I know that I could just define a float/double and then set it to a rounded pi value myself, but I'd really like to know if there is a designated mechanism.
Meeting C++ has an article on the different options for generating pi: C++ & π they discuss some of the options, from cmath, which is not platform independent:
and from boost:
and using atan, with constexpr removed since as SchighSchagh points out that is not platform independent:
I gathered all the methods into a live example:
The function below calculates pi without relying on any libraries at all.
Also, the type of its result is a template parameter.
Platform ueber-independence is stifled a bit because it only works with fixed-precision fractional types -- the calculated value needs to converge and remain constant over 2 iterations.
So if you specify some kind of arbitrary-precision rational or floating-point class which will automatically increase its precision as needed, a call to this function will not end well.