Project

Numerical derivative vs exact derivative

discretization_main.m

close all
clear all
clc
% Discretization
%f(x)= sin(x)/x^3;
%f\'(x) =(x^3*(cos(x)) - 3 * x^2 * sin(x))/x^6


x = pi /3;
dx = linspace(pi/40,pi/40000, 100);

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));

endfor 

figure(\'Name\',\'Error Variation in discretization methods\',\'NumberTitle\',\'off\');
plot1 = subplot(3,1,1)
bar(dx, first_order_error,\'b\', 1);
title(\'First order error vs dx\');
xlabel(\'dx\')
ylabel(\'Error\')

plot1 = subplot(3,1,2)
bar(dx, second_order_error,\'b\',1);
title(\'Second order error vs dx\');
xlabel(\'dx\')
ylabel(\'Error\')

plot1 =  subplot(3,1,3)
bar(dx, fourth_order_error,\'b\',1);
title(\'Fourth order error vs dx\');
xlabel(\'dx\')
ylabel(\'Error\')
saveas(plot1, \'Error_variation.png\',\'png\')




first_order_approximation.m

function forward_error = first_order_approximation(x, dx)
  %First order Approximation
 
  analytical_derivative  =(x^3*(cos(x)) - 3 * x^2 * sin(x))/x^6;
  forward_diff = (sin(x + dx)/(x+dx)^3 - sin(x)/x^3 )/dx;
  forward_error = abs(forward_diff - analytical_derivative);    
    
endfunction

second_order_approximation.m

function central_error = second_order_approximation(x,dx)
  
    analytical_derivative  =(x^3*(cos(x)) - 3 * x^2 * sin(x))/x^6;
    central_diff = (sin(x + dx)/(x+dx)^3 - sin(x - dx)/(x-dx)^3 )/(2*dx);
    central_error = abs(central_diff - analytical_derivative);

  
  
endfunction

fourth_order_approximation.m

function central_diff_fourth_order_error = fourth_order_approximation(x,dx)
  analytical_derivative  =(x^3*(cos(x)) - 3 * x^2 * sin(x))/x^6;
  central_diff_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);
  central_diff_fourth_order_error = abs(central_diff_fourth_order - analytical_derivative);

endfunction

Output bar Graph

Output

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.