为什么在乘以 Numpy 乘积输出时会出现溢出错误?

Fol*_*lau 5 python numpy python-3.x

由于乘以我想要理解的 Numpy 产品的输出,我遇到了溢出警告。它们在我的大型项目中实际使用的简化版本详述如下:

import numpy as np

class MyClass(object):
    def __init__(self,
                 array_1,
                 array_2):

        # Assigning arrays to be used in later methods
        self.array_1 = array_1
        self.array_2 = array_2

        # Assigning some scaling factors to be used in later methods.
        self.value_1 = np.prod(self.array_1.shape)
        self.value_2 = np.prod(self.array_2.shape)
        print("Numpy Product Assignment: {0}, {1}".format(self.value_1, self.value_2))

        # Alternative assignment of scaling factors
        self.alt_value_1 = self.array_1.shape[0] * self.array_1.shape[1]
        self.alt_value_2 = self.array_2.shape[0] * self.array_2.shape[1]
        print("Regular Product Assignment: {0}, {1}".format(self.alt_value_1, self.alt_value_2))

        pass

    def mymethod(self):
        print("Direct Multiplication: {0}".format(80160 * 262144))
        print("Numpy Product Multiplication: {0}".format(self.value_1 * self.value_2))
        print("Regular Product Multiplcation {0}".format(self.alt_value_1 * self.alt_value_2))

if __name__ == '__main__':
    test_array_1 = np.zeros([512, 512], dtype=complex)
    test_array_2 = np.zeros([1002, 80], dtype=complex)

    test_class = MyClass(test_array_1, test_array_2)
    test_class.mymethod()
Run Code Online (Sandbox Code Playgroud)

包括与类结构一起使用以确保完整性,尽管经过大量编辑到最低限度。如果我运行此代码(在 Python 3.6.0 上),我会得到以下输出:

C:/somepath/scratch.py:247: RuntimeWarning: overflow encountered in long_scalars
  print("Numpy Product Multiplication: {0}".format(self.value_1 * self.value_2))
Numpy Product Assignment: 262144, 80160
Regular Product Assignment: 262144, 80160
Direct Multiplication: 21013463040
Numpy Product Multiplication: -461373440
Regular Product Multiplcation 21013463040

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

显然,我可以使用常规乘法来解决这个问题,但我想了解为什么会出现问题以及是否可以按原样解决。我认为我错过了一些dtype=X 的微妙之处,所以我的问题是是什么导致了这些溢出错误?

kaz*_*ase 5

这看起来像是由 32 个整数引起的溢出。您可以像这样将值转换为 64 位:

    self.value_1 = np.prod(self.array_1.shape, dtype=np.int64)
    self.value_2 = np.prod(self.array_2.shape, dtype=np.int64)
Run Code Online (Sandbox Code Playgroud)

如果用于数组构造的值足够小,Numpy 会自动选择 32 位整数类型。在乘法期间,它们不会自动转换为 64 位。