【问题标题】:Numpy RuntimeWarning: divide by zero encountered in log10Numpy RuntimeWarning:在log10中遇到除以零
【发布时间】:2016-02-12 07:32:03
【问题描述】:

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

merge_y = np.where(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()

【问题讨论】:

  • 您确实意识到,您尝试计算log10(0),对吧?
  • 我看不到在哪里,对于 where(condition,a,b) 如果条件为假则不返回 b,如果条件为真则返回 a...

标签: python numpy logging where divide-by-zero


【解决方案1】:

您必须了解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]

【讨论】:

    【解决方案2】:

    为什么不这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-08
      • 2014-03-03
      • 2021-02-07
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多