c - PI 的定义很长

标签 c pi

我正在调试一些旧的 C 代码,它有一个定义 #define PI 3.14... 其中 ... 是大约 50 个其他数字。

这是为什么?我说我可以将数字减少到小数点后 16 位,但我的老板对我咆哮说其他数字是为了平台独立性和向前兼容性而存在的。但是会减慢程序速度吗?

最佳答案

不,这不会减慢程序速度,除非您运行在一个功率极低的 1MHz DSP 芯片上,该芯片必须在软件中进行浮点运算,而不是将其传递给专用 FPU。这意味着任何使用 float 据的数学运算都比仅使用整数运算要慢得多。

一般来说,如果程序中最耗时的部分正在快速连续地进行大量计算,而浮点计算特别慢,那么更高的精度只会导致速度变慢。在现代 CPU 上,通常情况并非如此,某些芯片可能会导致 80 周期停顿,例如浮点下溢。这类问题可能超出了这个问题的范围。

首先,最好使用 PI 的通用标准定义,例如在 C 标准头文件中,<math.h> , 它被定义为 #define M_PI 3.14159265358979323846 .如果您坚持,您可以继续手动定义它。

此外,C 中目前可用的最佳精度相当于大约 19 位数字。

According to Wikipedia, 80-bit "Intel" IEEE 754 extended-precision long double, which is 80 bits padded to 16 bytes in memory, has 64 bits mantissa, with no implicit bit, which gets you 19.26 decimal digits. This has been the almost universal standard for long double for ages, but recently things have started to change.

The newer 128-bit quad-precision format has 112 mantissa bits plus an implicit bit, which gets you 34 decimal digits. GCC implements this as the __float128 type and there is (if memory serves) a compiler option to set long double to it.

就我个人而言,如果我需要使用我们自己定义的圆周率,我会这样写:

#ifndef M_PI
#define PI 3.14159265358979323846264338327950288419716939937510
#else
#define PI M_PI
#endif

如果最新的 C 标准支持更广泛的浮点原始数据类型,则几乎可以保证数学库中的常量会更新以支持这一点。

引用资料

  1. 比 double 更精确的 float 据类型?,2014 年 3 月 13 日访问, <https://stackoverflow.com/questions/15659668/more-precise-floating-point-data-types-than-double>
  2. C 中的数学常量 PI 值,2014 年 3 月 13 日访问, <https://stackoverflow.com/questions/9912151/math-constant-pi-value-in-c>

关于c - PI 的定义很长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22392111/

相关文章:

python - 在 Raspberry PI 上将 Pi 计算到数百万个位置

C语言: if() with no else(): using braces fails

c++ - 关于数组指针的问题?

objective-c - C中的缓冲区(unsigned char *)连接

python - 为什么使用 Machin 公式计算 pi 的值会给出错误的值?

java - Math.(E|PI) 和 StrictMath 有什么区别?

对字符数组元素类型的混淆

c - 使用 getchar() 输入字符串

c++ - 用泰勒法 C++ 计算圆周率

c# - 计算第 N 个 Pi 数字