简体   繁体   English

assertEquals精度

[英]assertEquals Precision

I am confused regarding the delta/precision in assertEquals . 我对assertEquals的delta / precision感到困惑。 I understand that 0.034 will give me the precision for my division code, as shown below: 据我所知, 0.034将为我的分区代码提供精确度,如下所示:

public void testDivide() {
        assertEquals(3.0, Arithmetic.divide(12.0, 4.0), 0.0);
        assertEquals(3.3, Arithmetic.divide(10.0, 3.0), 0.034);

        //fail("Not yet implemented");
    }

However, I tried to change it to 0.03 , the test failed. 但是,我试图将其更改为0.03 ,测试失败。 On the other hand, when I change it to 0.04 , it succeeded, or even if I change it to 0.034444 and so forth, it will succeed. 另一方面,当我将其更改为0.04 ,它成功,或者即使我将其更改为0.034444等等,它也会成功。 May I know what does the number mean, and how do we use it? 我可以知道数字是什么意思,我们如何使用它?

You are using: 您正在使用:

assertEquals (double expected, double actual, double epsilon) assertEquals (double expected, double actual, double epsilon)

Since doubles may not be exactly equal in any language (precision issues), epsilon allows you to describe how close they have to be. 由于双语在任何语言中可能不完全相同 (精度问题),因此epsilon允许您描述它们的接近程度。

Epsilon is defined as the maximal deviation from the expected result: Epsilon 定义为与expected结果的最大偏差:

Math.abs(expected - actual) < epsilon

So in essence it allows you to deviate from the expected outcome ( 3.0 or 3.3 in your cases) by 所以从本质上讲,它允许你偏离expected结果(在你的情况下为3.03.3
Arithmetic.divide(12.0, 4.0) - 3.0 = 3.0 - 3.0 = 0 and Arithmetic.divide(12.0, 4.0) - 3.0 = 3.0 - 3.0 = 0
Arithmetic.divide(10.0, 3.0) - 3.3 ≈ 3.3333333 -3.3 ≈ 0.3333333 respectively. Arithmetic.divide(10.0, 3.0) - 3.3 ≈ 3.3333333 -3.3 ≈ 0.3333333

So in the first one as you see, there is actually no need for an epsilon since the expected and actual results are exactly the same. 因此,在您看到的第一个中,实际上不需要epsilon,因为expectedactual结果完全相同。 In the second one you should allow some deviation as you see that the actual result is approximately > by 0.33333 than the expected one. 在第二个你应该允许一些偏差,你看到actual结果是大约>0.33333expected一个。

According to: http://junit.sourceforge.net/javadoc/org/junit/Assert.html#assertEquals(double , double, double) 根据: http//junit.sourceforge.net/javadoc/org/junit/Assert.html#assertEquals (double,double,double)

**delta** - the maximum delta between expected and actual for which both numbers are still considered equal.

for delta = 0.3 Now, Arithmetic.divide(10.0,3.0) - 3.0 = 0.333.. which is greater than 0.3 , so assertEqual() fails for delta = 0.3现在, Arithmetic.divide(10.0,3.0) - 3.0 = 0.333..greater than 0.3 ,所以assertEqual()失败

for delta = 0.4 Now, Arithmetic.divide(10.0,3.0) - 3.0 = 0.333.. which is LESSER than 0.4 , so assertEqual() passes for delta = 0.4现在, Arithmetic.divide(10.0,3.0) - 3.0 = 0.333.. LESSER than 0.4 ,所以assertEqual()通过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM