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

n88*_*88b 5 python arrays numpy dot-product

我正在研究一些线性代数的东西,并且根本不明白为什么numpy给出以下内容:

在此输入图像描述

我从mathematica得到的结果是

在此输入图像描述

编辑:如果您需要矩阵:

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

A = [[9, 4, 1], [2, 0, 8], [-8, 8, -8]]
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 3

正如 @PaulPanzer 所指出的,您需要使用np.int64dtype 数组。NumPy 用于平台/系统配置1np.int32上的输入数组,并且不检查整数溢出。

但是,矩阵乘法的结果包含太大而无法存储在 中的整数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]]
Run Code Online (Sandbox Code Playgroud)

1这是另一个例子。还有一些关于特定于平台的问题的讨论