简体   繁体   中英

In Java, what happens if you use Double.NaN in an operation?

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.

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM