使用epsilon将double比较为零 [英] Compare double to zero using epsilon
问题描述
今天,我在寻找一些C ++代码(由别人写),并找到这一部分:
double someValue = ...
if(someValue< std :: numeric_limits< double> :: epsilon()&&
someValue> -std :: numeric_limits&
someValue = 0.0;
}
我试图找出这是否有意义。
epsilon()
的说明文件:
函数返回1和大于1的最小值之间的差值,可以用[double]表示。
这也适用于0,即 epsilon()
是大于0的最小值吗?或者是 0
和 0 + epsilon
之间的数字,可以用 double
?
如果没有,那么不等于 someValue == 0.0
?
假设64位IEEE双精度,有一个52位尾数和11位指数。查看以下数字:
1.0000 00000000 00000000 00000000 00000000 00000000 00000000×2 ^ 0 = 1
大于1的最小可表示数字:
1.0000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001×2 ^ 0 = 1 + 2 ^ -52
因此:
epsilon =(1 + 2 ^ -52) - 1 = 2 ^ -52
0和epsilon之间是否有任何数字?很多...最小正表示(正常)数是:
1.0000 00000000 00000000 00000000 00000000 00000000 00000000×2 ^ -1022 = 2 ^ 1022
其实有(1022 - 52 + 1)×2 ^ 52 = 4372995238176751616
0和epsilon之间的数字,约为所有可表示数字的正数的47%...
Today, I was looking through some C++ code (written by somebody else) and found this section:
double someValue = ...
if (someValue < std::numeric_limits<double>::epsilon() &&
someValue > -std::numeric_limits<double>::epsilon()) {
someValue = 0.0;
}
I'm trying to figure out whether this even makes sense.
The documentation for epsilon()
says:
The function returns the difference between 1 and the smallest value greater than 1 that is representable [by a double].
Does this apply to 0 as well, i.e. epsilon()
is the smallest value greater than 0? Or are there numbers between 0
and 0 + epsilon
that can be represented by a double
?
If not, then isn't the comparison equivalent to someValue == 0.0
?
Assuming 64-bit IEEE double, there is a 52-bit mantissa and 11-bit exponent. Look at the following numbers:
1.0000 00000000 00000000 00000000 00000000 00000000 00000000 × 2^0 = 1
The smallest representable number greater than 1:
1.0000 00000000 00000000 00000000 00000000 00000000 00000001 × 2^0 = 1 + 2^-52
Therefore:
epsilon = (1 + 2^-52) - 1 = 2^-52
Are there any numbers between 0 and epsilon? Plenty... E.g. the minimal positive representable (normal) number is:
1.0000 00000000 00000000 00000000 00000000 00000000 00000000 × 2^-1022 = 2^-1022
In fact there are about (1022 - 52 + 1)×2^52 = 4372995238176751616
numbers between 0 and epsilon, which is about 47% of all the positive representable numbers...
这篇关于使用epsilon将double比较为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!