Project

Discretization basics

Program that compares the first, second and fourth order approximations of the first derivative against the analytical or exact derivative.

`f(x)=sinx/x^3`

The function is computed at x=pi/3

1. First order approximation=`(sin(x+dx)/(x+dx)^3-sin(x)/x^3)/dx`

2. Second order approximation=`(sin(x+dx)/(x+dx)^3-sin(x-dx)/(x-dx)^3)/(2*dx)`

3. Fourth order approximation=`(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)`

Below shows The Bar graph of the errors for these three approximations at a particular dx.

So from the Bar graph we can clearly see that error for the fourth order approximation the lowest followed by second order and first order approximation respectively.

% Function for first order error calculation

function error1=first_order_approx(x,dx)
analy=((x^3*cos(x))-(sin(x)*3*x^2))/x^6;

numre_first_order=(sin(x+dx)/(x+dx)^3-sin(x)/x^3)/dx;

error1=abs(analy-numre_first_order);

end
   
% Function for second order error calculation

function error2=second_order_approx(x,dx)
analy=((x^3*cos(x))-(sin(x)*3*x^2))/x^6;


numre_second_order=(sin(x+dx)/(x+dx)^3-sin(x-dx)/(x-dx)^3)/(2*dx);

error2=abs(analy-numre_second_order);
end
 
% Function for fourth order error calculation

function error3=fourth_order_approx(x,dx)
analy=((x^3*cos(x))-(sin(x)*3*x^2))/x^6;


numre_fourth_order=(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);

error3=abs(analy-numre_fourth_order);
end

% Main program
clear all;
close all;
clc;
x=pi/3;
% fx=sin(x)/x^3;
dx=linspace(pi/4,pi/4000,20);


 for i=1:length(dx);

error1(i)=first_order_approx(x,dx(i));
error2(i)=second_order_approx(x,dx(i));
error3(i)=fourth_order_approx(x,dx(i));
 end
errorgraph=[error1(15) error2(15)  error3(15)];
bar(errorgraph);
set(gca,'XTicklabel',{'first_o_approx','second_o_approx','fourth_o_approx'})
ylabel('error');
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.