Discretization basics
Q1. Write a program that compares the first, second, and fourth-order approximations of the first derivative against the analytical or exact derivative.
Ans:
Given equation:
`f(x)=(sin (x))/x^3`
Computing first derivative at `x=pi/3`
Program:
clear all
close all
clc
%function given: sin(x)/x^3
%function derivative: ((x^3(cos(x))) - (sin(x)*3x^2))/x^6
x=pi/3;
%numerical Derivative
%step size
dx=pi/30;
analytical_derivative = ((x^3*(cos(x))) - sin(x)*3*(x^2))/(x^6)
%First order approximation
first_order_approximation= ((sin(x+dx)/(x+dx)^3)-(sin(x)/x^3))/dx;
%second orde approximation
second_order_approximation= ((sin(x+dx)/(x+dx)^3)-(sin(x-dx)/(x-dx)^3))/(2*dx);
%fourth order approximation
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);
%errors finding
error_in_first_order = abs(first_order_approximation-analytical_derivative)
error_in_second_order = abs(second_order_approximation-analytical_derivative)
error_in_fourth_order = abs(fourth_order_approximation-analytical_derivative)
%bar graph showing error
error = [error_in_first_order,error_in_second_order,error_in_fourth_order];
bar(error,0.3,'r')
xlabel('order of approximation')
ylabel('error')
legend('order of derivative approximation error')
As we can see here, first the analytical derivative is calculated at `x=pi/3`
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 or absolute value of the difference between the Analytical derivative and First-order approximation, Second-order approximation, and Fourth-order approximation simultaneously.
After calculating the errors, a bar graph is defined between 'Order of approximation' and 'error'.
Label and legends are also defined.
After running the program, the following results are obtained:
Graph:

Result values:
