1

I found that -1 // 2 is equal to -1 (Why not 0?), but int(-1 / 2) is equal to 0 (as I expected). It's not the case with 1 instead of -1, so both 1 // 2 and int(1 / 2) is equal to 0.

Why the results are different for -1?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
g00dds
  • 195
  • 8

1 Answers1

1

In Python, the division operator / and the floor division operator // have different behavior.

The division operator / returns a floating-point number that represents the exact quotient of the division. In the case of -1/2, the quotient is -0.5. When you cast it to int, it rounds the number up to 0.

The floor division operator // returns the quotient of the division rounded down to the nearest integer. In the case of -1//2, the quotient is -1, because -1 divided by 2 is -0.5, which is rounded down to -1.

That's why -1//2 = -1 and int(-1/2) = 0 in python.

godot
  • 3,422
  • 6
  • 25
  • 42
  • 2
    `0` is rounding *up*. – Barmar Jan 19 '23 at 21:46
  • 2
    Technically, it's not rounding up, either. It's rounding *towards 0*, which is true for both positive and negative arguments. It's better not to refer to it as rounding at all, as rounding in Python treats 1/2 specially (it could round up or down depending on whether the integer part is even or odd, the so-called banker's algorithm). `int` *truncates* by discarding the fraction. (I said without regard to sign in a comment, but that's not entirely true. The sign plays a part in deciding what the integer portion is: `-0.5` is `0 - 0.5`, not `-1 + 0.5`.) – chepner Jan 19 '23 at 21:55