Muktadir Rahman
Muktadir Rahman

Reputation: 161

Why are the results of integer division and converting to an int after division different for large numbers?

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?

Upvotes: 2

Views: 1287

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124978

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.

Upvotes: 11

Related Questions