Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
stack Avatar asked Feb 13 '16 08:02

stack


People also ask

What does the assertEquals () method do?

The assert. equal() method tests if two values are equal, using the == operator. If the two values are not equal, an assertion failure is being caused, and the program is terminated.

How many parameters does assertEquals () have?

Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value);

What is the output of assertEquals?

assertEquals() methods checks that the two objects are equals or not. If they are not, an AssertionError without a message is thrown. Incase if both expected and actual values are null, then this method returns equal.

Does assertEquals use equal?

assertEquals() The assertEquals() method compares two objects for equality, using their equals() method.


1 Answers

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.

like image 153
Idos Avatar answered Sep 29 '22 05:09

Idos