【问题标题】:Numpy elementwise multiplication (unexpected integer overflow)Numpy 元素乘法(意外的整数溢出)
【发布时间】:2019-01-08 09:45:44
【问题描述】:

我正在使用 Python 3.7 和 numpy 1.15.2,并且在元素乘法中遇到了我不理解的行为。以下对我来说很直观:

import numpy as np
a = np.array([[30000,4000]])
b = np.array([[70000,8000]])
np.multiply(a,b)

给予

array([[2100000000,32000000]])

但是,当我这样做时

a = np.array([[30000,40000]])
b = np.array([[70000,80000]])
np.multiply(a,b)

我明白了

array([[ 2100000000, -1094967296]])

我猜结果应该是array([[ 30000*70000, 40000*80000]])。负数从何而来?我应该怎么做才能得到预期的数组?

【问题讨论】:

标签: python numpy elementwise-operations


【解决方案1】:

默认情况下,numpy 似乎将普通数字解释为 np.int32(范围从 -231 ... 231 - 1),这将溢出40000*80000,因为3200000000 > 2**31 - 1 (= 2147483647)

import numpy as np

a = np.array([[30000,40000]])
b = np.array([[70000,80000]])
np.multiply(a,b)
Out: array([[ 2100000000, -1094967296]])

type(a[0][0])
Out: numpy.int32

您可以通过明确设置更适合的数据类型来解决此问题:

a = np.array([[30000,40000]], dtype=np.int64)
b = np.array([[70000,80000]], dtype=np.int64)
np.multiply(a,b)
Out: array([[2100000000, 3200000000]], dtype=int64)

a = np.array([[30000,40000]], dtype=np.uint32)
b = np.array([[70000,80000]], dtype=np.uint32)
np.multiply(a,b)
Out: array([[2100000000, 3200000000]], dtype=uint32)

【讨论】:

    猜你喜欢
    • 2015-03-30
    • 2017-09-17
    • 1970-01-01
    • 2015-05-13
    • 2020-06-12
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2020-03-27
    相关资源
    最近更新 更多