comparison between the first, second and fourth order approximations of the first derivative against the analytical or exact derivative.
Discretization is used to solve a partial differential function at discrete spoints in space. It basically converts a PDE into algebraic form using taylor series.
clear all
close all
clc
%function = sin(x)/x^3
%derivative of function = (x^3*(cos(x) - sin(x)*3*x^2)/x^3
x = pi/3;
analytical_function = (x^3*(cos(x)) - sin(x)*3*x^2)/x^6
% 1st order approximation= (f(x+dx) - f(x))/dx
dx= pi/40;
first_order = (sin(x+dx)/(x+dx)^3 -sin(x)/x^3)/dx
first_order_error = abs(first_order - analytical_function)
% 2nd order approximation = (f(x+dx)-f(x-dx)/2dx
second_order = (sin(x+dx)/(x+dx)^3-sin(x-dx)/(x-dx)^3)/(2*dx)
second_order_error = abs(second_order - analytical_function)
%4th order approximation = (f(x-2dx) -8*f(x-dx) +8*f(x+dx) -f(x+2dx))/12dx
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)
fourth_order_error = abs(fourth_order - analytical_function);
error = [first_order_error, second_order_error, fourth_order_error]
bar(error)
set(gca,'xticklabel',{'1st order error','2nd order error','4th order error'})
ylabel('absolute error')
title('comparision of 1st 2nd and 4th order approximation')
The code which solves the challenge is attached above.
The program compares a derivative of a function f(x) = sin(x)/x^3 with the first, second and fourth order approximation computed by taylor series.
first order approximation = (f(x+dx) - f(x))/dx
second order approximation = f(x+dx)-f(x-dx)/2dx
fourth order approximation = (f(x-2dx) -8*f(x-dx) +8*f(x+dx) -f(x+2dx))/12dx
Each approximation is compared with the analytical value and an error term is also computed. As seen in the results, as the number of orders increase the error decreases considerably ie The numerical value almost matches with the analytical value computed. By increasing the order information is taken more and more from its neighboring values. Hence the error decreases. 4th order approximation takes information from 4 neighboring points and its value matches very closely with the analytical value.