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

前端 未结 6 1227
失恋的感觉
失恋的感觉 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:19

    It is not obviously a good idea because there is no obvious type with which define pi that is universally applicable across domains.

    Pi is, of course, an irrational number so it cannot be correctly represented by any C++ type. You might argue that the natural approach, therefore, is to define it in the largest floating point type available. However, the size of the largest standard floating point type long double is not defined by the C++ standard so the value of the constant would vary between systems. Worse, for any program in which the working type was not this largest type, the definition of pi would be inappropriate since it would impose a performance cost on every use of pi.

    It is also trivial for any programmer to find the value of pi and define their own constant suitable for use, so it does not provide any great advantage to include it in the maths headers.

提交回复
热议问题