python - 数组乘以标量的意外结果

标签 python numpy multidimensional-array

来自“就在我以为我开始使用 Numpy 的时候”文件...

>>> import numpy as np
>>> y = np.array((1650, 2300, 2560, 3710)) * 1000000
>>> y
array([ 1650000000, -1994967296, -1734967296,  -584967296])

我的老数学老师会同意第一个结果,但其他人呢???

FWIW,在 64 位 Win 10 上运行 Python 3.6.3,也得到(如预期的那样)

>>> 2300 * 1000000
2300000000

最佳答案

这是因为整数的最大值为 2^31 - 1 = 2147483647。

您的第一个值小于该值,但其他 3 个值更大。因此你得到“循环”。请注意:

-1994967296 = -2147483648 + (2300000000 - 2147483647 - 1)

所以基本上你已经达到最大值 (2147483647) 加 1 达到最低值 (-2147483648),然后从那里继续。

你可以通过强制 64 位精度来解决这个问题

>>> import numpy as np
>>> y = np.array((1650, 2300, 2560, 3710), dtype='int64') * 1000000
>>> y
array([1650000000, 2300000000, 2560000000, 3710000000], dtype=int64)

关于python - 数组乘以标量的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771721/

相关文章:

python - 阻止 Visual Studio 的链接器在 Debug模式下查找 python39_d.lib

python - python 中的高斯(-Legendre)正交

python - 通过 View 动态改变django的DEBUG模式

python - 从二进制文件中读取 UTF-8 字符串

python - numpy 3D meshgrid 仅作为 View

python - numpy sum 不同意

php - 将多维数组(javascript)转换为 JSON(或类似格式)以进行传输

c - 以下两个声明有什么不同吗

python - 在 numba 的 jitclass 中索引多维 numpy 数组

python - 如果文件在两台机器中都丢失,如何以非零状态退出 shell 脚本?