1

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?

1

2 Answers 2

3

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()

enter image description here

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Woah good catch. I wouldn't have tought of that. For anyone wondering, this is because in python 2, deviding ints would output an int, while divividing floats & ints would return a float
@WayToDoor: Yes, indeed
@Bazingaa python --version Python 2.7.10. Caught again in python versions, thanks a lot! I am trying to avoidpython 2.7 but somehow in many places people still use it and a lot of older code is there sue to which I have to create python 2 environments and ...it goes on.
@Rafael: Let me tag python 2 in your question for sake of readers
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.