Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...