Python Integer Division vs. Float Division for Large Numbers

divisionfloating-pointpython

print(10**40//2)
print(int(10**40/2))

Output of the codes:

5000000000000000000000000000000000000000
5000000000000000151893014213501833445376

Why different values? Why the output of the second print() looks so?

Best Answer

The floating point representation of 10**40//2 is not accurate:

>>> format(float(10**40//2), '.0f')
'5000000000000000151893014213501833445376'

That's because floating point arithmetic is only ever an approximation, especially when you go beyond what your CPU can accurately model (as floating point is handled in hardware).

The integer division never has to represent the 10**40 number as a float, it only has to divide the integer, which in Python can be arbitrarily large without precision loss.

Also see:

Also look at the decimal module if you must use higher-precision floating point arithmetic.

Related Question