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:

f(x)=(1/ex)+(sin2(x2))f(x) = (1/e^{x}) + (sin^{2}(\frac{x}{2}))

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 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.

Example code

# import library
import sympy as sp
import matplotlib.pyplot as plt
import numpy as np
# Define the symbols
x = sp.symbols('x')
# Define the equation
equation = (1/sp.exp(x)) + (sp.sin(x/2) ** 2)
print("Equation: ", equation)
# Calculate the derivative
N = 4
for i in range(N):
equation = equation.diff(x)
print('Order ' ,i+1 , ": ", equation)
# Plotting the results
time = np.arange(0, 10, 0.1)
solution = [equation.subs({x: point}) for point in time]
# plot derivative time history
plt.plot(time, solution)
Copyright ©2024 Educative, Inc. All rights reserved