Search code examples
javajunitprecisionassert

assertEquals Precision


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?


Solution

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