C ++如何避免浮点运算错误 [英] C++ How to avoid floating-point arithmetic error
问题描述
我正在写一个循环,它以浮点数递增,但是我遇到了一个浮点算术问题,如下例所示:
I am writing a loop that increments with a float, but I have come across a floating-point arithmetic issue illustrated in the following example:
for(float value = -2.0; value <= 2.0; value += 0.2)
std::cout << value << std::endl;
这是输出:
-2
-1.8
-1.6
-1.4
-1.2
-1
-0.8
-0.6
-0.4
-0.2
1.46031e-07
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
获取 1.46031e-07
而不是 0
?我知道这与浮点错误有关,但我不知道为什么它正在发生,我应该做什么,以防止这种情况发生(如果有一种方式)。有人可以解释(或指向我的链接),将帮助我理解吗?任何输入是赞赏。谢谢!
Why exactly am I getting 1.46031e-07
instead of 0
? I know this has something to do with floating-point errors, but I can't grasp why it is happening and what I should do to prevent this from happening (if there is a way). Can someone explain (or point me to a link) that will help me understand? Any input is appreciated. Thanks!
推荐答案
这是因为浮点数只具有一定的离散精度。
This is because floating point numbers have only a certain discrete precision.
0.2不是0.2,而是内部表示为稍微不同的数字。
The 0.2 is not really a 0.2, but is internally represented as a slightly different number.
这是为什么你看到一个差异。
That is why you are seeing a difference.
这在所有浮点计算中都很常见,你真的不能避免。
This is common in all floating point calculations, and you really can't avoid it.
这篇关于C ++如何避免浮点运算错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!