简体   繁体   English

Double和Integer的不同溢出策略。 为什么?

[英]different overflow policy for Double and Integer. why?

this code 这段代码

System.out.println(Double.MAX_VALUE+12345 == Double.MAX_VALUE);
System.out.println(Integer.MAX_VALUE+12345 == Integer.MAX_VALUE);

returns 回报

true
false

Please clarify this difference. 请澄清这种差异。

The rules are the same, it's just that Double.MAX_VALUE is so large that 12345 is roughly 300 orders of magnitude (10 300 times) smaller. 规则是相同的,只是Double.MAX_VALUE是如此之大,以至于12345大约小300个数量级(10 300倍)。 Adding a number that is so much smaller than Double.MAX_VALUE does not change its value. 添加比Double.MAX_VALUE小得多的数字不会更改其值。 Adding a number that is of the same order of magnitude would make a difference, though: 但是,添加一个具有相同数量级的数字会产生影响:

Double.MAX_VALUE + 1E300

produces a positive infinity result, which is not the same as Double.MAX_VALUE ( demo ) 产生正无穷大结果,与Double.MAX_VALUE演示 )不同

The behavior of addition to the maximum value differs between int and double in two very significant ways: 在两个非常重要的方面,添加到最大值的行为在int和double之间不同:

  1. The difference between each int, other than the maximum, and its immediate successor is 1, regardless of magnitude. 每个int(除最大值之外)与其直接后继者之间的差异为1,无论其大小如何。 The difference between consecutive doubles increases with magnitude. 连续双打之间的差异随着幅度的增加而增加。 For example, the absolute value of the difference between Double.MAX_VALUE and the next double smaller than it is about 2e292. 例如, Double.MAX_VALUE与下一个小于它的差值的绝对值约为2e292。 The absolute value of the difference between 1.0 and the next double smaller than it is about 1.1e-16. 1.0和下一个小于它的差值的绝对值约为1.1e-16。
  2. Every 32-bit bit pattern represents an int number. 每个32位位模式代表一个int数。 Some of the 64-bit bit patterns are reserved in double for NaN and infinite values. 对于NaN和无限值,一些64位位模式保留为double。 Adding one to Integer.MAX_VALUE wraps around to Integer.MIN_VALUE . Integer.MAX_VALUE添加一个包装到Integer.MIN_VALUE Adding a big enough positive number to make a difference to Double.MAX_VALUE results in Double.POSITIVE_INFINITY , represented by one of the reserved bit patterns. 添加足够大的正数以使Double.MAX_VALUE产生差异会导致Double.POSITIVE_INFINITY ,由其中一个保留位模式表示。

int is based on 2's complement binary arithmetic. int基于2的补码二进制算术。 It is designed to be compact, efficient, and to allow very fast simple arithmetic. 它设计紧凑,高效,并允许非常快速的简单算术。

double has more of a bias towards functionality. double对功能有更大的偏见。 Often, floating point arithmetic takes more than one machine cycle. 通常,浮点运算需要多个机器周期。 It can afford to have reserved bit patterns, such as the infinities, that require special handling. 它可以提供需要特殊处理的保留位模式,例如无穷大。

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

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