I’m trying to make a function that will graph whatever formula I tell it to.
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = formula
plt.plot(x, y)
plt.show()
When I try to call it the following error happens, I believe it’s trying to do the multiplication before it gets to y = formula.
graph(x**3+2*x-4, range(-10, 11))
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
graph(x**3+2*x-4, range(-10, 11))
NameError: name 'x' is not defined
This is because in line
x is not defined.
The easiest way is to pass the function you want to plot as a string and use
evalto evaluate it as an expression.So your code with minimal modifications will be
and you can call it as