gpt4 book ai didi

python - 为什么小整数缓存似乎不适用于 Python 3 中 round() 函数的 int 对象?

转载 作者:行者123 更新时间:2023-12-03 17:04:13 26 4
gpt4 key购买 nike

您能解释一下为什么在 Python v3.8 中会发生这种情况吗?

a=round(2.3)
b=round(2.4)

print(a,b)
print(type(a),type(b))

print(a is b)
print(id(a))
print(id(b))
输出:
2 2
<class 'int'> <class 'int'>
False
2406701496848
2406701496656
>>>
2 在小整数缓存范围内。那么为什么会有不同的对象具有相同的值呢?

最佳答案

看起来像在 3.8 中,PyLong_FromDouble (这是 float.__round__ 最终委托(delegate)给的)explicitly allocates a new PyLong object and fills it in manually , 没有对其进行规范化(通过 IS_SMALL_INT 检查和 get_small_int 缓存查找函数),因此它不检查小的 int缓存以解析为规范值。
由于 issue 37986: Improve perfomance of PyLong_FromDouble(),这将在 3.9 中发生变化,现在已将其委托(delegate)给 PyLong_FromLongdouble小到可以无损地表示为 C long .作为副作用,这将使用小的 int缓存,如 PyLong_FromLong可靠地标准化小值。

关于python - 为什么小整数缓存似乎不适用于 Python 3 中 round() 函数的 int 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64019287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com