如何找出两个变量大致相等?

Dis*_*ive 30 c# .net-3.5

我正在编写单元测试来验证数据库中的计算,并且存在大量的舍入和截断以及有时候数字稍微偏离的东西.

在验证时,我发现很多时候事情会通过,但说它们会失败 - 例如,数字将为1而我将获得0.999999

我的意思是,我可以把所有东西都变成一个整数但是因为我使用了很多随机样本,最终我会得到这样的东西

10.5 10.4999999999

一个将圆到10,另一个将圆到11.

在需要大致正确的地方时,我该如何解决这个问题呢?

Mit*_*eat 53

定义容差值(又称'epsilon'或'delta'),例如0.00001,然后用于比较差异,如下所示:

if (Math.Abs(a - b) < delta)
{
   // Values are within specified tolerance of each other....
}
Run Code Online (Sandbox Code Playgroud)

你可以使用,Double.Epsilon但你必须使用倍增因子.

更好的是,编写一个扩展方法来做同样的事情.我们Assert.AreSimiliar(a,b)在单元测试中有类似的东西.

Microsoft的Assert.AreEqual()方法有一个带有delta的重载:public static void AreEqual(double expected, double actual, double delta)

NUnit还为其Assert.AreEqual()方法提供了重载,允许提供增量.


Ant*_*ram 17

您可以提供一个函数,其中包含两个值之间可接受差异的参数.例如

// close is good for horseshoes, hand grenades, nuclear weapons, and doubles
static bool CloseEnoughForMe(double value1, double value2, double acceptableDifference)
{
    return Math.Abs(value1 - value2) <= acceptableDifference; 
}
Run Code Online (Sandbox Code Playgroud)

然后打电话给它

double value1 = 24.5;
double value2 = 24.4999;

bool equalValues = CloseEnoughForMe(value1, value2, 0.001);
Run Code Online (Sandbox Code Playgroud)

如果你想稍微专业一点,你可以调用函数ApproximatelyEquals或类似的东西.

static bool ApproximatelyEquals(this double value1, double value2, double acceptableDifference)
Run Code Online (Sandbox Code Playgroud)

  • 我个人称之为"CloseEnoughForGovernmentWork()" (10认同)
  • +1表示正确答案,+1表示扩展名,-1表示不足以使用希腊字母.:-) (6认同)

use*_*954 10

我没有检查添加了哪个MS测试版但在v10.0.0.0中Assert.AreEqual方法有重载接受delta参数并进行近似比较的重载.

https://msdn.microsoft.com/en-us/library/ms243458(v=vs.140).aspx

//
// Summary:
//     Verifies that two specified doubles are equal, or within the specified accuracy
//     of each other. The assertion fails if they are not within the specified accuracy
//     of each other.
//
// Parameters:
//   expected:
//     The first double to compare. This is the double the unit test expects.
//
//   actual:
//     The second double to compare. This is the double the unit test produced.
//
//   delta:
//     The required accuracy. The assertion will fail only if expected is different
//     from actual by more than delta.
//
// Exceptions:
//   Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException:
//     expected is different from actual by more than delta.
public static void AreEqual(double expected, double actual, double delta);
Run Code Online (Sandbox Code Playgroud)


cod*_*tty 5

在 NUnit 中,我喜欢这种形式的清晰性:

double expected = 10.5;
double actual = 10.499999999;
double tolerance = 0.001;
Assert.That(actual, Is.EqualTo(expected).Within(tolerance));
Run Code Online (Sandbox Code Playgroud)