ZK Zhao
ZK Zhao

Reputation: 21533

Numpy: how to calculate log without warning?

I just upgrade to a new version of Anaconda, in which

%matplotlib inline

from numpy import inf, arange, array, linspace, exp, log, power, pi, cos, sin, radians, degrees
from matplotlib import pyplot as plt
x = linspace(0, 10)
plt.plot(x, log(x),'o', label='ECDF')

works fine, but will return the warning

RuntimeWarning: divide by zero encountered in log

Surely, the problem is that I use x = linspace(0, 10), which start at 0, and then pass it to log(x). But the problem is that, how can I refactor my code, so the warning disapears?

Generally speaking, most plot always start with 0. something like x = linspace(0.00000001, 10) looks very ugly to me.

Upvotes: 0

Views: 1975

Answers (2)

Stelios
Stelios

Reputation: 5521

Numpy offers a nice mechanism to suppress warnings using errstate, which applies only locally when used with with.

with np.errstate(divide = 'ignore'):
    plt.plot(x, np.log(x),'o', label='ECDF')

However, I would recommend this approach only if you are unable to "manually" modify your code to avoid the warning.

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

Logarithm is not defined in 0, so you can not possibly plot a graph for that function at zero. One option I see is that instead of plotting log(x) you plot a bit more complex function:

lambda x: log(x) if x > 0 else 0

Of course you could choose a different value for x = 0 but I think 0 makes sense.

Using the parameters of linspace it is possible to exclude the last point(by using x = linspace(0, 10, endpoint=False)) but I don't think there is a way to exclude the starting point.

Upvotes: 2

Related Questions