I have the following junit unit test and discovered something very interesting
public class MyTest {
@Test
public void BasicTest() {
assertEquals("0.0!=-0.0",new Double(0.0D),new Double(-3.0D*0.0D));
}
}
It gives me the error message:
0.0!=0.0 expected:<0.0> but was:<-0.0>
Why is 0.0 not equal to -0.0 in Java? What ways are there to get around this error?
The answer lies in the bit representation of the number. Use this method:
Where
x
is a type variabledouble
to see its representation in bits. For the numbers 0.0 and -0.0 respectively, this is your result:Departure:
As you can see, the numbers 0.0 and -0.0 are different . And this makes sense since Java uses the IEEE floating point format for the representation of
double
, where the first bit is for the sign.Add 0.0 to the negative and the problem is solved:
Departure: