Why do comparisions between very large float values fail in python?(为什么在 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.
这篇关于为什么在 python 中非常大的浮点值之间的比较会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 python 中非常大的浮点值之间的比较会失败?


基础教程推荐
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01