You are on page 1of 63

NUMERICAL ANALYSIS LAB

Lab Manual

Department of Mechanical Engineering


Department of Mechanical Engineering

Lab Form-1: Lab Course Outline


Lab Course: Numerical Analysis
Course Code: ME02408

Semester: F-21 Session: 2019


Credit Hours: (0, 1) Pre-requisite: - Applied Mathematics III
Instructor: Hamid Iftikhar Student Counseling hours:
Monday: 11:00-14:00
Tuesday: 11:00-14:00
Contact: +92 311 445 4812 Email: hamid.iftikhar@me.uol.edu.pk
Office: MED-312-7

Lab Days: Lab Room:


Friday: 08:00-11:00 IT-Lab 507

Lab Course Objectives


 To provide solutions of engineering problems by means of automated algorithms for numerical
methods in MATLAB. The concept of efficiency, reliability and accuracy of a method is the strength
of this course. Introduction to error, its types and sources; solution of non-linear equations in one
variable; solutions of systems of linear and nonlinear equations; Interpolation and curve fitting;
Numerical differentiation and integration; Solutions of ordinary differential equations (Initial–
Value Problems) through an iterative way.
 In every field, it is necessary to learn “how to manage data” for insight and decision making.
Statistical methods allow engineers to make a consistent product, detect problems, minimize
chemical waste, manage energy sources, quality control and predict product life.

Lab Course Learning Outcomes (CLOs)


Upon successful completion of the course, the student will be able to:

LAB WORK CLOs & PLOs

CLO# CLO Statement Domain Level of PLO


Learning
3 Understand and Apply algorithms based on Cognitive 3 5
numerical techniques to solve and integrate
linear and nonlinear equations, differential
equations in an iterative way using MATLAB
4 Analyze engineering and science problems Cognitive 4 5
using numerical analysis techniques with
MATLAB.

Lab Form-1: Lab Course Outline: Numerical Analysis Lab, F21 Page 1 of 5
Department of Mechanical Engineering

Lab Form-1: Lab Course Outline

Mapping of Course Learning Outcomes and Program Learning Outcomes

PLO CLO-3 CLO-4 Total


1.Engineering Knowledge
2.Problem Analysis
3.Design/Development
4.Investigation
5.Modern Tool uses 16 4 20
6.The Engineering & Usage
7.Environment & Sustainability
8.Ethics
9.Individual &Team work
10.Communication
11.Project Management
12.Lifelong Learning
Total 16 4 20

Lab Form-1: Lab Course Outline: Numerical Analysis Lab, F21 Page 2 of 5
Department of Mechanical Engineering

Lab Form-1: Lab Course Outline


Lab Plan

Week Lab Session Experiment Title CLO-4 CLO-5


1 1st Preliminaries: Introduction

Introduction to MATLAB
2 2nd Preliminaries: Pre-Calculus
Motivation for the course; basic commands in MATLAB; for loop, while loop, 
input, if else if, plot, int, diff, inline, symbolic math toolbox, spline, fprintf, disp.
3 3rd Root Finding Problems–I
Development of code for the Solution of Equations in one variable in MATLAB; 
Bisection Method; Fixed-Point Iteration.
4 4th Root Finding Problems–II
Development of code for the Method of False position; Secant Method; Newton 
Raphson Method in MATLAB.
5 5th Interpolation–I
Introduction to different Operators such as Shift operator, Forward and

Backward operator, Central operator, and Averaging operator; Lagrange’s
Interpolation polynomial.
6 6th Interpolation–II
Development of code for the Construction of Forward and Backward Difference

tables; Newton’s Forward Difference Interpolation; Newton’s Backward
Difference Interpolation in MATLAB.
7 7th Interpolation–III
Development of code for the Divided Difference Interpolation Formula in 
MATLAB; Sterling’s Centered Difference Formula; Gauss Formula.
8 8th Curve Fitting
Development of code for the Least Square approximation/Curve fitting in 
MATLAB.
9 9th Numerical Differentiation–I
Development of code for the Numerical Differentiation based on Newton’s

Forward Differences in MATLAB; Numerical Differentiation based on Newton’s
Backward Differences.

Lab Form-1: Lab Course Outline: Numerical Analysis Lab, F21 Page 3 of 5
Department of Mechanical Engineering

Lab Form-1: Lab Course Outline


10 10th Numerical Integration–I
Development of code for the Rectangle Rule, Trapezoidal Rule and their 
composite algorithms in MATLAB.
11 11th Numerical Integration–II

