我怎么觉得,如果两个变量是近似等于?近似、变量、两个、我怎么

2023-09-07 02:49: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.5 10.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?

推荐答案

定义一个公差值(也就是一个小量),例如,0.00001,然后用它来比较,像这样的区别:

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

if (Math.Abs(a - b) < epsilon)
{
   // 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.AreSimiliar(A,B)在我们的单元测试。

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