2

I was just coding something when I noticed something odd:
2/3 returns 0, which is logical, because that's 0.6666666666666666, which gets rounded towards 0, because its an int.
int(2/3.0) returns the same, because int(0.6666666666666666) returns 0.

now:
-2/3.0 returns -0.6666666666666666 which is logical, but here comes the part that is confusing me,
int(-0.6666666666666666) returns 0 (because ints round towards 0).
But -2/3 returns -1...
Why is this?
Shouldn't this also return 0?
After all int(-0.6666666666666666) returns 0, so why does -2/3 return -1?


TL;DR: 2/3 == 0, but -2/3 != 0?

Best regards, Sjaak.

sjaak31367
  • 43
  • 3

1 Answers1

7

/ floors, it doesn't truncate. It is not the same operation as int() applied to a floating point division. From the Binary arithmetic operations documentation:

the result is that of mathematical division with the ‘floor’ function applied to the result.

int() truncates:

If x is floating point, the conversion truncates towards zero.

Flooring always rounds down, so for negative numbers that'll round away from 0.

It should be noted that the - unary operator has a higher operator precedence than the / division operator, so the expression is parsed as (-2)/3, not -(2/3).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343