numpy.dot 给出大整数的错误答案

numpy.dot giving incorrect answer for large integers

我正在研究一些线性代数的东西,只是想不通为什么 numpy 给出以下内容:

我从 mathematica 手工得到的结果是

编辑:如果您需要矩阵:

test = [[19722145, -21016468, 51417377],
        [-185674670, 298847128, -428429486],
        [289326728, -516012704, 691212936]]

A = [[9, 4, 1], [2, 0, 8], [-8, 8, -8]]

如@PaulPanzer 所述,您需要使用 np.int64 dtype 数组。 NumPy 使用 np.int32 作为您的输入数组 在您的平台/系统配置上 1 并且不检查整数溢出。

但是,矩阵乘法的结果包含整数,这些整数太大而无法存储在 np.int32 中。

由于 NumPy 不会自动将输入数组向上转换为 np.int64,您需要在定义数组时或通过向上转换明确指定 np.int64

import numpy as np

test = np.array([[19722145, -21016468, 51417377],
                 [-185674670, 298847128, -428429486],
                 [289326728, -516012704, 691212936]],
                dtype=np.int64)

A = np.array([[9, 4, 1],
              [2, 0, 8],
              [-8, 8, -8]],
             dtype=np.int64)

res = np.dot(test, A)

print(res)

[[ -275872647   490227596  -559748615]
 [ 2354058114 -4170134568  5632538242]
 [-3957788344  6687010400 -9368478392]]

1 这里是 another example. There's also been some discussion on platform-specific issues.