10

I am confused regarding the delta/precision in assertEquals. I understand that 0.034 will give me the precision for my division code, as shown below:

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. 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. May I know what does the number mean, and how do we use it?

Idos
  • 15,053
  • 14
  • 60
  • 75
stack
  • 414
  • 1
  • 7
  • 21

2 Answers2

8

You are using:

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 is defined as the maximal deviation from the expected result:

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
Arithmetic.divide(12.0, 4.0) - 3.0 = 3.0 - 3.0 = 0 and
Arithmetic.divide(10.0, 3.0) - 3.3 ≈ 3.3333333 -3.3 ≈ 0.3333333 respectively.

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. 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.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75
2

According to: 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.4 Now, Arithmetic.divide(10.0,3.0) - 3.0 = 0.333.. which is LESSER than 0.4, so assertEqual() passes

Abhay Shukla
  • 349
  • 1
  • 12