Why do comparisions between very large float values fail in python?

僤鯓⒐⒋嵵緔 提交于 2019-11-29 12:37:45

On a typical machine running Python, there are 53 bits of precision available for a Python float. If you try to go further, Python will eliminate the smallest part so the number can be properly represented.

So the value 1 is absorbed or cancelled to be able to represent the high value you're trying to compute.

The limit is obtained by subtracting (or adding) the value multiplied by float epsilon.

On my machine:

maxfloat == 1.7976931348623157e+308
epsilon == 2.220446049250313e-16

sample test code

import math
import sys

m = sys.float_info.max                        # type 'float'
eps = sys.float_info.epsilon

print(m == m-(m*(eps/10)))   # True
print(m == m-(m*eps))        # False

m*eps is the smallest value you have to subtract to make comparison fail. It's always relative to the m value.

Maybe if you try printing those numbers, you will better understand what they are:

>>> sys.float_info.max
1.7976931348623157e+308
>>> sys.float_info.max - 1.0
1.7976931348623157e+308
>>> sys.float_info.max - 1e100
1.7976931348623157e+308
>>> sys.float_info.max - 1e300
1.7976931248623157e+308

Note that the printout does not nearly describe all the problems one can encounter with floating point number precision, but in this case, the "problems" are trivial. You can see that only the last number is different.

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