shahanneda
shahanneda

Reputation: 311

Difference in Python 3 between `int( x / y )` and `x // y`?

Is there a difference (and if so why?) in python (possibly in rounding) between floor division x // y vs division then casting such as int(x / y)?

Upvotes: 1

Views: 562

Answers (2)

Amal Rajan
Amal Rajan

Reputation: 153

I'm probably late, but anyways.

Building on others' answers, the most important differnce you'll likely encounter is:

>>> -11 // 5
-3
>>> int(-11 / 5)
-2

tl;dr: These are not the same operations.

Upvotes: 0

Masklinn
Masklinn

Reputation: 42502

Well yes, as its name indicates // floors aka rounds towards -∞. int, on the other hand:

For floating point numbers, this truncates towards zero.

So they will diverge for any division in the negatives.

Upvotes: 4

Related Questions