2

I've observed the following surprising result

System.out.println((int) (5.1f * 10f)); => 51
System.out.println((int) (5.1f * 10d)); => 50

This is because Java does an implicit cast on the float during the multiplication, i.e. Java is actually doing this...

 System.out.println((double)5.1f * 10d); => 50

and casting 5.1f to double gives the result

System.out.println((double) 5.1f);  => 5.099999904632568

I'm struggling to understand why casting to a more precise type gives a less precise result. I'd only expect a loss of precision if going from double to float, not from float to double...

Double to float gives a less surprising result...

System.out.println((float) 5.1d); // => 5.1
Adam
  • 35,919
  • 9
  • 100
  • 137
  • 6
    The float is actually representing the number `5.1f` inaccurately, so when you cast to double, it's the actual number `5.1f` was. The double doesn't make it less precise, it's just float was less precise. – Andrew Li Apr 26 '17 at 15:21
  • 2
    See http://stackoverflow.com/q/916081/5647260 – Andrew Li Apr 26 '17 at 15:23
  • FWIW 5.1d = 5.0999999999999996447286321199499070644378662109375 – harold Apr 26 '17 at 15:23
  • 1
    @AndrewLi Thanks, closing as duplicate. – Adam Apr 26 '17 at 15:26
  • 1
    Imagine that you ask somebody to measure the space taken up by one block of wood, which is roughly 5.1cm, and then you want them to build a box that will hold 10 of them. If they measure with a tape measure, they'll probably tell you that you need 51cm of space in the box. If they measure with a micrometer, they might tell you that you need 50.9999cm of space in the box. The more precise measurement still yields a more precise result, but if you then tell them to round down to the nearest cm instead of up, the blocks won't fit in the resulting box. – StriplingWarrior Apr 26 '17 at 15:30
  • Study (and I do mean study) _What Every Computer Scientist Should Know About Floating-Point Arithmetic_, https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Lew Bloch Apr 26 '17 at 16:18

0 Answers0