为什么在python中,很大的float值之间的比较会失败? [英] Why do comparisions between very large float values fail in python?
问题描述
据我了解, sys.float_info.max
是最大的浮点值。但是,似乎无法比较这么大的值。
In my understanding, sys.float_info.max
is the largest possible float value. However, it seems that comparing such large values fail.
import math
import sys
m = sys.float_info.max # type 'float'
m == m # True
m < m # False
m > m # False
m == m-1.0 # True
m < m-1.0 # False
m > m-1.0 # False
m == m-1e100 # True
m < m-1e100 # False
m > m-1e100 # False
m == m-1e300 # False
m > m-1e300 # True
m < m-1e300 # False
我认为这是因为精度有限吗?如果是这样,我可以在什么数值范围内安全操作?
I assume that's because of the limited precision? If so, in what numerical range can i operate safely?
上面的代码是使用Python 3.5.2。运行的。
推荐答案
在运行Python的典型计算机上,Python浮点数有53位精度。如果您尝试进一步,Python将消除最小的部分,以便可以正确表示数字。
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.
因此,值1被吸收或取消以能够表示
So the value 1 is absorbed or cancelled to be able to represent the high value you're trying to compute.
通过减去(或加)乘以float epsilon的值来获得限制。
The limit is obtained by subtracting (or adding) the value multiplied by float epsilon.
在我的机器上:
maxfloat == 1.7976931348623157e+308
epsilon == 2.220446049250313e-16
示例测试代码
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
是您必须减去的最小值,以使比较失败。始终相对于 m
值。
m*eps
is the smallest value you have to subtract to make comparison fail. It's always relative to the m
value.
这篇关于为什么在python中,很大的float值之间的比较会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!