为什么在 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 的典型机器上,有 53 位精度可用于 Python 浮点数.如果您尝试更进一步,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.

相关文章