Why don't operations on double-precision values give expected results?

后端 未结 3 437
逝去的感伤
逝去的感伤 2020-12-19 15:45
    System.out.println(2.14656);

2.14656

    System.out.println(2.14656%2);

0.14656000000000002

WTF?

3条回答
  •  盖世英雄少女心
    2020-12-19 16:10

    The do give the expected results. Your expectations are incorrect.

    When you type the double-precision literal 2.14656, what you actually get is the closest double-precision value, which is:

    2.14656000000000002359001882723532617092132568359375
    

    the println happens to round this when it prints it out (to 17 significant digits), so you see the nice value that you expect.

    After the modulus operation (which is exact), the value is:

    0.14656000000000002359001882723532617092132568359375
    

    Again, this is rounded when it gets printed, but because there is one less leading digit, the round point is one digit farther to the right, and so you see that trailing 2.

提交回复
热议问题