如何确定两个变量是否近似相等? [英] How do I find if two variables are approximately equals?

查看:39
本文介绍了如何确定两个变量是否近似相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写单元测试来验证数据库中的计算,并且有很多四舍五入和截断等内容,这意味着有时数字会略有偏差.

I am writing unit tests that verify calculations in a database and there is a lot of rounding and truncating and stuff that mean that sometimes figures are slightly off.

在验证时,我发现很多时候事情会通过但会说失败 - 例如,数字是 1 而我得到的是 0.999999

When verifying, I'm finding a lot of times when things will pass but say they fail - for instance, the figure will be 1 and I'm getting 0.999999

我的意思是,我可以将所有内容四舍五入为一个整数,但由于我使用了大量随机样本,因此最终我会得到这样的结果

I mean, I could just round everything into an integer but since I'm using a lot of randomized samples, eventually i'm going to get something like this

10.510.4999999999

10.5 10.4999999999

一个将四舍五入到 10,另一个将四舍五入到 11.

one is going to round to 10, the other will round to 11.

如果我需要一些大致正确的东西,我应该如何解决这个问题?

How should I solve this problem where I need something to be approximately correct?

推荐答案

定义一个容差值(又名 'epsilon' 或 'delta'),例如 0.00001,然后像这样用来比较差异:

Define a tolerance value (aka an 'epsilon' or 'delta'), for instance, 0.00001, and then use to compare the difference like so:

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

您可以使用 Double.Epsilon,但您必须使用乘数.

You could use Double.Epsilon but you would have to use a multiplying factor.

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

Better still, write an extension method to do the same. We have something like Assert.AreSimiliar(a,b) in our unit tests.

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

Microsoft's Assert.AreEqual() method has an overload that takes a delta: public static void AreEqual(double expected, double actual, double delta)

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

NUnit also provides an overload to their Assert.AreEqual() method that allows for a delta to be provided.

这篇关于如何确定两个变量是否近似相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