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

前端 未结 6 1223
失恋的感觉
失恋的感觉 2020-12-08 08:56

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.

N

6条回答
  •  一向
    一向 (楼主)
    2020-12-08 09:31

    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 . For example std::numbers::pi is a double type.

    Reference: https://en.cppreference.com/w/cpp/numeric/constants

提交回复
热议问题