Project

Discretization basics Numerical derivative vs. exact derivative

Objective: Write a program that compares the first, second and fourth-order approximations of the first derivative against the analytical/exact derivative.

Given Function : `f(x) = sin(x)/x^3`

First derivative of the function is `f'(x) = (x^3 cos(x) - sin(x)*3x^2)/x^6`

The function is computed at `x = pi/3`

First-order approximation : `(sin(x+dx)/((x+dx)^3) - sin(x)/x^3)/dx`

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

Fourth-order approximation : `(((sin(x-2dx)/(x-2dx)^3 - 8*(sin(x-dx)/(x-dx)^3))+8*(sin(x+dx)/(x+dx)^3)) - (sin(x+2dx)/(x+2dx)^3))/(12*dx)`

Main Code:

% Numerical derivative vs. exact derivative
clear all
close all
clc

% f(x) = sin(x)/x^3
% f'(x) = (((x^3)*cos(x)) - (sin(x)*3*(x^2)))/x^6

x = pi/3;
dx = linspace(pi/4,pi/4000,20);

for i = 1:length(dx)
    error1(i) = first_order_aprox(x,dx(i))
    error2(i) = second_order_aprox(x,dx(i))
    error3(i) = fourth_order_aprox(x,dx(i))
end

% Plotting Bar Graph
figure(1)
errorgraph= [error1(15) error2(15) error3(15)]
bar(errorgraph)
set(gca,'XTicklabel',{'First order','Second order','Fourth order'})
ylabel('Error');


Function Code :

First-order approximation code :

% First order approximation

function error1 = first_order_aprox(x,dx)

analytical_soln = ((x^3)*cos(x) - sin(x)*3*(x^2))/(x^6)
num_first_order = (sin(x+dx)/(x+dx)^3 - sin(x)/x^3)/dx;

error1 = abs(num_first_order - analytical_soln);

end

Second-order approximation code :

% Second order approximation
function error2 = second_order_aprox(x,dx)

analytical_soln = ((x^3)*cos(x) - sin(x)*3*(x^2))/(x^6)
num_second_order = (sin(x+dx)/(x+dx)^3 - sin(x-dx)/sin(x-dx)^3) / 2*dx;

error2 = abs(num_second_order - analytical_soln);
end

Fourth-order approximation code :

% Fourth order approximation
function error3 = fourth_order_aprox(x,dx)

analytical_soln = ((x^3)*cos(x) - sin(x)*3*(x^2))/(x^6)
num_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(num_fourth_order - analytical_soln);

end

Bar Graph

Figure 1

Conclusion :

From Figure 1 it is inferred that the fourth-order approximations are the lowest followed by first-order and second-order approximations respectively.

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.