Numpy RuntimeWarning:在 log10 中遇到被零除

Numpy RuntimeWarning: divide by zero encountered in log10

来自 this post 我了解到 log10() 在 where 被求值之前求值。简而言之,我不理解该问题中提供的答案。另外,为什么要先评估 log10(),肯定会导致不必要的计算?

merge_y = np.where(n <= 1, 1, n * np.log10(n))

import matplotlib.pyplot as plt
import numpy as np

n = np.arange(0, 10, 0.0001)

merge_y = np.where(n <= 1, 1, n * np.log10(n))
insertion_y = n*n

plt.plot(n, merge_y,'g')
plt.plot(n,insertion_y,'r')
plt.grid(True)
plt.xlabel('n')
plt.ylabel('T(n)')
plt.title('Time complexities of merge and insertion sort w/ input size n')
plt.show()

为什么不这样做:

merge_y = np.ones_like(n)
mask = (n > 1)
n_m = n[mask]
merge_y[mask] = n_m * np.log10(n_m)

您必须了解 np.where 是基于逻辑索引工作的,您将其视为一个循环。 np.where 所做的是

np.where(return_this_logical_indexes, From_this_array_if_true, From_this_array_if_false)

但是为了做到这一点,那些数组必须存在,如果它是一个函数,那么它会评估它以获得一个数组,然后用条件创建的逻辑数组对其进行索引。

您认为它更像是一个列表理解,例如:

merge_y = [x*np.log10(x) if x>=1 else 1 for x in n]