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

自作多情 提交于 2019-12-20 03:16:49

问题


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?


回答1:


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:

  • Floating Point Arithmetic: Issues and Limitations in the Python tutorial
  • What Every Programmer Should Know About Floating-Point Arithmetic
  • What Every Computer Scientist Should Know About Floating-Point Arithmetic

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



来源:https://stackoverflow.com/questions/26740938/why-are-the-results-of-integer-division-and-converting-to-an-int-after-division

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!