The expression 6 // 4
yields 1
, where floor division produces the whole number after dividing a number.
But with a negative number, why do
A useful way to understand why floor division // yields the results it does for negative values is see this as complimenting the modulo, or remainder, % operator.
5/3 is equivalent to 1 remainder 2
i.e.
5//3 = 1
5%3 = 2
But
-5/3 = -2
-5%3 = 1
Or
-2 + 1/3rd which is -1.6667 (ish)
It can seem strange, but it ensures results such as
-2,-2,-2,-1,-1,-1,0,0,0,1,1,1,2,2,2,3,3,3
etc. when generating sequences.
//
in Python is a "floor division" operator. That means that the result of such division is the floor of the result of regular division (performed with / operator).
The floor of the given number is the biggest integer smaller than the this number. For example
7 / 2 = 3.5 so 7 // 2 = floor of 3.5 = 3.
For negative numbers it is less intuitive: -7 / 2 = -3.5,
so -7 // 2 = floor of -3.5 = -4
. Similarly -1 // 10 = floor of -0.1 = -1.
//
is defined to do the same thing as math.floor()
: return the largest integer value less than or equal to the floating-point result. Zero is not less than or equal to -0.1.
Floor division will also round down to the next lowest number, not the next lowest absolute value.
6 // 4 = 1.5
, which rounds down to 1, and up to 2.
-6 // 4 = -1.5
, which rounds down to -2, and up to -1.
The //
operator explicitly floors the result. Quoting the Binary arithmetic operations documentation:
the result is that of mathematical division with the ‘floor’ function applied to the result.
Flooring is not the same thing as rounding to 0; flooring always moves to the lower integer value. See the math.floor() function:
Return the floor of x, the largest integer less than or equal to x.
For -6 // 4
, first the result of -6 / 4
is calculated, so -1.5
. Flooring then moves to the lower integer value, so -2
.
If you want to round towards zero instead, you'll have to do so explicitly; you could do this with the int()
function on true division:
>>> int(-6 / 4)
-1
int()
removes the decimal portion, so always rounds towards zero instead.