How to calculate the Nth-order derivative using Python
A derivative describes the rate of change of functions. In this answer, we will calculate an equation’s Nth-order derivative. We will be using the following equation to calculate the derivative:
Steps:
To calculate the Nth-order derivative of the equation, follow the steps given below:
-
Import the following modules:
sympy: This module is used to calculate the derivative of the equation.numpy: This module is used to perform the numeric operations on the equation.matplotlib.pyplot: This module is used to plot the equation results.
-
Define a symbol using the
symbols()method available insympy. -
Define the equation using the Python expressions.
-
Use a loop to iterate for the
Ntimes and use thediff()method fromsympyto calculate the derivative of the equation. -
Define an array containing some range of values for the x-axis in the plot.
-
Use the
subs()method from the equation to get the results of each substitution of the value in the equation. -
Plot the resultant values with the input values.
Example code
# import libraryimport sympy as spimport matplotlib.pyplot as pltimport numpy as np# Define the symbolsx = sp.symbols('x')# Define the equationequation = (1/sp.exp(x)) + (sp.sin(x/2) ** 2)print("Equation: ", equation)# Calculate the derivativeN = 4for i in range(N):equation = equation.diff(x)print('Order ' ,i+1 , ": ", equation)# Plotting the resultstime = np.arange(0, 10, 0.1)solution = [equation.subs({x: point}) for point in time]# plot derivative time historyplt.plot(time, solution)
Free Resources