问题描述
这是IEEE 754标准问题。我不完全理解它背后的机制。
This is IEEE 754 standard question. I don't completely understand the mechanics behind it.
public class Gray {
public static void main(String[] args){
System.out.println( (float) (2000000000) == (float) (2000000000 + 50));
}
}
推荐答案
只能保留7到8有效数字。也就是说,它没有足够的位来表示数字2000000050,所以它被四舍五入到2000000000。
Because a float
can only hold about 7 to 8 significant digits. That is, it doesn't have enough bits to represent the number 2000000050 exactly, so it gets rounded to 2000000000.
具体来说, float
由三部分组成:
Specifically speaking, a float
consists of three parts:
- 符号位(1位)
- 指数(8位)
- 有效位数(24位,但只存储23位,因为有效位数的MSB始终为1)
您可以将浮点视为计算机以科学记数法的方式,但是以二进制。
You can think of floating point as the computer's way doing scientific notation, but in binary.
> precision 等于 log(2 ^有效数位数)
。这意味着 float
可以保存 log(2 ^ 24)= 7.225
有效数字。
The precision is equal to log(2 ^ number of significand bits)
. That means a float
can hold log(2 ^ 24) = 7.225
significant digits.
数字2,000,000,050有9个有效数字。上面的计算告诉我们,24位有效位数不能容纳那么多有效数字。
The number 2,000,000,050 has 9 significant digits. The calculation above tells us that a 24-bit significand can't hold that many significant digits. The reason why 2,000,000,000 works because there's only 1 significant digit, so it fits in the significand.
要解决这个问题,您需要使用,因为它有一个52位有效位数,足以代表每个可能的32位数字。
To solve the problem, you would use a double
since it has a 52-bit significand, which is more than enough to represent every possible 32-bit number.
这篇关于为什么这是真的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!