MATLAB: What is the mistake in the code of first order, second order and fourth order errors of first order derivative of function sinx/x^3 in which the first order error graph is significantly lower than second and fourth order errors.

first orderfourth order approxiamtionssecond order

How to insert the code here ?Is this the correct way, if not can someone guide me
close all
clear all
clc
x=pi/3;
dx=linspace(pi/40,pi/400000,100);
function first_order_error=first_order_approximation(x,dx)
%analytical derivative


analytical_derivative = ((x^3)*(cos(x))-sin(x)*(3*x^2))/(x^6);
%numerical derivative


%first order approximation
forward_differencing=((sin(x+dx)/(x+dx).^3)-(sin(x)/(x).^3))/dx;
first_order_error=abs(forward_differencing-analytical_derivative);
end
function second_order_error=second_order_approximation(x,dx);
%analytical derivative
analytical_derivative = ((x^3)*(cos(x))-sin(x)*(3*x^2))/(x^6);
%numerical derivative
%second_order_approximation
central_differencing=((sin(x+dx)/(x+dx)^3)-(sin(x-dx)/(x-dx)^3))/2*dx;
second_order_error=abs(central_differencing-analytical_derivative);
end
function fourth_order_error=fourth_order_approximation(x,dx)
%analytical derivative
%analytical_derivative=((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 derivative
numerical_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
fourth_order_error=abs(analytical_derivative-numerical_derivative)
end
for i=1:length(dx)
first_order_error(i) = first_order_approximation(x,dx(i));
second_order_error(i)= second_order_approximation(x,dx(i));
fourth_order_error(i)=fourth_order_approximation(x,dx(i));
end
subplot(2,1,1)
loglog(dx,first_order_error,'b')
xlabel('dx')
ylabel('error')
hold on
loglog(dx,second_order_error,'r')
hold off
legend('first order error','second order error')
subplot(2,1,2)
loglog(dx,fourth_order_error,'k')
xlabel('dx')
ylabel('error')
legend('fourth order error')

Best Answer

central_differencing=((sin(x+dx)/(x+dx)^3)-(sin(x-dx)/(x-dx)^3))/(2*dx);
numerical_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)
Related Question