tags:

views:

1330

answers:

3

I have compiled code that erroneously tries to add a number and Double.NaN. I'm wondering if it's throwing an exception that's not getting caught? Does anyone know how that situation is handled?
Thanks.

+5  A: 

Adding a number to NaN gives NaN. It isn't expected to cause an exception. I understand that this conforms to IEEE 754.

Adrian
A: 
public static void main(String args[])
{
 Double d = Double.NaN + 1.0;
 System.out.println(d);
}

prints Double.Nan. Can anyone explain the source implementation?

  public static final double POSITIVE_INFINITY = 1.0 / 0.0;
  public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
  public static final double NaN = 0.0d / 0.0;
Steve B.
By definition, 0/0 = NaN. See http://en.wikipedia.org/wiki/NaN.
Michael Myers
Eh, didn't see that Gamecat's answer was referring to this one.
Michael Myers
+1  A: 

To answer Steve B's question:

POSITIVE_INFINITY is the largest postive number that you can store if you have unlimited storage space. Without this luxury we have to use a construction like 1.0 / 0.0 which does a fine job. Same goes for NEGATIVE_INFINITY but then the largest negative number.

NaN is normally defined as 0.0 / 0.0 because there is no such number as 0/0 so that perfectly qualifies for a NaN.

Gamecat