问题描述
据我了解,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 中非常大的浮点值之间的比较会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)