Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...