我想在一些c++程序中使用PI常数和三角函数。我得到三角函数包含<math。h>。然而,在这个头文件中似乎没有PI的定义。

如何获得PI而不手动定义它?


当前回答

我会这么做

template<typename T>
T const pi = std::acos(-T(1));

or

template<typename T>
T const pi = std::arg(-std::log(T(2)));

我不会把π输入到你需要的精度。这到底是什么意思?你需要的精度是T的精度,但是我们对T一无所知。

你可能会说:What are You talking about?T是float, double或long double。因此,只需输入long double的精度,即。

template<typename T>
T const pi = static_cast<T>(/* long double precision π */);

但是你真的知道在未来的标准中不会有比long double精度更高的新的浮点类型吗?你不。

这就是为什么第一个解很漂亮。可以肯定的是,这个标准将会使三角函数过载而产生一种新的类型。

请不要说三角函数在初始化时的计算是性能损失。

其他回答

我从大学(也许是高中)就开始背圆周率到11位,所以这一直是我的首选方法:

#ifndef PI
#define PI 3.14159265359
#endif

Pi可计算为atan(1)*4。您可以这样计算值并缓存它。

标准c++没有圆周率的常数。

许多c++编译器在cmath中定义M_PI(或在math.h中定义C)作为一个非标准扩展。在看到它之前,您可能必须#define _use_math_definitions。

在windows (cygwin + g++)上,我发现有必要添加标记-D_XOPEN_SOURCE=500,以便预处理程序处理math.h中M_PI的定义。

来自math.h的Posix手册页:

   The  <math.h>  header  shall  provide for the following constants.  The
   values are of type double and are accurate within the precision of  the
   double type.

   M_PI   Value of pi

   M_PI_2 Value of pi/2

   M_PI_4 Value of pi/4

   M_1_PI Value of 1/pi

   M_2_PI Value of 2/pi

   M_2_SQRTPI
          Value of 2/ sqrt pi