I'd like to plot a function together with it's derivative, say $f(x)=x^3-2x$. I know the graph of the derivative should be a parabola, but how can I have that automatically computed? Also, how can I control the viewing range?
Nice plot of a function together with it’s derivative
There are at least a couple of ways to compute derivatives in Python. There is a symbolic package, called SymPy, that can tell you that the formula for the derivative of your function is $f'(x)=3x^2-2$. Of course, it's easy to plot it from there. As this is a class in numerical methods, however, let's try to use SciPy. There is a function for numerical differentiation in the scipy.misc
module. Let's import it, along with the standard graphical tools:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import derivative
Now, let's define $f$ and use derivative
to compute $f'(1)$, whose exact value is $1$.
def f(x): return x**3-2*x
derivative(f,1,dx=0.0001)
#Out: 1.0000000099996686
Looks pretty good. The dx
term is a parameter involved in the approximation process. We'll learn more about that when we discuss differentiation.
Now, if we want to plot $f$ and $f'$ together in a restricted range, we can do so as follows:
plt.plot(xs,f(xs))
plt.plot(xs,derivative(f,xs, dx=0.001))
ax = plt.gca()
ax.set_ylim(-5,5)
plt.savefig('temp.png')
Note that the plt.savefig
command generated a PNG file on my laptop which I was able to upload here!