Floating point representations seem to do integer arithmetic correctly - why?

前端 未结 8 1285
死守一世寂寞
死守一世寂寞 2021-01-06 10:41

I\'ve been playing around with floating point numbers a little bit, and based on what I\'ve learned about them in the past, the fact that 0.1 + 0.2 ends up bein

相关标签:
8条回答
  • 2021-01-06 11:07

    The reason is, that you can represent every whole number (1, 2, 3, ...) exactly in binary format (0001, 0010, 0011, ...)

    That is why integers are always correct because 0011 - 0001 is always 0010. The problem with floating point numbers is, that the part after the point cannot be exactly converted to binary.

    0 讨论(0)
  • 2021-01-06 11:08

    All of the cases that you say "work" are ones where the numbers you have given can be represented exactly in the floating point format. You'll find that adding 0.25 and 0.5 and 0.125 works exactly too because they can also be represented exactly in a binary floating point number.

    it's only values that can't be such as 0.1 where you'll get what appear to be inexact results.

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