Project

Numerical derivative vs exact derivative

\"\"

clc
close all
clear all

dx=pi/40:pi/1000:pi/20

for i=1:length(dx)
    error1(i)=errorfds(dx(i));
    error2(i)=errorcds(dx(i));
    error3(i)=errorfourth(dx(i));
end

hold on
plot(dx,error1,\'r\') % red line is the first order derivative
plot(dx,error2,\'y\')  % yellow line is the second order derivative
plot(dx,error3,\'b\')  % blue line is the fourth order derivative

function [error_fds]= errorfds(dx)

%function=sin(x)/x^3; 
x=pi/3;

%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

 %spacing between the grid points

%first order approximation
%forward differencing scheme (FDS)

forward_differencing=(sin(x+dx)/(x+dx)^3-sin(x)/x^3)/dx;
error_fds=abs(forward_differencing-analytical_derivative);

end

function [error_cds]= errorcds(dx)

%function=sin(x)/x^3; 
x=pi/3;

%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

 %spacing between the grid points




%second order approximation-Central differencing scheme(CDS)

central_differencing=(sin(x+dx)/(x+dx)^3-sin(x-dx)/(x-dx)^3)/(2*dx);
error_cds=abs(central_differencing-analytical_derivative);


end

function [error_fourth_order_cds]= errorfourth(dx)

%function=sin(x)/x^3; 
x=pi/3;

%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

 %spacing between the grid points






%3.fourth order approximation-Central differencing scheme(CDS)

F_i_minus_2=(sin(x-dx-dx)/(x-dx-dx)^3);
F_i_minus_1=8*(sin(x-dx)/(x-dx)^3);
F_i_plus_1=8*(sin(x+dx)/(x+dx)^3);
F_i_plus_2=(sin(x+dx+dx)/(x+dx+dx)^3);

fourth_order_approximation=(F_i_minus_2-F_i_minus_1+F_i_plus_1-F_i_plus_2)/(12*dx);
error_fourth_order_cds=abs(fourth_order_approximation-analytical_derivative);
end
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.