gpt4 book ai didi

unit-testing - xunit.net - double[,] 比较

转载 作者:行者123 更新时间:2023-12-04 04:24:27 25 4
gpt4 key购买 nike

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

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 }

我知道如果你比较 double 数,你必须指定精度,所以我的解决方法是:
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);
}
}

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

最佳答案

来自 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)

关于unit-testing - xunit.net - double[,] 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23414477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com