简体   繁体   English

xunit.net - double [,]比较

[英]xunit.net - double[,] comparison

My unit test fail message was: 我的单元测试失败消息是:

Result Message: 
Assert.Equal() Failure
Position: First difference is at position 0
Expected: Double[,] { 0,888888888888889, 1,33333333333333, 1,33333333333333, 2,66666666666667 }
Actual:   Double[,] { 0,888888888888889, 1,33333333333333, 1,33333333333333, 2,66666666666667 }

I know that if you compare double numbers you must specify precision, so my workaround is: 我知道如果你比较双数,你必须指定精度,所以我的解决方法是:

Assert.Equal(_sA.ToArray(), result.ToArray(), new Comparer());

class Comparer : IEqualityComparer<double[,]>
{
    public bool Equals(double[,] x, double[,] y)
    {
        if (x.GetLength(0) != y.GetLength(0) || x.GetLength(1) != y.GetLength(1))
            return false;

        for (var i = 0; i < x.GetLength(0); ++i)
        {
            for(var j = 0; j < x.GetLength(1); ++j)
            if (!isEqual(x[i, j], y[i, j]))
                return false;
        }

        return true;
    }

    private bool isEqual(double x, double y)
    {
      const double epsilon = 1e-5;
      return Math.Abs(x - y) <= epsilon * Math.Abs(x);
    }
}

Is there any better, simpler solution? 有没有更好,更简单的解决方案?

From XUnit codebase 来自XUnit代码库

/// <summary>
/// Verifies that two <see cref="T:System.Double" /> values are equal, within the number of decimal
/// places given by <paramref name="precision" />.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="precision">The number of decimal places (valid values: 0-15)</param>
/// <exception cref="T:Xunit.Sdk.EqualException">Thrown when the values are not equal</exception>
public static void Equal(double expected, double actual, int precision)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM