简体   繁体   English

关于浮球式精度

[英]Regarding float type precision

I can't understand why this 我无法理解为什么会这样

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

produces the same lines, 产生相同的线,

As well as why this does 以及为什么这样做

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

I mean, mantissa length for floating point number is 2^23-1 . 我的意思是,浮点数的尾数长度是2^23-1 How does it manage to keep max_value of integer, which is 2^31 - 1 ? 它如何设法保持整数的max_value,即2^31 - 1

How does it manage to keep max_value of integer, which is 2^31 - 1? 它如何设法保持整数的max_value,即2 ^ 31 - 1?

It actually doesn't. 它实际上没有。 The value of f is 2147483648 . f的值是2147483648

However, the narrowing primitive conversion from float to int clamps the value. 但是,从floatint缩小基元转换会限制该值。 It gets to this part: 它到达这一部分:

  • 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. 该值必须太小(大幅度或负无穷大的负值),第一步的结果是int或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. 该值必须太大(大幅度或正无穷大的正值),第一步的结果是int或long类型的最大可表示值。

You can see this easily by making the number even bigger: 通过使数字更大,您可以轻松地看到这一点:

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

Or by casting to long instead, which obviously doesn't need to be clamped at the same point: 或者通过转换成long代替,这显然并不需要在同一地点被夹住:

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

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

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