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:
$f(x) = (1/e^{x}) + (sin^{2}(\frac{x}{2}))$
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 in sympy
.
Define the equation using the Python expressions.
Use a loop to iterate for the N
times and use the diff()
method from sympy
to 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.
# 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)