-1

Why does integer division truncate when N // D --> N > 0 and N < D when N is positive, but doesn't when N is negative?

Example 12 // 25 = 0

BUT -12 // 25 = 1

This is in python 3.

Lucas Hendren
  • 2,786
  • 2
  • 18
  • 33

1 Answers1

0

Sure, the answer here is that Python's integer division floors - it rounds down, always. So an instructive example would be something that doesn't yield 0, so it's more obvious:

>>> 10 // 3
3
>>> -10 // 3
-4
  • 10/3 = 3.3333..., which rounds down to 3.
  • -10/3 = -3.3333...., which rounds down to -4.

So, even if it's a positive fractional part, like 7 // 4, which yields 1.75, Python rounds down to 1. The mathy explanation is in the linked blog post, this is just a mechanics explanation.

tmcw
  • 11,536
  • 3
  • 36
  • 45