Suppose you have a Java language program in which the following expression appears:
1.0 / 0.0
What happens? Does this usage cause an exception to be thrown? Is the result undefined?
In the Java programming language, integral division by zero results in an ArithmeticException. But for floating-point, no exception is thrown (in C++ the result of division by zero is undefined). The result of 1.0 / 0.0 is positive infinity, indicated by the constant Double.POSITIVE_INFINITY (which, in fact, is defined by performing this division).
This example illustrates an important point, which is that Java language floating-point arithmetic operates according to a well-defined standard, known as IEEE 754.
Another related idea is that of NaN (not a number), used to represent the results of certain arithmetic operations such as the following:
0.0 / 0.0
There is also a "Double.NaN" constant defined, which is analogous to the constant Double.POSITIVE_INFINITY. NaN is interesting in that it has the following property:
NaN != NaN
In other words, NaN is unequal to itself, and this fact is used to implement methods such as Double.isNaN.
To tie down these ideas a little better, here is an example that uses negative infinity, positive infinity, and NaN:
=====================================================================
public class number {
public static void main(String args[])
{
long neg_inf_bits =
Double.doubleToLongBits(-1.0 / 0.0);
long pos_inf_bits =
Double.doubleToLongBits(1.0 / 0.0);
long nan_bits =
Double.doubleToLongBits(0.0 / 0.0);
System.out.println(Long.toHexString(neg_inf_bits));
System.out.println(Long.toHexString(pos_inf_bits));
System.out.println(Long.toHexString(nan_bits));
}
}
=======================================================================
The output of the program is the following:
fff0000000000000
7ff0000000000000
7ff8000000000000
These numbers are the hexadecimal 64-bit values that represent negative infinity, positive infinity, and NaN respectively. In other words, particular bit patterns for a double value indicate specific special values such as NaN.
Finally,
knowing how floating-point arithmetic behaves is quite important in particular
applications, and the Java language specification goes to some lengths to tie
down behavior in this area.