【问题标题】:numpy.dot giving incorrect answer for large integersnumpy.dot 对大整数给出不正确的答案
【发布时间】:2018-11-13 05:36:25
【问题描述】:

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

我从mathematica得到的结果,手工是

编辑:如果您需要矩阵:

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

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

【问题讨论】:

  • edit您的问题是数组和代码作为文本,而不是图像。
  • 我尝试复制您的数据,但遗憾的是我无法复制图片中的文字。
  • 试试dtypeint64

标签: python arrays numpy dot-product


【解决方案1】:

正如@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。还有一些discussion on platform-specific issues

【讨论】:

  • 非常感谢,这样的菜鸟错误哈哈
  • numpy 使用 int32 还是 int64 将取决于操作系统和计算机。我的,最近的翻新桌面上的 Linux 使用 int64 作为默认值。
猜你喜欢
  • 2021-06-30
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-24
  • 2013-07-31
相关资源
最近更新 更多