for循环在C ++中使用double break out一个步骤,边界值未达到 [英] For-loop in C++ using double breaking out one step early, boundary value not reached
问题描述
我有一个简单的C ++程序使用gcc 4.2.4在32位Ubuntu 8.04上编译。它有一个 for
-loop,其中 double
变量从零增加到一个具有一定步长的变量。当步长 0.1
时,行为是我预期的。但是当步长为0.05时,循环在 0.95
后退出。任何人都可以告诉我为什么会发生这种情况?输出遵循以下源代码。
#include< iostream>
using namespace std;
int main()
{
double rangeMin = 0.0;
double rangeMax = 1.0;
double stepSize = 0.1;
for(double index = rangeMin; index< = rangeMax; index + = stepSize)
{
cout<索引<< endl;
}
cout<< endl;
stepSize = 0.05;
for(double index = rangeMin; index< = rangeMax; index + = stepSize)
{
cout<索引<< endl;
}
return 0;
}
OUTPUT
sarva @ savija-dev:〜/ code / scratch $ ./a.out
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
sarva @ savija-dev:〜/ code / scratch $
解决方案使用浮点值时,可表示,
0.95 + 0.05> 1 ,因为
0.95
不能由double
值表示。
查看维基百科对浮点精确度的说明。
如果您看一下 IEEE浮点转换器,您会看到64位浮点数的值
0.95
(double
)0-01111111110-11100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110
,请输入浮点计算器,您得到的值是0.95000016
并添加0.05
1.0
这就是为什么你不应该在循环中使用浮点数
I have a simple C++ program compiled using gcc 4.2.4 on 32-bit Ubuntu 8.04. It has a
for
-loop in which adouble
variable is incremented from zero to one with a certain step size. When the step size is0.1
, the behavior is what I expected. But when the step size is '0.05', the loop exits after0.95
. Can anyone tell me why this is happening? The output follows the source code below.#include <iostream> using namespace std; int main() { double rangeMin = 0.0; double rangeMax = 1.0; double stepSize = 0.1; for (double index = rangeMin; index <= rangeMax; index+= stepSize) { cout << index << endl; } cout << endl; stepSize = 0.05; for (double index = rangeMin; index <= rangeMax; index+= stepSize) { cout << index << endl; } return 0; }
OUTPUT
sarva@savija-dev:~/code/scratch$ ./a.out 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 sarva@savija-dev:~/code/scratch$
解决方案When using floating point values not every value is exactly representable,
0.95+0.05 > 1
because0.95
is not exactly representable by adouble
value.See what Wikipedia has to say about floating point accuracy.
If you look at the IEEE floating point converter you'll see that the value of
0.95
in 64 bit floating point (double
) is0-01111111110-1110011001100110011001100110011001100110011001100110
by entering this in a floating point calculator you get the value is0.95000016
and adding0.05
to that takes you over the1.0
mark.This is why you should never use floating points in loops (or more generally compare the result of floating point calculation to an exact value).
这篇关于for循环在C ++中使用double break out一个步骤,边界值未达到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!