首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >xunit.net - double[,]比较

xunit.net - double[,]比较
EN

Stack Overflow用户
提问于 2014-05-02 02:52:57
回答 1查看 1.6K关注 0票数 5

我的单元测试失败消息是:

代码语言:javascript
复制
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 }

我知道,如果比较双精度数字,则必须指定精度,因此我的解决方法是:

代码语言:javascript
复制
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);
    }
}

有没有更好、更简单的解决方案?

EN

回答 1

Stack Overflow用户

发布于 2017-05-16 21:56:57

来自XUnit代码库

代码语言:javascript
复制
/// <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)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23414477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档