double 的值足够大时接近正无穷大,你需要添加一个远高于10 200 的数字,以便使你的大的双倍变化值变成 POSITIVE_INFINITY
p>
原因是 double
表示大数字。它使用一个简短的尾数来表示该值的最高有效位,还有一个指数来表示小数点的位置。在数字非常大的情况下,指数本质上是在尾数的二进制表示之后需要添加多少个零的指示。
为了使您的 double
数字通过加法改变值,你需要添加一个至少与尾数的最低有效位一样大的数字。一旦二进制指数超过48,为了使结果不同而需要添加的最小数字变成2,这意味着 ++
将不再改变该值。
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.
解决方案
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.
这篇关于在for循环中使用Double.POSITIVE_INFINITY(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!