由于我想要了解的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()
包括使用类结构的完整性,尽管经过大量编辑,但最低限度。如果我运行此代码(在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
显然,我可以使用常规乘法解决问题,但我想了解为什么存在问题以及是否可以按原样修复。我认为我错过了一些 dtype = X 微妙之处,所以我的问题是导致这些溢出错误的原因是什么?
答案 0 :(得分:4)
这看起来像是由32个整数引起的溢出。您可以将值转换为64位,如下所示:
self.value_1 = np.prod(self.array_1.shape).astype(np.int64)
self.value_2 = np.prod(self.array_2.shape).astype(np.int64)
如果用于数组构造的值足够小,Numpy会自动选择32位整数类型。在乘法过程中,它们不会自动转换为64位。