How Does Floor Division Work in Python? [Duplicate]

How Does Floor Division Work in Python? [Duplicate]
  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?

2

3 Answers

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.

2

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.

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

4
Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.