pythoninteger-division

Different types of Integer division in Python


In terms of the resulting value (ignoring the resulting data type), are the following the same in Python if x and y are both numbers?

int(x / y)
x // y

If so, which is better to use in real application? And why?

P.S. Are there any other methods in Python that achieve similar result but more suitable in different use cases? For example, if y is 2^n, then we can do bitwise shifting - that's all I know.


Solution

  • They have different behaviours.

    a//b rounds down, so 5//-2 == -3.

    int(a/b) rounds towards zero, so int(5/-2) == -2

    Edit to add: I just realized something important! a/b always produces a float. If a is too large for the quotient to be represented by a float (i.e, the result is greater than about 10^308), then a/b will fail with an OverflowError. This does not happen with a//b. Observe:

    >>> int(10**1000/3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    OverflowError: integer division result too large for a float
    >>> 10**1000//3
    333333333333333333333333333333333333333333333333333...
    

    Additionally, the floating point number resulting from the division will have rounding errors. Beyond about 2^53, 64-bit floating point numbers cannot accurately represent all integers, so you will get incorrect results:

    >>> int(10**22/3)
    3333333333333333508096
    >>> 10**22//3
    3333333333333333333333