你能比较准确浮点值为零? [英] Can you compare floating point values exactly to zero?
问题描述
我知道我们使用无法比拟2浮点值==。我们只能比较它们是彼此的一些间隔范围内。
我知道
如果(VAL == 0.512)
是不对由于浮点计算和转换为二进制和
应
固有误差
如果(VAL在(0.512-ε,0.512 +小量))
不过是0特殊?我们可以准确地比较花车为0?甚至可以说是不正确的?特别是在C#和Java
双VAL = 0的情况下?;
VAL = GETVAL();
如果(VAL == 0)
尽管0有一个精确的表示,你不能依赖于使用花车计算的结果是完全0正如你指出,这是由于浮点运算和转换的问题。
所以,你应该测试0战胜你的宽容小量。
I know we can't compare 2 floating point values using ==. We can only compare they are within some interval of each other. I know
if(val == 0.512)
is wrong due to errors inherent in floating point calculations and conversion to binary and should be
if (val in (0.512-epsilon, 0.512+epsilon))
But is 0 special? Can we compare floats exactly to 0? Or even that is incorrect? Particularly in the context of C# and Java?
double val = 0;
val = getVal();
if(val == 0)
Even though 0 has an exact representation, you can't rely on the result of a calculation using floats to be exactly 0. As you noted, this is due to floating point calculation and conversion issues.
So, you should test for 0 against your tolerance epsilon.
这篇关于你能比较准确浮点值为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!