I have recently noticed that int()
rounds a float towards 0, while integer division rounds a float towards its floor.
for instance:
-7 // 2 == -4
int(-7/2) == -3
I have read the documentation which specifies:
class int(x, base=10)
Return an integer object constructed from a number or string x, or return 0 if no arguments are >given. If x is a number, return
x.__int__()
. For floating point numbers, this truncates towards zero.
and:
floor division
Mathematical division that rounds down to nearest integer. The floor division operator is
//
. For example, the expression11 // 4
evaluates to 2 in contrast to the2.75
returned by float true division. Note that(-11) // 4
is-3
because that is-2.75
rounded downward. See PEP 238.
But it seems illogical for me that 2 similar operations (float division to integer) should return different results.
Is there any motivation for the differences between the functions?
Best Answer
Consistency.
You'll need to follow some very basic and seemingly irrelevant explanations to understand it.
In school you have learned division with a remainder. And you have done calculations like this:
Later, you have learned divisions for real numbers:
Until this point, you might believe that
x // 4
andint(x/4)
always give the same result. That's your current understanding of the situation.However, have a look what happens in the integer division: the number behind R cycles from 3, 2, 1 to 0 and then restarts: 3, 2, 1, 0. The number in front of the R decreses every 4th step.
So, how will it go on?
At the same time, the real number division gives us:
That's why
-1 // 4
gives -1 butint(-1/4)
gives 0.Well, they serve different purposes:
//
is part of an integer calculation with remainders andint()
gives you the part in front of the.
of a real number operation.You decide what you want to calculate, then you decide which operator to use in Python to get the correct result.
Good question. Keep on learning.