c# - 我应该如何比较这些 double 以获得所需的结果?

标签 c# .net comparison double precision

我在这里有一个简单的示例应用程序,我在其中乘以和添加 double 变量,然后将它们与预期结果进行比较。在这两种情况下,结果都等于预期结果,但当我进行比较时,它失败了。

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

这是输出:

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

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

我需要能够捕捉到在这两种情况下它实际上都是 True。我该怎么做?

最佳答案

float 通常不包含数学告诉我们的确切值,因为它们存储数字的方式不同。

为了仍然有一个可靠的比较,你需要允许一些差异:

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

请务必阅读 this blog post .

关于c# - 我应该如何比较这些 double 以获得所需的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18081222/

相关文章:

java - 相同的字符串比较给我错误

comparison - 如何在 Smalltalk 中比较集合

c# - 从 Azure Functions 中调用 HttpUtility

c# - NHibernate 哪个缓存用于 WinForms 应用程序

C# SQL Server CLR 函数 GET 和 POST 请求错误

.net - 将工作单元和存储库模式与 Entity Framework 结合使用的好处

c# - 当其内容为\0\0\0\0 时如何确定一个空字符串

c# - 如何比较两个 AssemblyName 实例?

string - Vba如何比较2列

c# - 如何从 ASP.NET MVC 中的数据库加载图像?