8

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.

HK Tong
  • 83
  • 1
  • 10
  • 4
    I strongly disagree with the duplicates suggestion, which are questions about np.log/np.log10, and do not address 0 ln 0 = 0. – P. Camilleri May 22 '18 at 13:32

1 Answers1

8

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
cel
  • 30,017
  • 18
  • 97
  • 117
  • 2
    Link to [the implementation](https://github.com/scipy/scipy/blob/master/scipy/special/_xlogy.pxd) for the curious. – bluenote10 Sep 27 '19 at 12:22
  • Looking at the implementation linked by @bluenote10, it looks like for real numbers using `xlogy(x, x)` is equivalent to `0 if x == 0 else x * log(x)`. – bienvenu Oct 14 '21 at 00:46