Development of code for the Simpson’s Rule in MATLAB.
12 12th Solution of System of Equations
Development of code for the Iterative methods for linear systems, Newton’s 
method and modified Newton’s method for nonlinear systems in MATLAB.
13 13th Numerical Solution of ODEs– I
Development of code for the Euler’s Method; Modified Euler’s Method;
 
Improved Euler’s Method in MATLAB.
Assignment-1
14 14th Numerical Solution of ODEs– II
Development of code for the Midpoint Formulae in MATLAB.  
Assignment-2
15 15th Numerical Solution of ODEs– III

Development of code for the Runge-Kutta Method in MATLAB.
16 16th Numerical Solution of ODEs– IV
Development of code in MATLAB for:
 Solution of systems of ODEs of 1st order 
 Solution of Differential equations of 2nd order and System of Differential
equations
17 Final Term Exam

Lab Form-1: Lab Course Outline: Numerical Analysis Lab, F21 Page 4 of 5
Department of Mechanical Engineering

Lab Form-1: Lab Course Outline

Lab Assessment Tools


Sr. # Sample Assessment Tools Quantity Weightage (%)
1 Lab Session Assessment 16 60
2 Lab Report 1 10
4 Quiz 2 10
5 Assignment 2 20
Total 100

Lab Assessments to CLOs Mapping


Sr. No. Assessment Week CLO-3 CLO-4 Total
1 Lab Session Assessment 1-16 12 10
3 Lab Report 1-16 2 2
4 Quiz 14 2 2
5 Assignment 13, 14 4 2
Total 16 4 20

Name of Lab Instructor Signature of Instructor

Hamid Iftikhar Date: 23/09/2021

Lab Form-1: Lab Course Outline: Numerical Analysis Lab, F21 Page 5 of 5
LAB MANUAL

Experiment # 01
INTRODUCTION TO MATLAB

Page 1 of 49
Introduction:
MATLAB (an abbreviation of "matrix laboratory") is a proprietary multi-paradigm programming language and
numerical computing environment developed by MathWorks. The heart of MATLAB is the MATLAB
language, a matrix-based language allowing the most natural expression of computational mathematics.
MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation
of user interfaces, and interfacing with programs written in other languages.

Applications of MATLAB:
Its uses include:
 Analyze data.
 Develop algorithms.
 Create models and applications.
 Predict a functions behavior under specified limits.
 App Building
 Data Import and Analysis
 Data Visualization
 Software Development
 Controlling Hardware

Starting MATLAB:
After starting Matlab different windows appear which includes:

 The Command Window:


The MATLAB Command Window is the main window where you type commands directly to
the MATLAB interpreter.
 The Command History:
To open the Command History window with all history showing, in the Command Window, press
the Up Arrow key (↑) or enter command history. It shows all the working/commands done by the
user.
 The Workspace:
The workspace contains variables that you create or import into MATLAB from data files or other
programs. You can view and edit the contents of the workspace in the Workspace browser or in
the Command Window.
 The Current Directory:
The current folder is a reference location that MATLAB uses to find files. This folder is sometimes
referred to as the current directory.
 The Help Browser:
The Help browser is an HTML browser integrated with the MATLAB desktop. To open the Help
browser, click the Help button in the desktop toolbar, type “helpbrowser” in the Command
Window, or use the Help menu in any tool.
 The Start button:
Click the Start button to view a menu of product categories and desktop tools installed on your
system. As an alternative, press Alt+S to view the Start button contents.
Page 2 of 49
Prompt: In command window, there is a prompt (>>), usually commands/codes are written in front of this
prompt.
Current directory Editor window Workspace
New m-file

Command Window

Different Commands: Prompt


 clc:
It clears all the text from the Command Window, resulting in a clear screen. After running clc, you cannot
use the scroll bar in the Command Window to see previously displayed text. You can, however, use the
up-arrow key ↑ in the Command Window to recall statements from the command history.
 Clear all:
It clears variables, but it also clears a lot of other things from memory, such as breakpoints, persistent variables
and cached memory.
 Close all:
It deletes the current figure or the specified figure(s). It optionally returns the status of the close operation.

Row and Column separation:


 The comma and spaces are used to separate various elements in a row.

Page 3 of 49
For example:

MATLAB Calculator: It is a matrix calculator; it can perform any sort of calculation from basic to complex.
It includes mathematical operation:

 (+) , (-), (*), (/), (^)


For example:

Page 4 of 49
 log (logarithm)
 exp (exponential)
 pow (Power)
 sqrt (Square-root)
 sin (sine)
 cos (Cosine)

Date of Issue

Course Code MT-202L


Lesson Plan
Page# 9 of 53

 tan (tangent)
 asin (Sine inverse)
 acos (Cosine inverse)
 atan (Tangent Inverse).

