Floor division with negative number

11,854

Solution 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.

Solution 2

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.

Share:
11,854
Naz Islam
Author by

Naz Islam

I am a software developer and blogger at Subtle Coding. This is my own blog where I share my programming experiences. I update this blog on a weekly basis to teach people best practices of programming. Currently I am pursuing my Computer Science bachelor degree from SUNY Plattsburgh. I like solving problems and mathematics. Besides writing code, I like writing technical essays and reading biographys.

Updated on June 05, 2022

Comments

  • Naz Islam
    Naz Islam almost 2 years

    The expression 6 // 4 yields 1, where floor division produces the whole number after dividing a number.

    But with a negative number, why does -6 // 4 return -2?