双重比较给了我意想不到的结果。当我增加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
答案 0 :(得分:2)
原因是即使25.0 + Double.Epsilon
大于零,25.0
也会产生Double.Epsilon
。那是因为Double
是有限的。
您可以在此处找到更详细的解释:
Why does adding double.epsilon to a value result in the same value, perfectly equal?
除此之外,不要将Assert.AreSame
与值类型一起使用。如果您将Assert.AreSame
与值类型一起使用,则会将它们装箱。而是使用Assert.AreEqual
Assert.AreEqual(twentyfive, twentyfivePlusEpsilon)
相关:What's the difference between Assert.AreNotEqual and Assert.AreNotSame?