为了账号安全,请及时绑定邮箱和手机立即绑定

python里面正无穷和负无穷问题?

python里面正无穷和负无穷问题?

HUWWW 2019-02-21 10:22:33
print id(float('inf')), id(float('-inf')) print type(float('inf')), type(float('-inf')) print float('inf') == float('-inf') 输出 35997760 35997760 <type 'float'> <type 'float'> False id相同,为何值却不同?原理是什么?
查看完整描述

1 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

Python的文档在id()中有这样一句话:

Return the ``identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)

里面说,两个生存期不重叠的对象有可能有相同的id()值,正如你在C里面malloc()之后立刻free(),然后又分配,两次的内存极有可能是相同的。在你的print id(float('inf')), id(float('-inf'))中生存期并没有重叠,因为在id()返回了它的id之后float('inf')就因为不再被引用而被释放了,生存期结束;而后下一个float('-inf')就被Python分配了相同的id。这里要补充,这里id是否相同是实现相关的,也就是说,可能CPython会相同,而JPython未必,IronPython也未必。

当然了,等号在判断float是否相等的时候,是不关心它的id,只关心它的值。==在关心id的情况,只有在比较类的实例的时候,int, float, str, list, dict依然是判断值:

>>> class C:
...  pass
... 
>>> a = C()
>>> b = C()
>>> a == b
False

然而整数又是不同的状况,这时为什么呢?这时因为Python有一个small_int缓存(有多小呢,CPython 2.7的实现是规定在[-5, 256]),它将小整数缓存起来,每次引用到这个整数就从缓存里拿对象,从而避免频繁内存分配,于是就造成了这个著名的情况:

>>> a = 1
>>> id(a)
33739096
>>> b = 1
>>> id(b)
33739096
>>> b = 2
>>> id(b)
33739072
>>> a += 1
>>> id(a)
33739072
查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 841 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信