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

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


当前回答

我不喜欢#定义,因为它们是零类型安全的简单文本替换。如果省略括号,它们也会在使用表达式时引起问题。

#define T_PI 2*PI

真的应该

#define T_PI (2*PI)

我目前对这个问题的解决方案是使用常量的硬编码值,例如my_constants.hxx

namespace Constants {
    constexpr double PI = 3.141... ;
}

但是我没有硬编码这些值(因为我也不喜欢这种方法),而是使用一个单独的Fortran程序来编写这个文件。我使用Fortran是因为它完全支持四精度(VisualStudio上的c++不支持),三角函数是c++的constexpr等价函数。 如。

real(8), parameter :: pi = 4*atan(1.0d0)

毫无疑问,其他语言也可以用来做同样的事情。

其他回答

我建议你只输入你需要的精度。这不会为您的执行增加计算时间,并且无需使用任何头文件或#define即可移植。计算acos或atan总是比使用预先计算的值更昂贵。

const double PI  =3.141592653589793238463;
const float  PI_F=3.14159265358979f;
#include <cmath>
const long double pi = acos(-1.L);

我在项目中使用了一个覆盖所有基础的公共头文件:

#define _USE_MATH_DEFINES
#include <cmath>

#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif

#ifndef M_PIl
#define M_PIl (3.14159265358979323846264338327950288)
#endif

另外,如果包含<cmath>,下面所有的编译器都定义了M_PI和M_PIl常量。不需要添加只有vc++才需要的#define _use_math_definitions。

x86 GCC 4.4+
ARM GCC 4.5+
x86 Clang 3.0+

一些优雅的解决方案。不过,我怀疑三角函数的精度是否等于类型的精度。对于那些喜欢编写常量值的人来说,这适用于g++:-

template<class T>
class X {
public:
            static constexpr T PI = (T) 3.14159265358979323846264338327950288419\
71693993751058209749445923078164062862089986280348253421170679821480865132823066\
47093844609550582231725359408128481117450284102701938521105559644622948954930381\
964428810975665933446128475648233786783165271201909145648566923460;
...
}

256十进制数字的精度应该足以用于任何未来的长长长双精度类型。如果需要更多信息,请访问https://www.piday.org/million/。

来自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