简体   繁体   English

增加primitve类型的MAX_VALUE

[英]Incrementing MAX_VALUE of primitve type

I try to understand the following code: 我尝试理解以下代码:

int i = Integer.MAX_VALUE;
double d = Double.MAX_VALUE;

System.out.println(i + ":" + (i+1));
System.out.println(d + ":" + (d+1));

The output is: 输出是:

2147483647:-2147483648
1.7976931348623157E308:1.7976931348623157E308

For the first line, i is equal to the maximum integer and incrementing it leads to the lowest integer value. 对于第一行, i等于最大整数,并且递增它导致最小整数值。 Why the same is not happening with d ? 为什么d不会发生同样的情况?

Is there a simple explanation for this behaviour? 这种行为有一个简单的解释吗?

When a double overflows, its value becomes Infinity , not a negative number. 当双溢出时,其值变为Infinity ,而不是负数。

The reason why you can't overflow by simply adding 1 to Double.MAX_VALUE is that MAX_VALUE + 1 == MAX_VALUE because the precision of doubles is not enough to make the difference between those two numbers. 简单地向Double.MAX_VALUE添加1就不能溢出的原因是MAX_VALUE + 1 == MAX_VALUE因为双精度不足以使这两个数字之间产生差异。

Actually you can add quite a large number before jumping to the next available double. 实际上你可以在跳到下一个可用的双倍之前添加相当多的数字。 For example that does not overflow either: 例如,不会溢出:

System.out.println(Double.MAX_VALUE + 1e100); //still Double.MAX_VALUE

This overflows as expected: 这按预期溢出:

System.out.println(m + (Math.ulp(m) / 2)); //Infinity

Your double cannot represent the actual number you're trying to represent due to lose of accuracy with double s. 您的double不能代表您尝试表示的实际数字,因为double精度会失去准确性。 That's why the value is not changing and you're actually don't have an overflow. 这就是为什么价值没有变化,你实际上没有溢出。

For non- int types, overflow will result in Infinity . 对于非int类型,溢出将导致Infinity Try to multiply that value with 20, for example, and you'll see the overflow in action. 例如,尝试将该值乘以20,您将看到溢出动作。

The integer overflows because it is represented in a two's complement format. 整数溢出,因为它以二进制补码格式表示。

  • Integer.MAX_VALUE is represented by 0111...111 Integer.MAX_VALUE0111...111表示
  • Integer.MIN_VALUE is represented by 1000...000 Integer.MIN_VALUE1000...000表示

So when you try and add 1 to Integer.MAX_VALUE , according to the normal rules of addition, you get Integer.MIN_VALUE . 因此,当您尝试将1添加到Integer.MAX_VALUE ,根据正常的添加规则,您将获得Integer.MIN_VALUE This is called overflow. 这称为溢出。

Floating point numbers have a different representation, which doesn't lend itself to this type of overflow. 浮点数具有不同的表示,这不适合这种类型的溢出。 They are all approximations, and the closest approximation it has to the value you gave it is Double.MAX_VALUE . 它们都是近似值,它与您给出的值的最接近的近似值是Double.MAX_VALUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM