Project

Week 3.3 - Discretization basics

QUESTION:

Write a program that compares the first, second, and fourth-order approximation of the first derivative against the analytical or exact derivative.

ANSWER:

Given Equation:

Computing the first derivative at `x = pi/2`

INPUT: -

%% Initialization
clc
close all
clear all

%% Function to be Discritized
% f(x) = sin(x)/x^3

%% Stencil Values
x = pi/3;
dx = pi/30;

%% Analytical Discretization

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

%% Fourth 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 - annalytical_value);
second_order_error = abs(second_order_approx - annalytical_value);
fourth_order_error = abs(fourth_order_approx - annalytical_value);

%% Graph plotting

error = [first_order_error, second_order_error, fourth_order_error];
bar(error,0.5,'r')
xlabel('Order of Approximations');
ylabel('Error Magnitude');
legend('Order of Approximation VS Error')

As we can 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’.

Label and Legends are also defined.

After running the program, the following results are obtained.

Error Image on Command Window:

Graph:

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.