Matlab Code to find the first, second and fourth order approximations of the first derivative and it Comparison using Analytical Solution
Aim
The Major objective of this project was to write a Matlab code that can compare the first, second, and fourth-order approximations of the first derivative against the analytical or exact derivative.
Introduction
The function that you will compute if`F(x)=frac{sin(x)}{x^3}`
The main task was to compute the first Derivative at `x=frac{pi}{3}`
`dx " Value was assumed to be "frac{pi}{30}`
Then compute the derivative both numerically and analytically. Make sure you compute 1st, 2nd, and 4th order derivatives.
Finding an error parameter as the absolute difference in numerical and exact derivative at x = pi/3
First Order Apprimation
For_diff=((sin(x+dx)/(x+dx)^3)-(sin(x)/x^3))/dx
Second-Order Approximation
CD_1=((sin(x+dx)/(x+dx)^3)-(sin(x-dx)/(x-dx)^3))/(2*dx);
Fourth Order Approximation
CD_4=(((sin(x-2*dx)/(x-2*dx)^3))-8*((sin(x-dx)/(x-dx)^3))+8*((sin(x+dx)/(x+dx)^3))-((sin(x+2*dx)/(x+2*dx)^3)))/(12*dx)
Code For Computing Errors
%Error Calculation for all the Order
error=abs(For_diff-analytical_derivative)
error_1=abs(CD_1-analytical_derivative)
error_2=abs(analytical_derivative-CD_2)
error_3=abs(analytical_derivative-CD_4)
Code for Plotting Bar Graph
The Code below 0.4 represents the thickness of the bars. Y is the array that contains the list of errors for all the orders. XLabel is used to label the X-axis whereas Y label is used naming the Y-axis.
%2D bar Plot
y=[error,error_1,error_3];
bar(y,0.4);
title('Comparision of First,Second and Fourth Order Approximation');
xlabel('Error in 1, 2 and 4 Order of approximation')
ylabel('Truncation Error')
legend('order of derivative approximation errors')
Matlab Code
clc
close all
clear all
%analytical Function of Sin(x)/x^3
%f'(x)=(x^3*cos(x)-sin(x)*3*x^2)/x^6;
x=pi/3;
analytical_derivative=(x^3*cos(x)-sin(x)*3*x^2)/x^6;
dx=pi/30;
%forward Differencing
%First Degree Approximation
For_diff=((sin(x+dx)/(x+dx)^3)-(sin(x)/x^3))/dx
%second Order Approximation for first order derivative
CD_1=((sin(x+dx)/(x+dx)^3)-(sin(x-dx)/(x-dx)^3))/(2*dx);
%Second order Central Differencing for second order derivative
CD_2=((sin(x+dx)/(x+dx)^3)+(sin(x-dx)/(x-dx)^3)-2*(sin(x)/x^3))/(dx^2)
%Fourth order Central Differencing
CD_4=(((sin(x-2*dx)/(x-2*dx)^3))-8*((sin(x-dx)/(x-dx)^3))+8*((sin(x+dx)/(x+dx)^3))-((sin(x+2*dx)/(x+2*dx)^3)))/(12*dx)
%Error Calculation for all the Order
error=abs(For_diff-analytical_derivative)
error_1=abs(CD_1-analytical_derivative)
error_2=abs(analytical_derivative-CD_2)
error_3=abs(analytical_derivative-CD_4)
%2D bar Plot
y=[error,error_1,error_3];
bar(y,0.4);
title('Comparision of First,Second and Fourth Order Approximation');
xlabel('Error in 1, 2 and 4 Order of approximation')
ylabel('Truncation Error')
legend('order of derivative approximation errors')
WorkSpace Result

Comparison of Data
