C-浮点precision [英] 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 \n");
else
printf("f is NOT 1.0\n");
return 0;
}
它总是打印f不是1.0。我理解,这是涉及到浮点precision在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?
推荐答案
二进制浮点数不能重新present值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单precision,这大约是十进制 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-浮点precision的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!