For Example:

Page 5 of 49
Observation and Discussion:

Page 6 of 49
Numerical Method Lab
Experiment # 02
Fixed Point Iteration Method

Page 7 of 49
Let us see how to solve a system of linear equations in MATLAB. Here are the various operators that we will be
deploying to execute our task :
\ operator:
A \ B is the matrix division of A into B, which is roughly the same as INV(A) * B. If A is an NXN
matrix and B is a column vector with N components or a matrix with several such columns, then X = A \ B is
the solution to the equation A * X = B. A warning message is printed if A is badly scaled or nearly
singular. A\EYE(SIZE(A)) produces the inverse of A.
linsolve operator:
X = LINSOLVE(A, B) solves the linear system A * X = B using LU factorization with partial
pivoting when A is square, and QR factorization with column pivoting. A warning is given if A is ill
conditioned for square matrices and rank deficient for rectangular matrices.

MATLAB CODES:-

FOR LINEAR EQUATIONS:


% Equations to solve
% 2*x = 3*y + 1 (Rearranging: 2*x - 3*y = 1)
% x + y = 4
% Converting these equations into Matrices.

A = [2 -3;1 1]
% B = [x;y]
C = [1;4]

% It can be solved by 3 different methods.


% 1st Method:
B = A\C % A is 'back divided' by B.

% 2nd Method:
% B = (A^-1)*C

% 3rd Method:
% B = linsolve(A,C)

Page 8 of 49
FOR NON-LINEAR EQUATIONS:
% First plot the graph to find the initial guess.

x = linspace(-5,5,50);
y = (x.^3 + 7);
plot(x,y)

Page 9 of 49
xlabel('x'), ylabel('x.^3 + 7'),title('Non-Linear Plot'),grid on

x = linspace(-5,5,50); % Tt generates 50 values between -5 and +5

fun = @(x) (x.^3 + 7); % Function


solution = fzero(fun,-2) % the general syntax is used to find solution
where -2 is the initial guess.

Page 10 of 49
PROCEDURE
FOR LINEAR EQUATIONS:
 Create a matrix by typing the following in the MATLAB workspace:
A = [2 -3; 1 1]

 The semicolon ( ; ) indicates a new row in the matrix. Create a second matrix, C.
C = [1 ; 4]

 The colon symbol (:) can be used to select columns or rows within a matrix.
 Solving systems of linear equations is extremely simple. Here‟s an example of an Ax=B system: Equation
1: 2x – 3y = 1, Equation 2: x + y = 4
A = [2 -3; 1 1]
C = [1 ; 4]
B = inv(A)*B

Note: Try B = A\C as a shortcut for the 3rd line above

Try B = linsolve(A,C)

FOR NON-LINEAR EQUATIONS:


1. General syntax x = fzero (fun,x0)
2. This function tries to find a point x where fun(x)=0.
3. To find the initial guess, we plot the graph between x and f(x).
4. The point where the plot crosses the x-axis is taken as the initial guess.

OBSERVATION

Page 11 of 49
Numerical Method Lab
Experiment # 03
False Positioning Method

Page 12 of 49
Objective.
Find the root of non-linear equation using False Position method on Matlab and discuss the final Result.

Background information:
• Also called false position method
• It is a bracketing method for finding a numerical solution of an equation of the form f(x)=0
• Requirement: Within a given interval [a b], f(x) is continuous and has a solution
• The objective is to make convergence faster than the Bisection method.

Formula:

(𝒃)−𝒃𝒇(𝒂)
x=
𝒇(𝒃)−𝒇(𝒂)
PROCEDURE
 First step is to define the equation in Matlab.
 Enter limits (a, b) from user.
 Now it will check whether the limits satisfy [f(a).f(b)<0 ] or not.
 If the limits are correct then program will proceed otherwise it would give an error.
 Now the formula of Regula Falsi method is implemented.
 In order to get accurate result „while loop‟ is applied. It is applied in such a way that the root becomes closer
to the exact root.
 The limits of „a‟ and „b‟ are kept between positive and negative sign.
 Finally, the result is displayed on the output screen.
MATLAB CODE
func= @(x)((x.^2) - (5.57*x)+5.774); %% Defining Function %%
z=0;

