是Math.Abs​​(x) double.Epsilon相当于Math.Abs​​(x)== 0d? [英] Is Math.Abs(x) < double.Epsilon equivalent to Math.Abs(x) == 0d?

查看:277
本文介绍了是Math.Abs​​(x) double.Epsilon相当于Math.Abs​​(x)== 0d?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一点点阅读,引发了我的兴趣:

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

我以为是的,两个语句是等价的,给出MSDN的声明:

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


表示大于零的最小正Double值。

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

很高兴看到人们的想法。

Curious to see what people think.

编辑:找到一台带VS的电脑,并运行这个测试。结果是,正如预期的那样,它们是等价的。

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);
    }


推荐答案

IL代码似乎投了一些

IL code seems to cast some light on this.

Epsilon只是一个双数字,分数部分是1,符号0,指数0.
零是一个双数,分数部分为0,符号0,指数0。

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.

根据 http://en.wikipedia.org/wiki/IEEE_754-1985 ,具有相同符号和指数的浮点数按顺序进行比较,这意味着(x <1)与(x == 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).

现在,可以得到一个零,不是fraction = 0,exponent = 0(我们不在乎符号,有一个Math.Abs​​到位)?

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)?

这篇关于是Math.Abs​​(x) double.Epsilon相当于Math.Abs​​(x)== 0d?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