There is a rather silly problem with the number pi in C and C++. As far as I know M_PI
defined in math.h
is not required by any standard.
New C++ standards introduced a lot of complicated math in the standard library - hyperbolic functions, std::hermite
and std::cyl_bessel_i
, different random number generators and so on and so forth.
Did any of the 'new' standards bring in a constant for pi? If not - why? How does all this complicated math work without it?
I am aware of similar questions about pi in C++ (they are several years and standards old); I would like to know the current state of the problem.
I am also very interested in why oh why C++ still doesn't have a pi constant but has a lot of more complicated math.
UPD: I know that I can define pi myself as 4*atan(1) or acos(1) or double pi = 3.14. Sure. But why in 2018 do I still have to do it? How do standard math functions work without pi?
UPD2: According to this trip report for C++ Committee meeting in July 2019 in Cologne, proposal P0631 (math constants) was accepted into C++20. So it looks like at long last we will have number pi in the standard library!
Up to and including C++17 pi is not a constant introduced into the language, and it's a pain in the neck.
I'm fortunate in that I use boost and they define pi with a sufficiently large number of decimal places for even a 128 bit long double
.
If you don't use Boost then hardcode it yourself. Defining it with a trigonometric function is tempting but if you do that you can't then make it a constexpr
. The accuracy of the trigonometric functions is also not guaranteed by any standard I know of (cf. std::sqrt
), so really you are on dangerous ground indeed relying on such a function.
There is a way of getting a constexpr
value for pi using metaprogramming: see http://timmurphy.org/2013/06/27/template-metaprogramming-in-c/
From C++20 some good news. There is a defininition for pi. C++20 adds some mathematical constants in <numbers>
. For example std::numbers::pi
is a double
type.
Reference: https://en.cppreference.com/w/cpp/numeric/constants