了解C语言中的双精度运算 [英] Understanding double precision operations in C
问题描述
我想了解为什么这段代码:
I would like to understand why this code:
double r,d,rc;
scanf("%lf %lf", &r, &d);
rc = (r * r) - (d/2) * (d/2);
printf("%.2f\n", M_PI * rc);
返回比此结果更精确的结果(没有分配rc
变量):
returns more precise result than this one (without rc
variable assignment):
double r,d,rc;
scanf("%lf %lf", &r, &d);
printf("%.2f\n", M_PI * (r * r) - (d/2) * (d/2));
另一个相关的问题:为什么n * n
比pow(n,2)
好?
Another, related, question: why is n * n
better than pow(n,2)
?
推荐答案
第一个代码示例计算:
M_PI * ((r * r) - (d/2) * (d/2));
第二个计算:
(M_PI * (r * r)) - (d/2) * (d/2);
在大多数编译器中,对pow(n, 2)
的调用与n * n
相同.将会发出完全相同程序集.这是由于称为强度降低"的优化而引起的-大多数pow()
实现将检查指数是否为2,并将该情况简化为一个乘法.未优化的版本稍微贵一点,因为它需要一个函数调用和一些分支.
A call to pow(n, 2)
is the same as n * n
, on most compilers. The exact same assembly will be emitted. This is due to an optimization called "strength reduction" -- most pow()
implementations will check to see if the exponent is 2, and reduce that case to a single multiplication. The unoptimized version is slightly more expensive since it requires a function call and some branching.
请注意,M_PI
不是C标准的一部分,因此您可以使用等效的代码,该代码可以编译为完全相同的代码:
Note that M_PI
is not part of the C standard, so you can use the equivalent, which compiles to the exact same code:
double M_PI = 4.0 * atan(1.0);
这篇关于了解C语言中的双精度运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!