user4388177
user4388177

Reputation: 2613

Double comparison failing

The comparison of double is giving me unexpected results. When I increase 0.0 of Epsilon I get an increased value, when I increase 25.0 of Epsilon I get exactly 25.0, not more. How can I increase 25.0 of the minimum double to trigger the comparison? And why is working with 0.0 and not with 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

Upvotes: 1

Views: 124

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460098

The reason is that 25.0 + Double.Epsilon yields 25.0 even if Double.Epsilon is larger than zero. That is because Double is limited.

You find a more detailed explanation here:

Why does adding double.epsilon to a value result in the same value, perfectly equal?


Apart from that, don't use Assert.AreSame with value types. If you use Assert.AreSame with value types they are boxed. Instead use Assert.AreEqual

Assert.AreEqual(twentyfive, twentyfivePlusEpsilon) 

Related: What's the difference between Assert.AreNotEqual and Assert.AreNotSame?

Upvotes: 2

Related Questions