Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c++ - Does C++11, 14, 17 or 20 introduce a standard constant for pi?

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.

I know that I can define pi myself as 4*atan(1) or acos(-1) or double pi = 3.14;. Sure. But why do I still have to do it? How do standard math functions work without pi?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...