Java Reference
In-Depth Information
< Day Day Up >
Puzzle 29: Bride of Looper
Provide a declaration for i that turns this loop into an infinite loop:
while (i != i) {
}
Solution 29: Bride of Looper
This looper is perhaps even more puzzling than the previous one. It really seems that it ought to
terminate immediately, no matter what declaration precedes it. A number is always equal to itself,
right?
Right, but IEEE 754 floating-point arithmetic reserves a special value to represent a quantity that is
not a number [IEEE-754] . This value, known as NaN (short for "Not a Number"), is the value of all
floating-point computations that do not have well-defined numeric values, such as 0.0 / 0.0 . The
specification says that NaN is not equal to any floating-point value, including itself [JLS
15.21.1]. Therefore, if i is initialized to NaN before the loop starts, the termination test ( i != i )
evaluates to TRue , and the loop never terminates. Strange but true.
You can initialize i with any floating-point arithmetic expression that evaluates to NaN; for
example:
double i = 0.0 / 0.0;
Once again, you can add clarity by using a constant that is provided for you by the standard
libraries:
double i = Double.NaN;
NaN holds other similar surprises. Any floating-point operation evaluates to NaN if one or more
of its operands are NaN. This rule is perfectly reasonable, but it has strange consequences. For
 
 
Search WWH ::




Custom Search