Please provide a Statement on I to convert the following loop into an infinite loop:
while (i != i) {}
This cycle may be even more confusing than the previous one. No matter what statements are made before it, it seems that it should be terminated immediately. A number is always equal to itself, right?
Yes, but the IEEE 754 Floating Point Arithmetic retains a special value to indicate a number that is not a number [IEEE 754]. This value is Nan (not a number). It is used for all floating point calculations without a good number definition, such as 0.0/0.0. The norm describes that Nan is not equal to any floating point value, including itself [JLS 15.21.1]. Therefore, if I is initialized as Nan before the cycle starts, terminate the conditional test (I! = I) The calculation result is true, and the loop will never end. It's strange, but it's a fact.
You can use any floating-point arithmetic expression that calculates Nan to initialize I. For example:
double i = 0.0 / 0.0;
Similarly, to be clear, you can use the constants provided by the standard class Library:
double i = Double.NaN;
Nan has other amazing features. For any floating point operation, if one or more of its operands is Nan, the result is Nan. This rule is very reasonable, but it has strange results. For example, the following program prints false:
class Test { public static void main(String[] args) { double i = 0.0 / 0.0; System.out.println(i - i == 0); }}
The principle behind this Nan calculation rule is that once a computation produces Nan, it will be damaged, and no further computation can fix such damage. The Nan value is intended to continue the execution of the damaged computation until it is convenient to handle this situation.
In short, float and double types both have a special Nan value, which is used to indicate the number of numbers. For calculations involving Nan values, the rules are simple and wise, but the results of these Rules may be contrary to intuition.
Puzzle 29: The Bride of the loop