【问题标题】:Calculation of xlogx with numpy用 numpy 计算 xlogx
【发布时间】:2018-10-16 08:19:57
【问题描述】:

我想用任意小的正 x 来计算 x ln x,或者 x = 0 没有下溢或除以零。我该怎么做呢?

我用谷歌搜索了“python numpy xlnx OR xlogx”,但没有任何有意义的结果。

x = 0
a = x * np.log(x)
b = np.log(np.power(x,x))
print(a,b)

for i in range(-30,30,10):
    x = 10.**-i 
    a = x * np.log(x)
    b = np.log(np.power(x,x))
    print(a,b)

nan 0.0
6.90775527898e+31 inf
4.60517018599e+21 inf
230258509299.0 inf
0.0 0.0
-2.30258509299e-09 -2.30258512522e-09
-4.60517018599e-19 0.0

编辑添加: 这是导致我的问题的另一个问题。但是计算 xlogx 的最佳方法是什么?当 x = 0 时,直接的方法会导致 nans。

【问题讨论】:

  • 我强烈不同意重复的建议,这是关于 np.log/np.log10 的问题,不解决 0 ln 0 = 0。

标签: python numpy logarithm


【解决方案1】:

您可以使用 scipy 中的 xlogy 函数来做到这一点:

from scipy.special import xlogy
from numpy import log

>>> xlogy(10, 10)

23.0258509299

>>> 10 * log(10)

23.0258509299

>>> xlogy(0, 0)

0.0

【讨论】:

  • 链接到 the implementation 供好奇的人使用。
  • 查看@bluenote10 链接的实现,看起来使用xlogy(x, x) 的实数相当于0 if x == 0 else x * log(x)
猜你喜欢
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
相关资源
最近更新 更多