We’ve discussed how to compute derivatives by hand. However, oftentimes when working on a computer, we have functions given to us in array form rather than an explicit equation. In this exercise, we will investigate how to calculate derivatives using Python.
For example, let’s say we have an array that represents the following function:
We can define this function in two sets of arrays using the following code.
from math import pow # dx is the "step" between each x value dx = 0.05 def f(x): # to calculate the y values of the function return pow(x, 2) + 3 # x values f_array_x = [x for x in np.arange(0,4,dx)] # y values f_array_y = [f(x) for x in np.arange(0,4,dx)]
pow() function within the
f(x) function we defined allows us to calculate the values of x2, and we use a list comprehension to create a list of the y-values in a variable called
To compute the derivative of
f_array, we use a NumPy function called
f_array_deriv = np.gradient(f_array_y, dx)
gradient() takes in an array (in this case, a one-dimensional array) as its first argument. We also need to specify the distance between the x values, which is
dx. For a one-dimensional array,
gradient() calculates the rate of change using the following formula:
As we know from the limit definition of the derivative, we want “Change in x” to be as small as possible, so we get an accurate instantaneous rate of change for each point.
In script.py, we have code that defines an plots the following function:
sin_x contains the x-values, while
sin_y contains the y-values.
Define a variable
sin_deriv that calculates the derivative of f(x) = sin(x).
Uncomment the following line of code to plot
What does the new plot look like?
Let’s play around with the
dx variable. Change the value of
What do you notice about the graphs after you hit run? Does the accuracy of your calculation appear to increase or decrease?