Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation of xlogx with numpy

I want to calculate x ln x with arbitrarily small positive x, or x = 0 without underflow or division by zero. How do I go about doing it?

I have googled "python numpy xlnx OR xlogx" with no meaningful result.

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

Edit to add: It was another issue causing my problem. But what is the best way to calculate xlogx? The straightforward method causes nans when x = 0.

like image 201
HK Tong Avatar asked May 06 '18 10:05

HK Tong


1 Answers

You can do this with the xlogy function in scipy:

from scipy.special import xlogy
from numpy import log

>>> xlogy(10, 10)

23.0258509299

>>> 10 * log(10)

23.0258509299

>>> xlogy(0, 0)

0.0
like image 79
cel Avatar answered Nov 14 '22 21:11

cel