Monday, 25 November 2024

Numerical Differentiation using Central Difference Method with Python

Topic: CDM of Numerical Differentiation;

Subject: Numerical Method;

Tool: Python;

by: Gani Comia, Nov. 2024;

Numerical differentiation is a method to approximate the derivative of a function using discrete data points. This is applicable for a set of data points or having a function that is difficult to differentiate analytically. There are three common methods of numerical differentiation.

  • Forward Difference
  • Backward Difference
  • Central Difference

The central difference method is generally more accurate as it considers the function values on both sides of the independent variable. The toolbox presented here is the Python script of numerical differentiation using CDM. The plot is generated for both the given function and its derivative for comparison.

Python Script

# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 19:17:34 2021
@by: Gani Comia
"""

'''
This is an example plotting script of a function and its derivative
using the central difference method (CDM) of numerical differentiation
with the use of Python.

Function:  f(x) = exp(-x^2)
Derivative:  f'(x) = (f(x+h) - f(x-h)) / 2h
'''

import numpy as np
import matplotlib.pyplot as plt

# Given: domain and the function, f(x)
x = np.linspace(-5,5,1000)            # domain from -5 to 5
f = np.exp(-x**2)                           # f(x)

# Approximation of derivative, f'(x), using numerical differentiation
h = 0.001                                      # step size
df = np.zeros(1000,float)              # initialization

# Numerical differentiation using CDM
# Note: x is replaced with x[i] and added with +h and -h
for i in np.arange(1000):
    df[i] = (np.exp(-(x[i]+h)**2) - np.exp(-(x[i]-h)**2)) / (2*h)

# Plot of f(x) and f'(x)
plt.plot(x, f, label="f(x)")
plt.plot(x, df, label="f'(x)")
plt.title("Plot of f(x) and f'(x) of $e^{(-x^2)}$")
plt.xlabel("x-value")
plt.ylabel("f(x) and f'(x)")
plt.legend()
plt.show()


Visualization of the given function and its derivative.



Fig. 1. Plot of the function and its derivative.


This kind of script can be saved and rerun to solve similar engineering problems. Python IDEs such as Thonny, Spyder, Jupyter NB, and Google Collab can be used to execute the script.

Feel free to comment for inquiry, clarification, or suggestion for improvement. Drop your email to request the softcopy of the file.



No comments:

Post a Comment

Exponential Illusions: Modeling Population Growth with Caution

Topic: Exponential Growth Model and Limitation Subject: Numerical Methods Tool: Scilab By: Gani Comia, July 2025 Ordinary Differe...