0

I'm facing a (for me) strange behaviour of the // operator in python.

When I compute, e.g., 5.//0.25 I become the right result, i.e.

>>> 5.//0.25
20.0

But

>>> 5.//0.2
24.0

Instead of

>>> math.floor(5./0.2)
25

Can anyone explain me this results? Why is the result of the // 24.0?

EDIT: The given link Is floating point math broken? does not really answer the question exhaustively. In fact, with this answer one can not understand why the floor of the normal division give the right result. The real answer should explain how does // work, as was done by polku in the comments

And perhaps I had to write this from the beginning: why is this happening?

>>> print('%.17f' % (5./0.20000000298023224))
24.99999962747097726
>>> print('%.17f' % (5./0.2))
25.00000000000000000

EDIT2: This question should really be reopened, since it's answers isn't given in the suggested duplicate question, but rather in @polku's comment.

David
  • 513
  • 7
  • 26
  • 5
    The reason is the used format for decimals cannot store the value `0.2` *exactly*. It differs from number to number, but for this value the closest one is 0.20000000298023224 – just a bit more than you were expecting. Other values can be exact (0.25) or just a little bit *less* (0.26). – Jongware May 09 '16 at 09:50
  • Yes, but then why am I getting the right result with floor? Also, if i print the result I get 25.00000000... – David May 09 '16 at 09:56
  • 4
    I think the given link doesn't really answer the question why 5/0.2 != 5//0.2. The thing is // (aka floordiv) has a friend % (aka modulo), and they both agreed to work together to make (a//b)*b + (a%b) == a, whereas / (aka div) doesn't care about modulo. Since 5%0.2 = 0.199..., floordiv can't say 5//0.2 = 25 anymore but (5/0.2)*.2==(5//0.2)*.2+(5%0.2) return True. – polku May 09 '16 at 10:30
  • 1
    Agreed that the given duplicate doesn't answer the question. Here's a [better duplicate](https://stackoverflow.com/questions/24057694/python-different-result-when-performing-division-vs-floor-division-when-dividi) link. – Mark Dickinson Feb 09 '18 at 19:53
  • 1
    Another duplicate: https://stackoverflow.com/q/38588815/270986 – Mark Dickinson Feb 09 '18 at 19:55

0 Answers0