[Numpy-discussion] new warning in 1.5.0: divide by zero encountered in log

Alan G Isaac alan.isaac at gmail.com
Wed Sep 8 08:35:47 EDT 2010


On 9/8/2010 6:38 AM, John Reid wrote:
> def safe_x_log_x(x):
>       "@return: x log(x) but replaces -inf with 0."
>       l = np.log(x)
>       result = x * l
>       result[np.isneginf(l)] = 0.
>       return result


Assuming x is known to contain nonnegative floats:

def safe_x_log_x(x):
   x = np.asarray(x)
   l = np.zeros_like(x)
   l[x>0] = np.log(x[x>0])
   return x * l

hth,
Alan Isaac




More information about the NumPy-Discussion mailing list