Discretization basics
Aim:
Write a program that compares the first, second, and fourth-order approximation of the first derivative against the analytical or exact derivative.
Given equation
`f(x) = (sin(x))/x^3`
Code
clc
close all
clear all
%Function to be discritize
% f(x) = sin(x)/x^3
% initial values
x= pi/3;
dx = pi/30;
%Analytical derivative
analytical_value = ((x^3)*(cos(x))-(sin(x))*3*(x^2))/(x^6);
% First order approximation
First_order_approx = ((sin(x+dx))/((x+dx))^3-(sin(x))/(x^3))/dx;
% second order approximation
second_order_approx = ((sin(x+dx)/(x+dx)^3)-(sin(x-dx)/(x-dx)^3))/(2*dx);
% Forth order approximation
fourth_order_approx = (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);
%Error calculation
first_order_error = abs(First_order_approx - analytical_value);
second_order_error = abs(second_order_approx - analytical_value);
fourth_order_error = abs(fourth_order_approx - analytical_value);
%plot
error = [first_order_error second_order_error fourth_order_error];
bar(error,0.5,'r')
xlabel('order of approximation')
ylabel('error magnitude')
Explanation
- As we see here, first the analytical derivative is calculated at `x = pi/2`
- After that, the first-order derivative is calculated using the first-order approximation, Second-order approximation, and Fourth-Order Approximation.
- To find the error, the modulus of the absolute value of the difference between the Analytical derivative and the First-order approximation, Second-order approximation, and Fourth-order approximation simultaneously.
- After calculating the error, a bar graph is defined between ‘Order of Approximation’ and ‘Error’.
OUTPUT

Graph