While (z==0) %% This loop will run until the user puts correct value of limit%%
a=input ('Enter the first value :');
Func (a) %% It displays the value of the function with variable 'a'
%%b=input ('Enter the second value :');
Page 13 of 49
Func (b) %% It displays the value of the function with variable 'b'
%%if func (a)*func (b)>0 %% Testing the basic requirement %%
Disp („you entered wrong choice. Please Try
Again...')else
Xnew= (a*func (b)-b*func (a))/(func(b)-func(a)); %%If true then new limits would
changen=0;

While abs (func (xnew))>1e-6 %% User wants an answer upto 6 decimal place
%%n=n+1; %%It tells the total number of iterations %%
Xnew= (a*func (b)-b*func (a))/(func(b)-func(a));
If func (a)*func (xnew) <0 %% Again checking the basic requirement.
%%b=xnew;
else
a=xnew;
end
end
disp('Your root is : ')
disp(xnew)

disp('Total No. of iterations are : ')


disp(n)
z=1; %% Closing the very first while loop %%
end
end

Tasks
Write Regular-Falsi code in MATLAB and solve the following equation:

F(x)=(x) x.^3-2.*x-5 x=(1,3)

Page 14 of 49
Code:

Discussion:

Page 15 of 49
Numerical Method Lab
Experiment # 04
Secant Method

Page 16 of 49
Objective:
Find the root of non-linear equation using secant method on MATLAB and discuss the final
Result.
Theory
Secant method is considered to be the most effective approach to find the root of a non-linear function. It is a
generalized from the Newton-Raphson method and does not require obtaining the derivatives of the function.
So, this method is generally used as an alternative to Newton Raphson method.

Secant method falls under open bracket type. The programming effort may be a tedious to some extent,
but the secant method algorithm and flowchart is easy to understand and use for coding in any high-level
programming language.

This method uses two initial guesses and finds the root of a function through interpolation approach.
Here, at each successive iteration, two of the most recent guesses are used. That means, two most recent fresh
values are used to find out the next approximation.

Procedure:
1. First step is to define the equation in Matlab.
2. Enter limits (a, b) from user.
3. Now it will check whether the limits satisfy [f(a).f(b)<0 ] or not.
4. If the limits are correct, then program will proceed otherwise it would give an error.
5. Now the formula of secant method is implemented.
6. In order to get accurate result „while loop‟ is applied. It is applied in such a way that the root becomes
closer to the exact root.
7. The limits of „a‟ and „b‟ are kept between positive and negative sign.
8. Finally, the result is displayed on the output screen.
Formula:
xnew=b-(b-a)*f(b)/(f(b)-f(a))
whereas “a” and “b” are the limits between which the equation changes its sign.

Page 17 of 49
Code:

Discussion:

Page 18 of 49
Numerical Method Lab
Experiment # 05
Interpolation Method

Page 19 of 49
Objective:
Find any value of y against any value of x by using the interpolation Method.
Interpolation:
Interpolation is a technique for adding new data points within a range of a set of known data points.

Methods of interpolation:
Following are the methods of integration.

 Linear Interpolation
 Nearest Neighbor Interpolation
 Next neighbor interpolation
 Previous neighbor interpolation
 Cubic Interpolation
 Spline Interpolation

Theory
Interpolation Method
There are many cases where we have discrete data points, and we want to estimate or predict the values
at other points. Interpolation constructs a polynomial from the data points provided, which passes through all
data points and attempts to describe the behavior in between data points (and beyond them). From two points
we can construct a unique line, and from three points a unique parabola. In general, the polynomial constructed
from N+1 point will have degree N. The polynomial created from these points is unique (to polynomial
interpolation), such that all polynomial interpolation methods will output the same function.

What do we use it for?

Interpolation, especially polynomial interpolation, is useful when we have discrete data points and want
to say something about a behavior or property where the data is not defined. Polynomial interpolation is one of
multiple forms of interpolation. Spline interpolation is piecewise polynomial interpolation using small power
polynomials, to reduce errors found using high order polynomials.

Procedure:
1. In this method we use interpolation to fill in the missing data.
2. A command is used “y_sub=interp1(x,y,x_sub) “ and new data is known .
3. It will give all corresponding y-values for the set of x-values.
4. At the end a graph is plotted using “plot(x_sub,y_sub,'^-r‟)”
Example:
We have a graph, and we need to find a value of y against any value of x then we can use interpolation.

x=[1 10]%% its means value of x varies from 0 to 10 having difference of 1

y=[0 80] %% its means value of y varies from 0 to 80 having difference of 1


Page 20 of 49
plot(x,y)

grid on

yinterpolate=interp1(x,y,3) %%This command means that we Need to know the value of y when x=3 so it
gives

yinterpolate = 17.7778

MATLAB code

Output

Page 21 of 49
Code:

Page 22 of 49
MATLAB code:
x=0:20

y=x.^2

plot(x,y,'o')

x_sub=linspace(0.5,18.5,7)

y_sub=interp1(x,y,x_sub)

hold on %% hold on retains the current plot and certain axes properties so that subsequent graphing commands
add to the existing graph

plot(x_sub,y_sub,'^-r‟)

x=[1 2 3 4]

y=[0 1 2 2]

Xx=linspace

(0,6,100);

yy=spline(x,y,xx)

plot(x,y,'ro‟); (red colour with circle rep)

hold on;

plot(xx,yy,'b','linewidth',1.5);

legend('Spline data points')

Discussion and Observations:

Page 23 of 49
Numerical Method Lab
Experiment # 06
Newton's Forward interpolation and Backward Interpolation
Method

Page 24 of 49
Objective:
To find the approximate root of an equation by Newton‟s Forward & Backward Interpolation method.

Theory:
Interpolation is the process of approximating a given function, whose values are known at tabular points,
by a suitable polynomial, of degree which takes the values at for. Note that if the given data has errors, it will also
be reflected in the polynomial so obtained. Newton’s backward interpolation is another way of approximating
a function with an nth degree polynomial passing through (n+1) equally spaced points. Where s = (x - x1) / (x1 -
x0) and Ñf1 is the backward difference of f at x1. The same can be obtained from the difference operators as
follows.

FORMULA:
𝑝(𝑝+1) 𝑝(𝑝+1)(𝑝+2) 𝑝(𝑝+1)(𝑝+2)(𝑝+3)
y(x)=yn+ p∇yn+ ⋅∇2yn+ ⋅∇3yn+ ⋅∇4yn+...
2! 3! 4!

MATLAB Code:

Newton’s Forward Interpolation


n=input('Enter no of values in X: ');

for a=1:n

X(a)=input('Enter Elements of Array X : ');

end

for b=1:n

Y(b)=input('Enter Elements of Array Y : ');

end

x=input('Enter value of x for which you need value of y : ')

h=X(2)-X(1); % finding the difference between the second and first value of X

for i=1:n-1

table(i,1)=Y(i+1)-Y(i); % basically y2-y1 when i=1

end

for j=2:n-1 % for filling second column and onwards

for i=1:n-j

table(i,j)=table(i+1,j-1)-table(i,j-1);
Page 25 of 49
end

end

u=(x-X(1))/h;

prod=1;

y=Y(1);

for t=1:n-1

prod=prod*(u-t+1)/t;

y=y+prod*table(1,t);

end

Example:
Solve and find the value of y at x=52. Also, find all the values of the table of

Newton Forward difference table.

X Y = sin(x)

45 0.7071

50 0.7660

55 0.8192

60 0.8660

Page 26 of 49
Result:

Page 27 of 49
Steps to follow:
1. First, we input the number of values for x.

Page 28 of 49
2. We input values of column „x‟ and „y‟.

3. We input the value of „x‟ for which we need the solution.


4. We find the step size.
5. Then we calculate the table and find the value of „u‟.
6. We find the value of „y‟ required by using the table.

Newton Backward Interpolation Method


Code:

Page 29 of 49
Result:

Page 30 of 49
Numerical Method Lab
Experiment # 07
Lagrange Interpolation Methods

Page 31 of 49
Objective:
The objective of the lab is to use the technique of Lagrange interpolation ad discuss the final results.

Theory:
Lagrange interpolating polynomials are a particular form of Polynomials. This method is based on creating a
polynomial of degree n. The degree depends on the number of points considered in the data set so they should
be n+1points. If data points are 5 then polynomial will be of degree 4

Formula:

Procedure:
1. We are using Langrange interpolation technique for polynomial interpolation.
2. We setup the code and find the value of interpolation at desire value.
3. Certain corresponding values of x and y are(300,2.4771),(304,2.4829),(305,2.4843) and (307,2.4871).
4. Then we put y=3 in order to find out the the value at 3 and the result is displayed as shown in the
figure.
Matlab Code:
x = [300 304 305 307];
y = [2.4771 2.4829 2.4843 2.4871];
n = length(x) - 1 %%% degree of polynomial is less than the data points by 1
xp = 301; %%% Xp is the value of x whose value of y is required
sum = 0; %%% Initialization of summation variable
for i = 1 : n+1 %%%% Loop of summation
pr = 1; %%%% product variable is initialized
for j = 1 : n+1 %%%% goes from 1 to n+1
if j ~= i %%% i is not equal to j then take product
pr = pr * (xp - x(j))/(x(i) - x(j)); %%% formulae for
product in Lagrange interpolation
end
end
sum = sum + y(i) * pr;
end
display (sum)

Page 32 of 49
Observation and Discussion:

Page 33 of 49
Numerical Method Lab
Experiment # 08
Curve Fitting Method

Page 34 of 49
Objective:
The objective of the lab is to learn and use the technique of Curve fitting and discuss the final results.

Theory:

Matlab has a curve fitting toolbox that can be used to fit any curve to data. Curve fitting examines the
relationship between one or more predictors (independent variables) and a response variable (dependent
variable), with the goal of defining a "best fit" model of the relationship. Origin provides tools for linear,
polynomial, and nonlinear curve fitting along with validation and goodness-of-fit tests. You can summarize and
present your results with customized fitting reports. There are many time-saving options such as a copy-and-
paste-operation feature which allows you to "paste" a just-completed fitting operation to another curve or data
column. Curve fitting operations can also be part of an Analysis Template, allowing you to perform batch fitting
operations on any number of data files or data columns.

MATLAB Code:
For linear relation
x=[1 10]
y=[0 80]
plot(x,y)
grid on

For non-linear and 7th degree of polynomial

Page 35 of 49
x = linspace(0,4*pi,10);
y = sin(x);
p = polyfit(x,y,7);
x1 = linspace(0,4*pi);
y1 = polyval(p,x1);
figure
plot(x,y,'o')

hold on
plot(x1,y1)
hold off

Page 36 of 49
Observations and Discussions:

Page 37 of 49
Numerical Method Lab
Experiment # 09
Trapezoidal Rule
&
Rectangular Integration

Page 38 of 49
Objective:
Calculate the integral of a vector by using Trapezoidal Method.

Trapezoidal Rule:
The area under a curve is evaluated by dividing the total area into little trapezoids rather than rectangles under
this rule.

Let f(x) be continuous on [a, b]. We partition the interval [a, b] into n equal subintervals, each of width

Δx=(b−a)/n,

such that

a=x0<x1<x2<⋯<xn=b.

PURPOSE:
Trapezoidal rule is used to solve the complex integrals, which are so difficult to solve by simple integration
techniques.

Formula:
𝑏
𝑎
∫ (𝑥)𝑥≈Tn=Δx/2[f(x0)+2f(x1)+2f(x2)+⋯+2f(xn−1)+f(xn)],

where Δx=(b−a)/n and xi=a+iΔx.

𝑏
As n→∞, the right-hand side of the expression approaches the definite integral 𝑎∫ (𝑥)𝑥

Procedure:
1. Calculate the integral of a vector where the spacing between data points is 1.
2. Create a numeric vector of data
3. Y contains function values for f(x)=x^2 in the domain [1, 5].
4. Use trapz to integrate the data with unit spacing.
5. The trapz function overestimates the value of the integral because f(x) is concave up.
MATLAB Code:

>> n = 5; % number of small trapeziums formed after splitting


a = 1.0; % starting point or lower limit of the area

Page 39 of 49
b = 2.0; % end point or upper limit of the area
sum = 0.0; % to find the sum Code
dx = (b-a)/(n-1); % to find step size or height of trapezium

% Generating the samples


for i = 1:n
x(i) = a + (i-1)*dx;
end

% to generate the value of function at different values of x or


sample
for i = 1:n
y(i) = x(i).^2;
end
Output
% computation of area by using the technique
of trapezium method
for i = 1:n
if ( i == 1 || i == n) % for finding the sum of
fist and last ordinate
sum = sum + y(i)./2;
else
sum = sum + y(i); % for calculating the sum of other ordinates
end
end
area = sum * dx; % defining the area
Rectangular Integration:
Theory:

 The rectangle method computes an approximation to a definite integral, made by finding the area of a
collection of rectangles whose heights are determined by the values of the function.
 This method has less accurate approximation in few subintervals.

Formula:
𝑏
∫𝑎 𝑓(𝑥) 𝑑𝑥 ≈ ℎ { (𝑥1) + · · · + 𝑓(𝑥𝑛)

from interval a to b. This is called composite rectangle method.

Page 40 of 49
Observations and Discussions:

Page 41 of 49
Numerical Method Lab
Experiment # 10
Simpson’s rule

Page 42 of 49
Objective:
In this experiment we work to get a second order integral of a function

SIMPSON’S 1/3 INTEGRATION:


Theory:
In numerical analysis, Simpson's 1/3 rule is a method for numerical integration, the
numerical approximation of definite integrals. Specifically, it is the following approximation for n+1 values
x0…….xn bounding n equally spaced sub intervals

∫ab f(x) dx = h/3[(y0+yn) + 4(y1+y3+y5+….+yn-1)+2(y2+y4+y6+…..+yn-2)]


h=(b - a) / n.
n must be even for applying Simpson‟s 1/3 rule

Code:
clc;
clear all;
close all;
f=@(x)cos(x)-log(x)+exp(x); %Change here for different The area under the data
points is measured by this method which is our required answer. function
a=input('Enter lower limit a: '); % exmple a=1
b=input('Enter upper limit b: '); % exmple b=2
n=input('Enter the number of sub-intervals n: '); % exmple n=16
h=(b-a)/n;
if rem(n,2)==1
fprintf('\n Enter valid n!!!');
n=input('\n Enter n as even number ');
end
for k=1:1:n
x(k)=a+k*h;
y(k)=f(x(k));
end
so=0;se=0;
for k=1:1:n-1
if rem(k,2)==1
so=so+y(k);%sum of odd terms
else
se=se+y(k); %sum of even terms
end
end
% Formula: (h/3)[(y0+yn)+2(y3+y5+..odd term)+4*(y2+y4+y6+...even terms)]
Page 43 of 49
answer=h/3*(f(a)+f(b)+4*so+2*se);
fprintf('\n The value of integration is %f',answer); % exmple The value of
integration is 0.408009

Page 44 of 49
Simpson 3/8 method
Theory:
Another method of numerical integration method called “Simpson‟s 3/8 rule”. It is completely based on the
cubic interpolation rather than the quadratic interpolation. Simpson‟s 3/8 or three-eight rule is given by
Formula:

∫𝑎𝑏 (𝑥) 𝑑𝑥 = 3ℎ/8[(𝑦0+𝑦𝑛)+3(𝑦1+𝑦2+𝑦4+𝑦5+⋯.+𝑦𝑛−1)+2(𝑦3+𝑦6+𝑦9+⋯..+𝑦𝑛−3)]Where


h = (b-a)/2

Matlab Code
clc;
clear all;
f=@(x)1/(1+x); %Change here for different function
a=input('Enter lower limit a: '); % exmple a=1
b=input('Enter upper limit b: '); % exmple b=2
n=input('Enter the number of sub-intervals n: '); % exmple n=21
h=(b-a)/n;
if rem(n,3)~=0
fprintf('\n Enter valid n!!!');
n=input('\n Enter n as multiple of 3: ');
end
for k=1:1:n
x(k)=a+k*h;
y(k)=f(x(k));
end
so=0;sm3=0;% Formula: (3h/8)*[(y0+yn)+2*(y3+y6+..multiple of 3 terms)+3*(y1+y2+y4+y5+...remining terms)]
for k=2:1:n-1
if rem(k,3)==0
sm3=sm3+y(k); %sum of multiple of 3 terms
else
so=so+y(k);%sum of others terms
end
end
answer=(3*h/8)*(f(a)+f(b)+3*so+2*sm3);
fprintf('\n The value of integration is %f',answer); % exmple The value of integration is 0.381665

Page 45 of 49
Observation and Discussions:

Page 46 of 49
Numerical Method Lab
Experiment # 11

Euler's Method,
Modified Euler's method
&
Improved Euler's Method

Page 47 of 49
Objective:
Application of basic mathematical knowledge of Euler‟s Method in finding solutions of examples through
MATLAB.

Theory:
In mathematics and computational science, the Euler method (also called forward Euler method) is a first-
order numerical procedure for solving ordinary differential equations (ODEs) with a given initial value. It is the
most basic explicit method for numerical integration of ordinary differential equations.

Formula:

MATLAB CODE:
% Euler's Method
% Initial conditions and setup
h = (enter your step size here); % step size
x = (enter the starting value of x here):h:(enter the ending value of x here); % the range of x
y = zeros(size(x)); % allocate the result y
y(1) = (enter the starting value of y here); % the initial y value
n = numel(y); % the number of y values
% The loop to solve the DE
for i=1:n-1
f = the expression for y in your DE
y(i+1) = y(i) + h * f;
end

Page 48 of 49
Modified Euler's method:
In this method instead of a point, the arithmetic average of the slope over an interval is used. Thus in this
method, for each step the predicted value of is calculated first using Euler‟s method and then the slopes at the
points and is calculated and the arithmetic average of these slopes are added to calculate the corrected value of
given problem.
Formula:

ym+1=ym+hf(xm+(1/2)h,ym+(1/2)hf(xm,ym))
MATLAB Code:
clear all
clc
f=@(x,y)x+y; %Write your f(x,y) function, where dy/dx=f(x,y), x(x0)=y0.
x0=input('\n Enter initial value of x i.e. x0: '); %example x0=0
y0=input('\n Enter initial value of y i.e. y0: '); %example y0=0.5
xn=input('\n Enter the final value of x: ');% where we need to find the value of y
%example x=2

Page 49 of 49
h=input('\n Enter the step length h: '); %example h=0.2
%Formula: y1=y0+h/2*[f(x0,y0)+f(x1,y1*)] where y1*=y0+h*f(x0,y0);
fprintf('\n x y ');
while x0<=xn
fprintf('\n%4.3f %4.3f ',x0,y0);%values of x and y
k=y0+h*f(x0,y0);
x1=x0+h;
y1=y0+h/2*(f(x0,y0)+f(x1,k));
x0=x1;
y0=y1;
end

Page 50 of 49
Improved Euler’s Method:
The Improved Euler's Method addressed these problems by finding the average of the slope based on the
initial point and the slope of the new point, which will give an average point to estimate the value. It also
decreases the errors that Euler's Method would have.

Formula:

[( ) (
ym+1=ym+(1/2)h f xm,ym +f xm+h,ym+hf xm,ym ( ))]
Matlab Code:

function z=z(n,t0,t1,y0)
h=(t1-t0)/n;
t(1)=t0;
z(1)=y0;
for i=1:n
t(i+1)=t(i)+h;
z(i+1)=z(i)+((ex(t(i),z(i))+ex(t(i+1),z(i)+h*ex(t(i),z(i))))*h)/2;
end;
Observations and Discussions:

Page 51 of 49
Numerical Method Lab
Experiment # 12
MIDPOINT METHOD

Page 52 of 49
Objective:

Find the numerical solution of data using midpoint formula on MATLAB.

Theory:
Midpoint formula is the numerical technique which is used to solve ordinary differential equation. In
this method we approximate our solution with the help of graphs.

Formula:

MATLAB Code:
close all
clear all
disp(' ');
disp('This program will calculate the approximate integral');
disp('using the left, right, and midpoint rules, as well as');
disp('the trapezoidal and simpsons rule');
disp(' ');
disp(' ');
lower=1;
upper=2;
N=10;
deltax=(upper-lower)/N;
x=[lower:deltax:upper];
f=(x.^3-1).^(1/2);
lpr=0;
rpr=0;
mpr=0;
for k=1:N;
lpr=lpr+f(k)*deltax;
rpr=rpr+f(k+1)*deltax;
mpr=mpr+f((2*k+1)/2)*deltax;
tr=tr+(f(k)+f(k+1))/2*deltax;
end;
if numel(f)>1
Page 53 of 49
N=numel(f)-1;
sr= deltax/3*(f(1)+2*sum(f(3:2:end-
2))+4*sum(f(2:2:end))+f(end));
else
sr= deltax/3*(f(x(1))+2*sum(f(x(3:2:end-
2)))+4*sum(f(x(2:2:end)))+f(x(end)));
end
disp(' ');
fprintf('Midpoint approximation = %f.\n',mpr);

Observations and Discussions:

Page 54 of 49
Numerical Method Lab
Experiment # 13
Runge–Kutta Methods

Page 55 of 49
Objective:
Find the solution of ODE by R-K4 method using MATLAB.

Theory:
The Runge–Kutta methods are a family of implicit and explicit iterative methods, which include the well-
known routine called the Euler Method, used in temporal discretization for the approximate solutions
of ordinary differential equations. Runge-Kutta method is based on solution procedure of initial value problem
in which the initial conditions are known. Based on the order of differential equation, there are different Runge-
Kutta methods which are commonly referred to as: RK2, RK3, and RK4 methods.

Procedure:

 Define the initial condition in any problem.


 Define initial conditions.
 Specify the order of Runge-Kutta Method.
 Discuss the solution.
Formula:

1
𝑦(𝑥 + ℎ) = 𝑦(𝑥) + ( ) (𝐹1 + 𝐹2 + 𝐹3 + 𝐹4)
6

Whereas,

𝐹1 = ℎ(𝑥, 𝑦)
ℎ 𝐹1
𝐹2 = ℎ𝑓 (𝑥 + ,𝑦 + )
2 2
ℎ 𝐹2
𝐹3 = ℎ𝑓 (𝑥 + ,𝑦 + )
2 2

Matlab Code:
clc;
clear all;
h=1.5;
x = 0:h:3;
y = zeros(1,length(x));
y(1) = 5;
F_xy = @(t,r) 3.*exp(-t)-0.4*r;
for i=1:(length(x)-1)
k_1 = F_xy(x(i),y(i));

Page 56 of 49
k_2 = F_xy(x(i)+0.5*h,y(i)+0.5*h*k_1);
k_3 = F_xy((x(i)+0.5*h),(y(i)+0.5*h*k_2));
k_4 = F_xy((x(i)+h),(y(i)+k_3*h));
y(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;

end

Observations and Discussions:

Page 57 of 49

You might also like