Python Forum

Full Version: Integer division
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all. I am new to python and was hoping to get some help. I understand that // is used to do integer division but I'm confused about certain outcomes. Eg: 10//2.5 results in 4.0, 9//1.6 results 5.0 (rounded down), 9//1.8 results in 4.0 !! I don't understand why the last two have different results. Can someone please explain (remembering that I am new to this lol)?

Thanks,
plozaq
It's the integer floor of a division, but it may not be the one you expect. You might want to review https://docs.python.org/3/tutorial/floatingpoint.html.

1.8 can't be exactly represented in a binary floating point, so math using that value will tend to have small errors.

>>> format(1.8, ".20f")
'1.80000000000000004441'
Since the representation is slightly larger than 1.8, the division doesn't work out exactly and it can't complete 5 full divisions.
>>> divmod(9,1.8)
(4.0, 1.7999999999999998)
So the integer division result is only 4, not 5 due to inaccuracies in the floating point. Whereas 1.799999999 would give a different number.

>>> 9 // 1.8
4.0
>>> 9 // 1.79999999999
5.0
Thankyou so much for the answer. It was confusing the hell out of me but now it makes sense lol.

plozaq