How would the following code behave, especially when the double counter reaches its limit ((2-2^-52)·2^1023)?
for (double i = 0; i < Double.POSITIVE_INFINITY; i++){
//do something
}
Would this code behave as expected (loop forever) or fail at some point and why?
Thanks.
public static final double POSITIVE_INFINITY. A constant holding the positive infinity of type double . It is equal to the value returned by Double.
static double NEGATIVE_INFINITY − This is the constant holding the negative infinity of type double. static double POSITIVE_INFINITY − This is the constant holding the positive infinity of type double. static int SIZE − This is the number of bits used to represent a double value.
To implement infinity in Java, we can simply divide the number by zero as shown below in the example. That's all for today, please mention in the comments in case you have any questions related to how to assign infinity in Java.
double includes numbers, and it includes infinity, and it includes NaN.
At some point, i++
will stop having any effect, because for very large values of i
, consecutive double
values are far apart.
Therefore it is an infinite loop.
To prove there are double
values for which i == i + 1
try this:
for (double i = 1;; i *= 2){
if (i == i + 1) {
System.out.println(i);
break;
}
}
It prints
9.007199254740992E15
This code will never exit the loop.
The reason for this is that adding 1
to a sufficiently large double
number does not change its value:
double a = 1.7976931348623155E308;
double old = a;
a++;
System.out.println(a); // prints 1.7976931348623155E308
System.out.println(old); // prints 1.7976931348623155E308
System.out.println(a==old); // prints "true"
Demo.
In fact, when the value of double
gets sufficiently close to positive infinity, you need to add a number well above 10200 in order to make your large double change value and become POSITIVE_INFINITY
.
The reason for this is the way double
represents large numbers. It uses a short mantissa to represent the most significant digits of the value, and an exponent to indicate where the fractional point should be placed. In case of very large numbers, the exponent is essentially an indication of how many zeros need to be added after the binary representation of the mantissa.
In order to make your double
number change value through addition, you need to add a number that is at least as large as the least significant bit of the mantissa. Once the binary exponent goes above 48, the smallest number that you need to add in order for the result to be different becomes 2, meaning that ++
would no longer change the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With