views:

597

answers:

5

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

+11  A: 
  • 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
coobird
but I think 1/0 will cause positive infinity :-?
Johanna
Yes, you're correct -- that was my error, and it has been fixed.
coobird
+2  A: 
  • 1/0 will result in positive infinity.
  • 0/0 will result in Nan. You can use NaN as any other number, eg: NaN+NaN=NaN, NaN+2.0=NaN
  • -1/0 will result in negative infinity.

Infinity (in java) means that the result of an operation will be such an extremely large positive or negative number that it cannot be represented normally.

kadam
+3  A: 

This may be a good reference if you want to learn more about floating point numbers in Java.

Positive Infinity is a positive number so large that it can't be represented normally. Negative Infinity is a negative number so large that it cannot be represented normally. NaN means "Not a Number" and results from a mathematical operation that doesn't yield a number- like dividing 0 by 0.

In Java, the Double and Float classes both have constants to represent all three cases. They are POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN.

Cameron
+2  A: 

The idea is to represent special numbers which can arise naturally from operations on "normal" numbers. You could see infinity (both positive and negative) as "overflow" of the floating point representation, the idea being that in at least some conditions, having such a value returned by a function still gives meaningful result. They still have some ordering properties, for example (so they won't screw sorting operations, for example).

Nan is very particular: if x is Nan, x == x is false (that's actually one way to test for nan, at least in C, again). This can be quite confusing if you are not used to floating point peculiarities. Unless you do scientific computation, I would say that having Nan returned by an operation is a bug, at least in most cases that come to mind. Nan can come for various operations: 0/0, inf - inf, inf/inf, 0 * inf. Nan does not have any ordering property, either.

David Cournapeau
A: 

You can use them as any other number:

e.g:

float min = Float.NEGATIVE_INFINITY;
float max = Float.POSITIVE_INFINITY;
float nan = Float.NaN;
Freddy