Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Math.Abs(x) < double.Epsilon equivalent to Math.Abs(x) == 0d?

After a bit of light reading, this article piqued my interest:

I'd have thought that yes, the two statements are equivalent, given MSDN's statement:

Represents the smallest positive Double value that is greater than zero. This field is constant.

Curious to see what people think.

EDIT: Found a computer with VS on and ran this Test. Turns out that yes, as expected, they're equivalent.

    [Test]
    public void EpsilonTest()
    {
        Compare(0d);
        Compare(double.Epsilon);
        Compare(double.Epsilon * 0.5);
        Compare(double.NaN);
        Compare(double.PositiveInfinity);
        Compare(double.NegativeInfinity);
        Compare(double.MaxValue);
        Compare(double.MinValue);
    }

    public void Compare(double x)
    {
        Assert.AreEqual(Math.Abs(x) == 0d, Math.Abs(x) < double.Epsilon);
    }
like image 676
trilson86 Avatar asked Dec 07 '25 00:12

trilson86


1 Answers

IL code seems to cast some light on this.

Epsilon is simply a double number with the fraction part being 1, sign 0, exponent 0. Zero is a double number with the fraction part being 0, sign 0, exponent 0.

According to http://en.wikipedia.org/wiki/IEEE_754-1985, floating point numbers with the same sign and exponent are compared ordinally, which means that (x < 1) is the same as (x == 0).

Now, is it possible to get a zero that isn't fraction = 0, exponent = 0 (we don't care about sign, there's a Math.Abs in place)?

like image 190
Luaan Avatar answered Dec 08 '25 16:12

Luaan