Reputation: 671
I wrote a simple function to plot log in python:
import matplotlib.pyplot as plt
import numpy as np
x = list(range(1, 10000, 1))
y = [-np.log(p/10000) for p in x]
plt.scatter(x, y) # also tried with plt.plot(x, y)
plt.show()
I just want to see how the plot looks.
fn.py:5: RuntimeWarning: divide by zero encountered in log
y = [-np.log(p/10000) for p in x]
I get the above error and on top of that I get a blank plot with even the ranges wrong.
It is strange why there is divide by zero
warning, when I am dividing by a number?
How can I correctly plot the function?
Upvotes: 1
Views: 2181
Reputation: 39042
Although you have tagged python-3.x
, it seems that you are using python-2.x
where p/10000
will result in 0 for values of p < 10000
because the division operator /
performs integer division in python-2.x
. If that is the case, you can explicitly use 10000.0
instead of 10000
to avoid that and get a float division.
Using .0
is not needed in python 3+
because by default it performs float division. Hence, your code works fine in python 3.6.5
though
import matplotlib.pyplot as plt
import numpy as np
x = list(range(1, 10000, 1))
y = [-np.log(p/10000.0) for p in x]
plt.scatter(x, y)
plt.show()
On a different note: You can simply use NumPy's arange
to generate x
and avoid the list
completely and use vectorized operation.
x = np.arange(1, 10000)
y = -np.log(x/10000.0)
Upvotes: 3
Reputation: 41872
Why import numpy and then avoid using it? You could have simply done:
from math import log
import matplotlib.pyplot as plt
x = xrange(1, 10000)
y = [-log(p / 10000.0) for p in x]
plt.scatter(x, y)
plt.show()
If you're going to bring numpy into the picture, think about doing things in a numpy-like fashion:
import matplotlib.pyplot as plt
import numpy as np
f = lambda p: -np.log(p / 10000.0)
x = np.arange(1, 10000)
plt.scatter(x, f(x))
plt.show()
Upvotes: 1