Project

Matlab Program Numerical Discretization

Aim: Write a program that compares first order, second order and fourth order derivatives.

Objectives:

  • To compute analytical derivative of given function.
  • Compare this to numerical methods and evaluate the absolute error in various schemes

Theory:

In applied mathematics, discretization is the process of transferring continuous functions, models, variables, and equations into discrete counterparts. This process is usually carried out as a first step towards making them suitable for evaluation and/or implemetation in computing techniques.

In this program, we'll compare first, second and fourth order approximations to the analytical solution.

Given Function: `f(x) = (sin(x))/(x^3)`

Derivative at: `x = (pi)/3`

Code:

The program is as shown below. It is a MATLAB program.

%Discretization Basics
clear all
close all
clc

x = pi /3; % given value of x
dx = pi/30; %grid spacing

%given function f(x) = sin(x)/x^3
analytical_derivative = (x^3*cos(x)-sin(x)*3*x^2)/x^6;


%First order approximation using forward differencing scheme
% forward_differincing = (f(x+dx) - f(x))/dx 
forward_differencing = ((sin(x+dx))/((x+dx)^3) - (sin(x))/(x^3))/dx;
first_order_error = abs(forward_differencing - analytical_derivative);


%Second order approximation using central differencing scheme.
% central_differincing = (f(x+dx) - f(x-dx))/2*dx 
central_differencing_second_order = ((sin(x+dx))/((x+dx)^3)-(sin(x-dx))/((x-dx)^3))/(2*dx);
second_order_error = abs(central_differencing_second_order - analytical_derivative);


%Fourth order approximation using central differencing scheme.
term1 = (sin(x-(2*dx)))/((x-(2*dx))^3);
term2 = 8*(sin(x-dx))/((x-dx)^3);
term3 = 8*(sin(x+dx))/((x+dx)^3);
term4 = (sin(x+(2*dx)))/((x+(2*dx))^3);

central_differencing_fourth_order = (term1 - term2 + term3 - term4)/(12*dx);
fourth_order_error = abs(central_differencing_fourth_order - analytical_derivative);

Y = [first_order_error,second_order_error,fourth_order_error];

bar(Y,'FaceColor','c')
set(gca,'xticklabel',{'First order error','Second order error','Fourth order error'});

Outputs:

Hence, we can clearly observe the drastic reduction in error as the order of approximation increases.

References:

  • Introduction to CFD using MATLAB and OpenFOAM - Course provided by Skill Lync.
  • Higher Engineering Mathematics - BS Grewal
  • GNU Octave
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.