Search code examples
pythoninteger-division

Why does division "/" and floored division "//" operators in python gives different results for divisions with a remainder = 0?


When dividing somewhat large integers with numbers that divides them, I get different results from division / and floored division //.

for instance:

In [1]: a = 123456789012345678

In [2]: int(a/2)
Out[2]: 61728394506172840

In [3]: a//2
Out[3]: 61728394506172839

clearly 2|a, and out[3] is the correct answer, so why the inconsistency from the division operator? what is going on? and, How to make / behave correctly?


Solution

  • / is the floating division operator, thus your integer is stored into a float type. This type cannot store exactly every value, only approximations, see:

    >>> a = 123456789012345678
    >>> a/2
    6.172839450617284e+16
    

    You lose the last digit... 123456789012345678 approximately equals to 6.172839450617284 * 10^16. Look what happens for "huge" numbers:

    >>> float(1234512345123451234512345)
    1.2345123451234512e+24
    

    Floats are basically scientific notation with fixed size mantissa.

    While // is the integer division operator, and integer type (in Python) is of arbitrary precision (only in the domain of integers):

    >>> 2**1000
    10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376