Numerical derivative vs Exact derivative
Objective: In this assignment, finite difference method was used to discretize the first-order derivative to the desired order of accuracy, and the results obtained through their implementation were compared with the exact solution.
Given Function:
Exact Derivative:
The Exact and numerical Solutions of the given function is calculated at x=pi/3 with dx=0.2
Here is the code to get the absolute errors and plot them as a bar function:
clear all
close all
clc
%f(x)=(sin(x)/(x^3));
x=pi/3;dx=0.2
%estimation of derivatives
exact_derivative=((cos(x)*(x^3))-(sin(x)*(3*(x^2))))/(x^6)
firstorder_derivative=((sin(x+dx)/(x+dx)^3)-(sin(x)/(x^3)))/dx
secondorder_derivative=((sin(x+dx)/((x+dx)^3))-(sin(x-dx)/((x-dx)^3)))/(2*dx)
fourthorder_derivative=((((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)
%estimation of errors
error_firstorder=abs((firstorder_derivative)-(exact_derivative))
error_secondorder=abs((secondorder_derivative)-(exact_derivative))
error_fourthorder=abs((fourthorder_derivative)-(exact_derivative))
%plotting
xt=[1,2,3]
e=[error_firstorder,error_secondorder,error_fourthorder]
labels={'0.3979','0.1344','0.0361'}
bar(e,0.3,'k','EdgeColor','r','LineWidth',0.6)
axis([0 4 0 0.5])
legend('truncation error for dx=0.2','location','northeast')
title('Comparision of errors obtained by emplying different schemes')
grid on
text( xt, e, labels, 'HorizontalAlignment','center', 'VerticalAlignment','baseline')
set(gca,'Xticklabels',{'1st approx','2nd approx','4th approx'})
saveas(gcf,'error.jpeg')
After running the program, the following bar graph has been obtained:
google drive link:
https://drive.google.com/drive/folders/1CSopnXVDArIO2HNUU4RACXYekFFXeO2s