为什么有两个np.int64s公司在numpy.core.numeric.\u typelessdata(为什么是数字.int64不是numpy.int64?)

2024-09-30 18:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这不是一个问题,而是一个好奇心。在

在64位linux上的解释器中,我可以执行

In [10]: np.int64 == np.int64
Out[10]: True

In [11]: np.int64 is np.int64
Out[11]: True

太好了,正是我所期待的。 但是我发现了numpy.core.numeric模块

^{pr2}$

奇怪为什么数字.int64进去两次?让我们调查一下。在

In [23]: _typelessdata[0] is _typelessdata[-1]
Out[23]: False
In [24]: _typelessdata[0] == _typelessdata[-1]
Out[24]: False
In [25]: id(_typelessdata[-1])
Out[25]: 139990931572128
In [26]: id(_typelessdata[0])
Out[26]: 139990931572544
In [27]: _typelessdata[-1]
Out[27]: numpy.int64
In [28]: _typelessdata[0]
Out[28]: numpy.int64

哇哦,他们不一样。这是怎么回事?为什么有两个np.int64是的?在


Tags: 模块incorenumpyidfalsetrueis
2条回答

Here是在numeric.py内构造_typelessdata的行:

_typelessdata = [int_, float_, complex_]
if issubclass(intc, int):
    _typelessdata.append(intc)

if issubclass(longlong, int):
    _typelessdata.append(longlong)

intc是一个与C兼容的(32位)有符号整数,int是本机Python 整数,可能是32位或64位,具体取决于平台。在

  • 位{32位Python也是本机类型 issubclass(intc, int)返回True,而intc被附加到_typelessdata, 结果是这样的:

    ^{pr2}$

    注意_typelessdata[-1] is numpy.intc,而不是{}。

  • 在64位系统中,int是64位,因此issubclass(longlong, int)返回{},并且longlong被附加到_typelessdata,结果是:

    [numpy.int64, numpy.float64, numpy.complex128, numpy.int64]
    

    在这种情况下,正如Joe所指出的,(_typelessdata[-1] is numpy.longlong) == True


更大的问题是为什么_typelessdata的内容是这样设置的。 我在numpy源代码中唯一能找到_typelessdata的地方 实际使用的是this line^{}的定义内 在同一个文件中:

skipdtype = (arr.dtype.type in _typelessdata) and arr.size > 0

_typelessdata的目的是确保np.array_repr正确地打印dtype恰好与(依赖于平台的)本机Python整数类型相同的数组的字符串表示。在

例如,在32位系统中,int是32位:

In [1]: np.array_repr(np.intc([1]))
Out[1]: 'array([1])'

In [2]: np.array_repr(np.longlong([1]))
Out[2]: 'array([1], dtype=int64)'

而在64位系统中,int是64位:

In [1]: np.array_repr(np.intc([1]))
Out[1]: 'array([1], dtype=int32)'

In [2]: np.array_repr(np.longlong([1]))
Out[2]: 'array([1])'

上面一行中的arr.dtype.type in _typelessdata检查可确保为适当的依赖于平台的本机整数dtypes跳过打印{}。在

我不知道它背后的全部历史,但第二个int64实际上是{}。在

In [1]: import numpy as np

In [2]: from numpy.core.numeric import _typelessdata

In [3]: _typelessdata
Out[4]: [numpy.int64, numpy.float64, numpy.complex128, numpy.int64]

In [5]: id(_typelessdata[-1]) == id(np.longlong)
Out[5]: True

numpy.longlong应该是directly correspond to C's ^{} type。C的long long被指定为至少64位宽,但确切的定义由编译器决定。在

我的猜测是numpy.longlong在大多数系统上是numpy.int64的另一个实例,但是如果C编译器将long long定义为比64位更宽的内容,则允许它是不同的。在

相关问题 更多 >