java - 关于浮点型精度

标签 java floating-point

我不明白这是为什么

float f = Integer.MAX_VALUE;
System.out.println(Integer.MAX_VALUE);
System.out.println((int)f);

产生相同的行,

以及为什么会这样

Float f2 = (float) Integer.MAX_VALUE;
System.out.println(Integer.MAX_VALUE);
System.out.println(f2.intValue());

我的意思是, float 的尾数长度是 2^23-1。它如何设法保持整数的 max_value,即 2^31 - 1

最佳答案

How does it manage to keep max_value of integer, which is 2^31 - 1?

其实不然。 f 的值为 2147483648

然而,narrowing primitive conversionfloatint 限制值。它到达了这一部分:

  • Otherwise, one of the following two cases must be true:

    • The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.

    • The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

您可以通过将数字更大来轻松地看到这一点:

float f = Integer.MAX_VALUE;
f = f * 1000;
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println((int)f); // 2147483647

或者通过转换为 long 来代替,这显然不需要在同一点进行限制:

float f = Integer.MAX_VALUE;
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println((long)f); // 2147483648

关于java - 关于浮点型精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16557999/

相关文章:

java - 添加 JSON 类文件夹并在 Java 和 Eclipse 作为 IDE 中导入

java.util.concurrent.ExecutionException : redis. clients.jedis.exceptions.JedisDataException:ERR 达到最大客户端数

java - 添加字符串资源而不是静态数据

c - fdim 首字母缩写词代表什么?

java - Spring boot --> 在 war 部署期间动态添加 jars(而不是在 war 生成期间)

java - 两个 Jpanel 未显示在 Jframe 中

python - 在 python 3.x 中表示 float 无穷大的最佳实践

floating-point - 为什么 exponent(0.0) 是一个 DomainError?

C libpq : get float value from numeric

haskell - 除法返回 NaN