1

why does python floor division operator behaves like this? I came across this code snippet and result was quite surprising.

a = 1 // 10 
b = -1 // 10
print a,b
a= 0
b=-1

printing output obtained results are a=0 and b= -1.

why does a=0 and b= -1?

// does floor division, so it's always rounding down?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Roshan Bagdiya
  • 2,048
  • 21
  • 41
  • 1
    Yes, the "floor" means "down". – Klaus D. Sep 30 '17 at 05:15
  • 3
    In my country, the floors are down and the ceilings are up; we find this more convenient than other arrangements. ;) – PM 2Ring Sep 30 '17 at 05:29
  • 1
    It's straight out of standard mathematics: The floor operator rounds down to the next integer. So floor(3.9) equals floor(3.1) equals 3, and floor(-3.9) equals floor(-3.1) equals -4. You will find this definition throughout computer languages and libraries. – Tom Karzes Sep 30 '17 at 05:33
  • 1
    On a more serious note, it's very handy that Python's integer division is floor division. For example, here's a demo of finding the greatest multiple of 5 ≤ a given number: `[(i, i//5*5) for i in range(-10, 11)]`. If `//` rounded towards zero instead of towards negative infinity that wouldn't work properly for negative numbers. And we can also use `//` to perform _ceiling_ division. So this list comp finds the smallest multiple of 5 ≥ a given number: `[(i, i//-5*-5) for i in range(-10, 11)]` – PM 2Ring Sep 30 '17 at 05:33
  • On a related note, this behaviour is consistent with the fact that in `r = a % b` the sign of `r` is always the same as the sign of `b` because if `q, r = a // b, a % b` then we want `a == q * b + r` to be true. – PM 2Ring Sep 30 '17 at 05:44

2 Answers2

6

Floor function returns the greatest integer not greater than x. For example if the input is 2.25 then output will be 2.00. So in case of -0.1 greatest integer less than -0.1 would be -1.

4

// in Python is a "floor division" operator. That means that the result of such division is the floor of the result of regular division (performed with / operator).

The floor of the given number is the biggest integer smaller than the this number. For example

7 / 2 = 3.5 so 7 // 2 = floor of 3.5 = 3.

For negative numbers it is less intuitive: -7 / 2 = -3.5, so -7 // 2 = floor of -3.5 = -4. Similarly -1 // 10 = floor of -0.1 = -1.

// is defined to do the same thing as math.floor(): return the largest integer value less than or equal to the floating-point result. Zero is not less than or equal to -0.1.