假设 0 * 无穷大 = 0 时如何在 NumPy 中乘法.outer()?

Meh*_*dad 5 python floating-point numpy infinity

numpy.multiply.outer我正在尝试在多维数组上使用,并且我确实需要它来假设0 * infinity它看到的任何值都为零。我怎样才能有效地做到这一点?

>>> import numpy
>>> numpy.multiply.outer([0.], [float('inf')])
Warning (from warnings module):
  File "__main__", line 2
RuntimeWarning: invalid value encountered in multiply
array([[ nan]])
Run Code Online (Sandbox Code Playgroud)

p-r*_*bot 3

一种解决方案可能是避免使用np.multiply.outer并使用已检查矩阵的元素乘法来查找解决方案,以确定它们是否满足感兴趣的条件(一个数组中为零,inf另一数组中为零)。

import numpy as np
A = np.array([0., 0., 0.4, 2])
B = np.array([float('inf'), 1., 3.4, np.inf])

# Conditions of interest
c1 = (A == 0)
c2 = (B == np.inf)
condition1 = np.multiply.outer(c1, c2)
c3 = (A == np.inf)
c4 = (B == 0)
condition2 = np.multiply.outer(c3, c4)
condition = condition1 | condition2

AA = np.multiply.outer(A, np.ones(B.shape))
BB = np.multiply.outer(np.ones(A.shape), B)

AA[condition] = 0.
BB[condition] = 0.

AA*BB
Run Code Online (Sandbox Code Playgroud)

然而,这可能无法满足发布者的“效率”要求。