我应该如何比较这双打,以获得期望的结果? [英] How should I compare these doubles to get the desired result?

查看:134
本文介绍了我应该如何比较这双打,以获得期望的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的示例应用程序,在这里我在哪里倍增并添加变量,然后对预期的结果进行比较他们。在这两种情况下,结果等于预期的结果然而,当我这样做是失败的比较。

I have a simple example application here where I am multiplying and adding double variables and then comparing them against an expected result. In both cases the result is equal to the expected result yet when I do the comparison it fails.

static void Main(string[] args)
{
    double a = 98.1;
    double b = 107.7;
    double c = 92.5;
    double d = 96.5;

    double expectedResult = 88.5;
    double result1 = (1*2*a) + (-1*1*b);
    double result2 = (1*2*c) + (-1*1*d);            

    Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", a, b, result1, expectedResult == result1));
    Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", c, d, result2, expectedResult == result2));

    Console.Read();
}

这里是输出:

And here is the output:

2x98.1 - 107.7 = 88.5
Equal to 88.5? False

2x92.5 - 96.5 = 88.5
Equal to 88.5? True

我需要能够捕捉到它是在这两种情况下实际上。我将如何做呢?

推荐答案

浮点数通常不包含数学告诉,因为他们是如何存储的数字我们,确切的价值。

Floating point numbers often don't contain the exact value that mathematics tells us, because of how they store numbers.

要仍然有一个可靠的比较,你需要让一些区别:

To still have a reliable comparison, you need to allow some difference:

private const double DoubleEpsilon = 2.22044604925031E-16;

/// <summary>Determines whether <paramref name="value1"/> is very close to <paramref name="value2"/>.</summary>
/// <param name="value1">The value1.</param>
/// <param name="value2">The value2.</param>
/// <returns><c>true</c> if <paramref name="value1"/> is very close to value2; otherwise, <c>false</c>.</returns>
public static bool IsVeryCloseTo(this double value1, double value2)
{
    if (value1 == value2)
        return true;

    var tolerance = (Math.Abs(value1) + Math.Abs(value2)) * DoubleEpsilon;
    var difference = value1 - value2;

    return -tolerance < difference && tolerance > difference;
}

另外,请务必阅读这篇博客

这篇关于我应该如何比较这双打,以获得期望的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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