我正在编写单元测试来验证数据库中的计算,并且有很多四舍五入和截断等内容,这意味着有时数字会略有偏差.
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.
更多推荐
如何确定两个变量是否近似相等?
发布评论