What do these three special floating-point values mean: positive infinity, negative infinity, NaN?

Johanna picture Johanna · Jun 17, 2009 · Viewed 21.4k times · Source

How can we use them in our codes, and what will cause NaN(not a number)?

Answer

coobird picture coobird · Jun 17, 2009
  • Positive infinity means going to infinity in the positive direction -- going into values that are larger and larger in magnitude in the positive direction.
  • Negative infinity means going to infinity in the negative direction -- going into values that are larger and larger in magnitude in the negative direction.
  • Not-a-number (NaN) is something that is undefined, such as the result of 0/0.

And the constants from the specification of the Float class:

More information can be found in the IEEE-754 page in Wikipedia.

Here's a little program to illustrate the three constants:

System.out.println(0f / 0f);
System.out.println(1f / 0f);
System.out.println(-1f / 0f);

Output:

NaN
Infinity
-Infinity