1

Here is my JUnit code for a test case of the cube root method I created that implements Newton's method:

@Test
public void standardCase_negative64e9() {
  double n = -64E9;
  double result = csc143.newton.Roots.cbrt(n);
  double delta = n * 1E-8;
  assertEquals("Standard cube root -64E9", -4.0E3, result, delta);
}

When I do the tests for all my test cases (using DrJave IDE) I only get a failure for this test case, and it reads:

Failure: java.lang.AssertionError: Standard cube root -64E9 expected:<-4000.0> but
was:<-4000.0000000003124>

I feel this has something to do with my "delta" value (which is -640 in this case) because when I replace "delta" with 640 (instead of -640) in the assertEquals() method, I do not get a failure...

Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
adub3
  • 141
  • 3
  • 9

2 Answers2

3

Your delta has this value: -64E9*1E-8 which is actually -64.That is: it is a negative value. As delta is expected to be the upper limit on the difference between the actual and expected value you need to make it a positive number.

Take a look at the source code of the Assert class. The place where doubles are compared is the doubleIsDifferent method:

static private boolean doubleIsDifferent(double d1, double d2, double delta) {
    if (Double.compare(d1, d2) == 0) {
        return false;
    }
    if ((Math.abs(d1 - d2) <= delta)) {    
        return false;
    }

    return true;
}

As you can see the relevant expression is Math.abs(d1 - d2) <= delta. As it uses Math.abs the left-hand side is always 0 or positive. Thus it can never be less than a negative value so this method always returns true thus indicating to the caller (assertEquals) that your values are different.

In other words: change the definition of delta to:

double delta = Math.abs(n * 1E-8);
Itay Maman
  • 30,277
  • 10
  • 88
  • 118
1

If you read the Javadocs of JUnit Assert, assertEquals, you'll see that delta should indeed be positive:

Asserts that two doubles or floats are equal to within a positive delta.

kuporific
  • 10,053
  • 3
  • 42
  • 46
  • Then why is one of my earlier test cases not encountering the same issue: @Test public void standardCase_negative1000() { double n = -1000; double result = csc143.newton.Roots.cbrt(n); double delta = n * 1E-8; assertEquals("Standard cube root -1000", -10.0, result,delta); } – adub3 Jul 19 '13 at 22:19