- 5//2 = 2;
- 5//7 = 0;
- 5//-6 = -1;
- 5//-2 = -3;
- 5//-3 = -2;
- 5/-4 = -2;
Can someone explain the logic behind this?
Can someone explain the logic behind this?
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.
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
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.