Float numbers in Java

后端 未结 6 1638
傲寒
傲寒 2020-12-07 03:10

Could anyone please me why the output of the following programme is not \" different different\"?

public static void main(String[] args)
{

float f1=3.2f;
fl         


        
相关标签:
6条回答
  • 2020-12-07 03:12

    Because 3.2f is a float value and 3.2 is a double value. Floating point numbers are always slightly inaccurate because binary representation cannot implement them accurately, so comparing them for exact equality is a bad idea. Particularly comparing floats with doubles. Expressions such as 3.2f == 3.2f are usually okay, but even those can fail in some languages, e.g. if they represent numbers in registers more accurately than in memory.

    0 讨论(0)
  • 2020-12-07 03:16

    Because 3.2 is not representable exactly as floating point number and 6.5 is (hint: 6.5 = 13 * 2^(-1)), as well as the fact that 3.2 is a double literal but 3.2f is a float literal.

    0 讨论(0)
  • 2020-12-07 03:19

    This can help understand

    0 讨论(0)
  • 2020-12-07 03:27

    Also, I think anything with a decimal defaults into a double, so when you do a comparison, you have to add 'f' as well like if(f2==6.4f).

    0 讨论(0)
  • 2020-12-07 03:30

    "3.2f" is a of type float. "3.2" is of type double.

    0 讨论(0)
  • 2020-12-07 03:37

    6.5 has a finite binary representation: 110.1

    Any floating type with at least 4 significant bits can represent this number perfectly.

    110.100000000000000000000 (float)
    = 6.5

    110.10000000000000000000000000000000000000000000000000 (double)
    = 6.5

    3.2 on the other hand has an infinite binary representation: 101.0011001100110011...

    float and double don't have infinite precision and thus can only approximate this number :(

    101.001100110011001100110 (float)
    = 3.2000000476837158203125

    101.00110011001100110011001100110011001100110011001101 (double)
    = 3.20000000000000017763568394002504646778106689453125

    As you can clearly see, these numbers are not the same!

    0 讨论(0)
提交回复
热议问题