python 中的矩阵乘法有什么问题

问题描述 投票:0回答:1

在下面的代码(Jupiter Notebook)中,输出给出了错误,如何纠正代码?

import numpy as np

A = [1,22,231,1540]

B = [[-1,1,0],[1,-1,1],[0,6,0],[0,6,0]]

C = [[113401201],[10649],[1]]

result = np.dot(np.dot(A, B),C)

print(result)

输出

 [-1800609408]

实际答案是

我想找到错误并改正它

python numpy matrix-multiplication
1个回答
1
投票

您可能在 32 位平台上运行此代码(其中整数为 32 位):

A = np.array(A, dtype=np.int32)
B = np.array(B, dtype=np.int32)
C = np.array(C, dtype=np.int32)

result = np.dot(np.dot(A, B), C)

print(result)

打印(错误,因为值溢出):

[-1800609408]

要纠正它,请使用 64 位值:

A = np.array(A, dtype=np.int64)
B = np.array(B, dtype=np.int64)
C = np.array(C, dtype=np.int64)

result = np.dot(np.dot(A, B), C)

print(result)

打印:

[2494357888]
© www.soinside.com 2019 - 2024. All rights reserved.