Issue
I'm working with JUnit 5 in Java SE 11 and discovered that assertEquals(-0.0,0.0) fails. Why is that? Java itself is perfectly happy with "-0. == 0.". Sample code follows.
double dVar1 = 0;
double dVar2 = -dVar1;
System.out.println( dVar1 == dVar2 ); // true
System.out.println( -0. == 0. ); // true
assertEquals( dVar1, dVar2, .00001 ); // passes
assertEquals( 0.0, -0.0, .0001 ); // passes
assertEquals( 0.0, -0.0 ); // fails
assertEquals( dVar1, dVar2 ); // fails
Solution
Java has no problem with -0 and 0. But in assertEquals method use this method from Double class to convert params to longBits and the reterned values are not the same.
public static long doubleToLongBits(double value) {
long result = doubleToRawLongBits(value);
// Check for NaN based on values of bit fields, maximum
// exponent and nonzero significand.
if ( ((result & DoubleConsts.EXP_BIT_MASK) ==
DoubleConsts.EXP_BIT_MASK) &&
(result & DoubleConsts.SIGNIF_BIT_MASK) != 0L)
result = 0x7ff8000000000000L;
return result;
}
In your case you have to use the first assertEquals(double expected, double actual, double delta) which based on math operation: return doublesAreEqual(value1, value2) || Math.abs(value1 - value2) <= delta
Answered By - BARHOUMI