I found that -1 // 2
is equal to -1 (Why not 0?), but int(-1 / 2)
is equal to 0 (as I expected).
It's not the case with 1 instead of -1, so both 1 // 2
and int(1 / 2)
is equal to 0.
Why the results are different for -1?
I found that -1 // 2
is equal to -1 (Why not 0?), but int(-1 / 2)
is equal to 0 (as I expected).
It's not the case with 1 instead of -1, so both 1 // 2
and int(1 / 2)
is equal to 0.
Why the results are different for -1?
In Python, the division operator /
and the floor division operator //
have different behavior.
The division operator /
returns a floating-point number that represents the exact quotient of the division. In the case of -1/2
, the quotient is -0.5
. When you cast it to int, it rounds the number up to 0
.
The floor division operator //
returns the quotient of the division rounded down to the nearest integer. In the case of -1//2
, the quotient is -1
, because -1
divided by 2
is -0.5
, which is rounded down to -1
.
That's why -1//2 = -1
and int(-1/2) = 0
in python.