first second and fourth order approximations
function out = first_order_approximations(x,dx)
% analytical_derivative
%f\'(x)=(x^3(cos(x)-sin(x)*3*x^2)/x^6
analytical_derivative=((x.^3*cos(x))-(sin(x)*3*x.^2))/(x.^6);
%numerical derivatives
forward_differincing = (sin(x)*(x+dx)-sin(x)*(x))/dx;
out=abs(forward_differincing - analytical_derivative);
end
----------------------------------------------------------------------------------------
function out =second_order_approximations(x,dx)
% analytical_derivative
%f\'(x)=(x^3(cos(x)-sin(x)*3*x^2)/x^6
analytical_derivative=((x.^3*cos(x))-(sin(x)*3*x.^2))/(x.^6);
%numerical derivatives
central_differincing = (sin(x)*(x+dx)-sin(x)*(x-dx))/(2*dx);
out=abs(central_differincing - analytical_derivative);
end
----------------------------------------------------------------------------------------
function out =fourth_order_approximations(x,dx)
% analytical_derivative
%f\'(x)=(x^3(cos(x)-sin(x)*3*x^2)/x^6
analytical_derivative=((x.^3*cos(x))-(sin(x)*3*x.^2))/(x.^6);
%numerical derivatives
fourth_order_error=((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))/(12*dx))));
out=abs(fourth_order_error- analytical_derivative);
end
------------------------------------------------------------------------------------------
clear all;
close all;
clc;
x=pi/3;
dx=linspace(pi/4,pi/40,20);
for i= 1:length(dx)
first_order_error(i)=first_order_approximations(x,dx(i));
second_order_error(i)=second_order_approximations(x,dx(i));
fourth_order_error(i)=fourth_order_approximations(x,dx(i));
end
figure(1);
plot(dx,first_order_error,\'-o\');
hold on;
plot(dx,second_order_error,\'--\');
hold on;
plot(dx,fourth_order_error,\'b\');
xlabel(\'dx\');
ylabel(\'errors\');
legend(\'first order error\',\'second order error\',\'fourth order error\');
-------------------------------------------------------------------------------------------
Result Graph:
----------------------------------------------------------------------------------------------
From the above graph, we can say that the first order error and second-order error have the very negligible difference (tends to zero). we have obtained the straight line for the first order and second order error. while the value of the errors for the fourth order increases with the increases in the values of the dx. There is the large difference between first, second and fourth order errors values.