Numpy 在 windows 和 unix 上返回不同的结果

标签 numpy

<分区>

给定以下代码:

import numpy as np
c = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

c = np.array(c)
print((c * c.transpose()).prod())

在我的 Windows 机器上它返回 "-1462091776"(不确定它是如何从所有这些正数中得到负数的)。 在 ubuntu 上它返回 "131681894400"

有人知道这里发生了什么吗?

编辑:显然这是一个溢出问题。 (感谢@rafaelc!) 但它是可重现的(也感谢@richardec 的测试)

所以现在问题变成了..这是我应该报告的错误吗?我应该向谁报告?

最佳答案

我有足够多的评论,我认为“回答”是必要的。

发生了什么事?

Not sure how it got a negative from all those positives

正如@rafaelc 指出的那样,您遇到了整数溢出。您可以在 wikipedia link 阅读更多详细信息。已提供。

溢出的原因是什么?

根据 this thread , numpy 使用操作系统的 C long 类型作为整数的默认 dtype。所以当你写这行代码时:

c = np.array(c)

dtype 默认为 numpy 的默认整数数据类型,即操作系统的 C long。在 Microsoft 的 Windows C 实现中,long 的大小为 4 字节(x8 位/字节 = 32 位),因此您的 dtype 默认为 32 位整数。

为什么这个计算会溢出?

In [1]: import numpy as np

In [2]: np.iinfo(np.int32)
Out[2]: iinfo(min=-2147483648, max=2147483647, dtype=int32)

32 位带符号整数数据类型可以表示的最大数字是 2147483647。如果您只从一个轴来看您的产品:

In [5]: c * c.T
Out[5]:
array([[ 1,  8, 21],
       [ 8, 25, 48],
       [21, 48, 81]])

In [6]: (c * c.T).prod(axis=0)
Out[6]: array([  168,  9600, 81648])

In [7]: 168 * 9600 * 81648
Out[7]: 131681894400

您可以看到 131681894400 >> 2147483647(在数学中,符号 >>> 表示“大得多”)。由于 131681894400 远大于 32 位 long 可以表示的最大整数,因此发生溢出。

但是在Linux下没问题

在 Linux 中,long 是 8 个字节(x8 位/字节 = 64 位)。为什么?这是 an SO thread在评论中对此进行了讨论。

“这是一个错误吗?”

不,虽然这很烦人,我承认。

就其值(value)而言,明确您的数据类型通常是个好主意,所以下次:

c = np.array(c, dtype='int64')

# or
c = np.array(c, dtype=np.int64)

我应该向谁报告错误?

同样,这不是错误,但如果是,您会在 numpy github 上提出问题(您还可以在其中细读源代码)。某处有证据证明 numpy 如何使用操作系统的默认 C long,但我没有足够的能力去挖掘它。

关于Numpy 在 windows 和 unix 上返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72482769/

相关文章:

python - numpy 列表理解和 +=/-= 运算符

Python - 获取 Pandas 的 Apply 函数上的值的索引

python - 汇总分组 Pandas 数据框中的行并返回 NaN

python - 带有数组和标量的 Numpy 数学?

python - 为什么我得到 "ufunc ' multiply' did not contain a loop with signature matching types dtype ('S32' ) dtype ('S32' ) dtype ('S32' )"with values from raw_input

python | NumPy |坐标 - 地理坐标转换的问题

python - 值错误 : NumPy boolean array indexing assignment cannot assign 0 input values to the N output values where the mask is true

python - 将元组列表转换为 numpy 数组并 reshape 它?

python - 将两个 nparray 乘以 python

python - 根据条件在 numpy 数组的元素中进行数学运算的有效方法