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...
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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.