I am running python 3.7.3
Regarding the integer division operator: "//" (double divide, double forward slash, double division operator? I'm not sure the exact name.)
It does not seem to give consistent results, and many of the explanations I've found don't fully explain its results.
Here[What is the reason for having '//' in Python? (and other places) it's said that the "//" operator gives the quotient without the remainder. As if a // b
is the same as floor(a / b)
(or rounding up if a / b
is negative).
However, sometimes it does not give that answer. For example,1 // 0.2
evaluates to 4. However 1 / 0.2
returns 5, and math.floor(1 / 2)
also returns 5. It's giving a number one less than what integer division should. The //
operator returns a 5 if you divide 10 by 2, but 1 divided 0.2 does not work correctly.
This problem comes up other times I use the //
operator to divide floating point numbers. Like 5 // 0.2
or 100 // 0.2
. I don't know if this is some quirk of floating point arithmetic, but these problems seem to go away if you type math.floor(5 / 0.2)
(or any other set of numbers giving issues). Except when you divide negative numbers, in which case you have to use math.ceil()
instead of math.floor()
My current solution is this:
import math
def integerDivision(a,b):
tmp = a / b
if tmp > 1:
return(math.floor(tmp))
else:
return(math.ceil(tmp))
What is the implementation of the //
operator that makes it not give the right result in some floating point cases? Is there a better way to get around this issue of the //
operator, other than the above code?