There is an interesting difference between ==
and equals
for Float
and Double
types: They treat NaN
differently:
scala> Double.NaN == Double.NaN
res3: Boolean = false
scala> Double.NaN equals Double.NaN
res4: Boolean = true
Edit: As was pointed out in a comment - "this also happens in Java" - depends on what exactly this is:
public static void main(final String... args) {
final double unboxedNaN = Double.NaN;
final Double boxedNaN = Double.valueOf(Double.NaN);
System.out.println(unboxedNaN == unboxedNaN);
System.out.println(boxedNaN == boxedNaN);
System.out.println(boxedNaN.equals(boxedNaN));
}
This will print
false
true
true
So, the unboxedNan
yields false
when compared for equality because this is how IEEE floating point numbers define it and this should really happen in every programming language (although it somehow messes with the notion of identity).
The boxed NaN yields true for the comparison using ==
in Java as we are comparing object references.
I do not have an explanation for the equals
case, IMHO it really should behave the same as ==
on unboxed double values, but it does not.
Translated to Scala the matter is a little more complicated as Scala has unified primitive and object types into Any
and translates into the primitive double and the boxed Double as needed. Thus the scala ==
apparently boils down to a comparison of primitive NaN
values but equals
uses the one defined on boxed Double values (there is a lot of implicit conversion magic going on and there is stuff pimped onto doubles by RichDouble
).
If you really need to find out if something is actually NaN
use isNaN
:
scala.Equals
which points to Programming in Scala, Chapter 28, Object Equality.