-4
  1. 5//2 = 2;
  2. 5//7 = 0;
  3. 5//-6 = -1;
  4. 5//-2 = -3;
  5. 5//-3 = -2;
  6. 5/-4 = -2;

Can someone explain the logic behind this?

Usr_Dev
  • 77
  • 1
  • 1
  • 9
  • http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html might help you. – Akshat Harit Jul 15 '15 at 20:18
  • 1
    similar to [Integer division & modulo operation with negative operands in Python](http://stackoverflow.com/questions/14348219/integer-division-modulo-operation-with-negative-operands-in-python) – vaultah Jul 15 '15 at 20:18

3 Answers3

4

This is always true, ignoring floating point issues:

b*(a // b) + a % b == a

This is also always true:

((b > 0) == (a % b > 0)) or (a % b == 0)

Finally,

abs(a % b) < abs(b)

To provide this behavior, integer division rounds towards negative infinity, rather than towards zero.

Kevin
  • 28,963
  • 9
  • 62
  • 81
3

Floor division works in Python the way it's mathematically defined.

x // y == math.floor(x/y)

In other words x // y is the largest integer less than or equal to x / y

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Or: `fdiv = lambda a, b: (a - a % b) / b` – Malik Brahimi Jul 15 '15 at 20:22
  • @AdamSmith It certainly doesn't work that way. Compare `1 // 0.1` to `math.floor(1 / 0.1)`. – Selcuk Aug 20 '19 at 23:45
  • @Selcuk that appears to be just floating point inaccuracies. `1 / 0.1` is very nearly 10, so flooring it becomes 9. `math.floor(1 / 0.1)` lets the `__truediv__` operator handle the floating point weirdness which it correctly accounts for, then floors afterwards. – Adam Smith Aug 21 '19 at 06:15
  • @Selcuk note that `1 // Decimal('0.1') == Decimal('10')`. Similarly for a decimal whose binary floating-point is precise like `0.5`: `5 // 0.5 == 10` – Adam Smith Aug 21 '19 at 06:17
3

The way it should:

5 / 2 = 2.5        (2)
5 / 7 = 0.714285   (0)
5 / -6 = −0.8333   (-1 is the integer below -0.833333)
5 / -2 = −2.5      (-3)
5 / -3 = −1.6666   (-2)

It's a basic floor. It divides it, and then makes it the integer below.

Tim
  • 2,563
  • 1
  • 23
  • 31