To compare first, second and fourth order approximations of the first derivative against the analytical or exact derivative.
Aim:-To compare first, second and fourth order approximations of the first derivative against the analytical or exact derivative.
#MATLAB CODE:-Following program has been written on MATLAB to compare first, second and fourth order approximations of the first derivative against the analytical or exact derivative for a given value of x and dx, and also to compare the absolute error of first,second and fourth approximation with the help of bar graph.
clear all
close all
clc
% analytical function = sin(x)/x^3
% analytical_derivative
% f'(x)=(x^3*cos(x))-sin(x)*3*x^2 )/x^6
%Input parameter;
x=pi/3;
dx=pi/20;
analytical_derivative = (x^3*(cos(x))-sin(x)*3*x^2 )/x^6
% numerical derivative
% forward differncing
% forward differncing = (f(x+dx)-f(x))/dx
% first_order approximation
forward_differncing = ((sin(x+dx)/(x+dx)^3)-(sin(x)/x^3))/dx;
first_order_error = abs(forward_differncing - analytical_derivative)
%second_order_approximation
% central_differncing = (f(x+dx)-f(x))/dx
central_differncing = ((sin(x+dx)/(x+dx)^3)-(sin(x-dx)/(x-dx)^3))/(2*dx);
second_order_error = abs(central_differncing - analytical_derivative)
%fourth_order_approximation
%central_differncing = (f(x+dx)-f(x))/dx
% fourth_order approximation
central_differncing = ((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);
fourth_order_error= abs(central_differncing - analytical_derivative)
%Bar graph;
hold on
h=bar(1,first_order_error,0.3)
set(h,'Facecolor','r')
h=bar(2,second_order_error,0.3)
set(h,'Facecolor','g')
h=bar(3,fourth_order_error,0.3)
set(h,'Facecolor','bl')
%Labelling;
xlabel('dx')
ylabel('error')
legend('first_order_error','second_order_error','fourth_order_error')
legend('Location','northeast')
#Output:-
#Below bar graph compares first, second and fourth order error:-
#Observation:-By observing above bar graph we can conclude following statement
- The first order has high error which is highly unstable and at the same point we are getting low error for fourth order which is quite stable as compare to first order error.
- By observing,we can also says that as order of approximation increases error get reduce.Higher the order of approximation lower the error value.
Now,lets see what is the actual meaning of absolute error
Error:-Error is basically the difference of Numerical value and Exact value.
Absolute error:-Well absolute error is quite similar to normal error,the only difference is in absolute error we consider only the value of error irrespective its sign.