Regarding the accuracy of the float type

I can’t understand why this

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

creates the same lines

How and why it does

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

I mean that the length of the mantissa for the floating point number is 2^23-1 . How does it manage to save the max_value of an integer that is 2^31 - 1 ?

+6
source share
1 answer

How to keep max_value maximum value equal to 2 ^ 31 - 1?

This is actually not the case. The value of f is 2147483648 .

However, narrowing down the primitive conversion from float to int clamps the value. He gets to this part:

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

    • The value must be too small (a negative value of a large value 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 a large value or positive infinity), and the result of the first step is the largest representable value of type int or long.

This can be easily seen by making the number even larger:

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

Or by clicking on long instead, which obviously does not need to be clamped at the same point:

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

Source: https://habr.com/ru/post/945040/


All Articles