Wednesday, March 14, 2012

How can you compare NaN values in Java?


Floating-point numbers are ordered from -∞, -y (negative finite nonzero values), -0, +0, +y, +∞. The float and double types represent 32- and 64-bit IEEE 754 floating-point numbers.
The special number NaN (not-a-number) is unordered and has the following characters:
  • The numerical comparison operators <, <=, >, and >= always return false if either or both operands are NaN.
  • The equality operator == returns false if either operand is NaN.
  • The inequality operator != returns true if either operand is NaN .
In particular, x != x is true if and only if x is NaN, and (x == y) will be false if x or y is NaN.
To verify a floating point value is NaN, use the Double.isNaN() method instead. The x == NaN will not work because "The equality operator == returns false if either operand is NaN". NaN is never equal to any other number, not even itself.
The wrapper classes such as Float and Double have the same behavior when using the above comparison operators. Comparing two NaN Float objects using Float.equals() will yieldtrue even even though Float.NaN==Float.NaN has the value false. This is one of two special cases in Float class and described in Float class document. Such behavior make it possible to use an NaN Float object as a key in a HashMap. For example,
public class Program {        
  public static void main(String[] s){
    Double a = new Double(Double.NaN);
    Double b = new Double(Double.NaN);
   
    if( Double.NaN == Double.NaN )
      System.out.println("True");
    else
      System.out.println("False");
        
    if( a.equals(b) )
      System.out.println("True");
    else
      System.out.println("False");
  }
}
The output is
False
True

No comments:

Post a Comment