双重比较失败
Double comparison failing
double 的比较给了我意想不到的结果。当我增加 0.0 的 Epsilon 时,我得到一个增加的值,当我增加 25.0 的 Epsilon 时,我得到恰好 25.0,而不是更多。如何增加最小双倍的 25.0 来触发比较?为什么使用 0.0 而不是 25.0?
<TestMethod()>
Public Sub Test()
Const epsilon As Double = Double.Epsilon
Const zero As Double = 0.0
Const zeroPlusEpsilon As Double = zero + epsilon
Const twentyfive As Double = 25.0
Const twentyfivePlusEpsilon As Double = twentyfive + epsilon
Assert.IsTrue(zero < zeroPlusEpsilon)
Assert.IsTrue(twentyfive < twentyfivePlusEpsilon) ' <-- This is failing.
End Sub
原因是即使 Double.Epsilon
大于零,25.0 + Double.Epsilon
也会产生 25.0
。那是因为 Double
是有限的。
您可以在这里找到更详细的解释:
Why does adding double.epsilon to a value result in the same value, perfectly equal?
除此之外,不要使用 Assert.AreSame
with value types. If you use Assert.AreSame
with value types they are boxed. Instead use Assert.AreEqual
Assert.AreEqual(twentyfive, twentyfivePlusEpsilon)
相关:What's the difference between Assert.AreNotEqual and Assert.AreNotSame?
double 的比较给了我意想不到的结果。当我增加 0.0 的 Epsilon 时,我得到一个增加的值,当我增加 25.0 的 Epsilon 时,我得到恰好 25.0,而不是更多。如何增加最小双倍的 25.0 来触发比较?为什么使用 0.0 而不是 25.0?
<TestMethod()>
Public Sub Test()
Const epsilon As Double = Double.Epsilon
Const zero As Double = 0.0
Const zeroPlusEpsilon As Double = zero + epsilon
Const twentyfive As Double = 25.0
Const twentyfivePlusEpsilon As Double = twentyfive + epsilon
Assert.IsTrue(zero < zeroPlusEpsilon)
Assert.IsTrue(twentyfive < twentyfivePlusEpsilon) ' <-- This is failing.
End Sub
原因是即使 Double.Epsilon
大于零,25.0 + Double.Epsilon
也会产生 25.0
。那是因为 Double
是有限的。
您可以在这里找到更详细的解释:
Why does adding double.epsilon to a value result in the same value, perfectly equal?
除此之外,不要使用 Assert.AreSame
with value types. If you use Assert.AreSame
with value types they are boxed. Instead use Assert.AreEqual
Assert.AreEqual(twentyfive, twentyfivePlusEpsilon)
相关:What's the difference between Assert.AreNotEqual and Assert.AreNotSame?