C- 浮点精度 [英] C- Floating point precision
问题描述
我有一个程序:
int main()
{
float f = 0.0f;
int i;
for (i = 0 ; i < 10 ; i++)
f = f + 0.1f;
if (f == 1.0f)
printf("f is 1.0
");
else
printf("f is NOT 1.0
");
return 0;
}
它总是打印 f is NOT 1.0
.我知道这与 C 中的浮点精度有关.但我不确定它到底在哪里搞砸了.有人可以解释一下为什么它不打印另一行吗?
It always prints f is NOT 1.0
. I understand this is related to floating point precision in C. But I am not sure exactly where it is getting messed up. Can someone please explain me why it is not printing the other line?
推荐答案
二进制浮点数不能准确表示值 0.1,因为它的二进制展开没有有限的位数(和十进制展开完全一样)1/7 没有).
Binary floating point cannot represent the value 0.1 exactly, because its binary expansion does not have a finite number of digits (in exactly the same way that the decimal expansion of 1/7 does not).
0.1的二进制展开是
0.000110011001100110011001100...
当截断为 IEEE-754 单精度时,这大约是十进制的 0.100000001490116119
.这意味着每次将接近 0.1"的值添加到变量时,都会累积一个小错误 - 因此最终值略高于 1.0
.
When truncated to IEEE-754 single precision, this is approximately 0.100000001490116119
in decimal. This means that each time you add the "nearly 0.1" value to your variable, you accumulate a small error - so the final value is slightly higher than 1.0
.
这篇关于C- 浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!