0% found this document useful (0 votes)
18 views

NUMERICAL METHODS FOR ENGINEERS LAB

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

NUMERICAL METHODS FOR ENGINEERS LAB

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

NUMERICAL METHODS FOR ENGINEERS LAB

[MEEN-3234]
Lab Manual

SUBMITTED TO:
Dr. Muhammad Ijaz Khan

SUBMITTED BY:
Name: Zohaib Javad
Registration No: Meen221101049
Class: BS-MEEN-4

INSTITUTE OF MECHANICAL AND MANUFACTURING ENGINEERING


(IMME)
KHWAJA FAREED UNIVERSITY OF ENGINEERING & INFORMATION
TECHNOLOGY, RAHIM YAR KHAN
Lab Report 01
Objective:
Introduction to MATLAB and learn about basic arithmetic and matrices.

Introduction
MATLAB:
MATLAB (an abbreviation of "matrix laboratory") is a proprietary multi-paradigm
programming language and numeric computing environment developed by MathWorks.This is
a high-level matrix/array language with control flow statements, functions, data structures,
input/output, and object-oriented programming features.

Matlab or Matrix Laboratory is a high-level programming language consisting of an interactive


environment mainly used for numeric computation, programming, and visualization. It has
been developed by MathWorks. The basic functions of Matlab are plotting of functions and
data, the creation of user interfaces, matrix manipulations.

Applications of MATLAB:

Matlab is widely used in the industry as a tool for mathematical computation and different
streams of studies like physics chemistry, engineering, mathematics, Etc. The various
applications involving Matlab are below

1. Computational Finance
2. Control systems
3. Signal Processing and communication
4. Test and Measurement
5. Image and video processing
6. Computational

biology For command entry

we use

➢ M-File Editor (Only use for code writing)


➢ Command Window (Use for code writing and also show results)

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.

Let’s start by entering a few really basic commands. If you want to fi nd the value of a numerical
expression, simply type it in. Let’s say we want to know the value of 433.12 multiplied by 15.7.
We type 433.12 * 15.7 at the MATLAB prompt and hit the enter key.

The result looks like this:

>> 433.12*15.7

ans =

6.8000e+003

For Store value in any variable:

We might want to call a variable x. Suppose we want to set it equal to five multiplied by six. To
do this, we type the input as

>> x=5*6

x=
30

Once a variable has been entered into the system, we can refer to it later. Suppose that we want to
compute a new quantity that we’ll call y, which is equal to x multiplied by 3.56. Then we type

>> y = x * 3.56

y=

106.8000

Basic Arithmetic:

➢ Let’s summarize basic arithmetical input in MATLAB. To write the multiplication ab, in
MATLAB we type

>>a * b

➢ For division, the quantity a divided by b is typed as

>>a / b

➢ Exponentiation ab is entered in the following way

>>a ^ b

➢ Finally, addition and subtraction are entered in the usual way


>>a + b >>a – b

Example No 01

Use MATLAB to evaluate

5( 𝟑 ) + ( 𝟗 ) and 43 [ (𝟑) +( 𝟗 )]
𝟒 𝟓 𝟒 (𝟐)𝟑

Solution
𝟗
➢ 5( 𝟑 ) + ( )
𝟒 𝟓

The command required to find the value of the first expression is

>> 5*(3/4) + 9/5

ans =

5.5500
𝟑 𝟗
➢ 43 [ ( ) +( )]
𝟒 (𝟐)𝟑

For the second expression,

>> r = 4^3

r=

64

>> s = 3/4 + 9/(2*3)

s=

2.2500

>> t=r*s

t=
144

For Showing Answer to Four Decimal Digits:

MATLAB has been spitting out numbers with four decimal places. This is known as short format
in MATLAB.

For Example:

>> format short

>> x = 3 + 11/16 + 2^1.2

x=

5.9849
For Showing Answer to 16 Decimal Digits:

If we want 16 digits instead of 4, we type format long. To see how this works, look at the following
calculation,

For Example:

>> format long

>> x = 3 + 11/16 + 2^1.2

x=

5.98489670999407
MATLAB displays large numbers using exponential notation. That is it represents 5.4387 × 103
as 5.4387e + 003.

For short (four decimal places plus the exponent) you can type format short e.

For Example:

>> format short e

>> x = 3 + 11/16 + 2^19

x=

5.2429e+05

To allow 15 decimal digits plus the exponent, type format long e.

>> format long e

>> x = 3 + 11/16 + 2^19

x=

5.242916875000000e+05
Commands Used to Clear Command Window:

➢ Clear all
➢ CLC
➢ Close all

Basic Notes:

➢ To open previous code press [ ] key.


➢ If we don’t want to show answer in command window write ( ; ) next to equation.
➢ If we write ‘who’ it will show all variables in workspace.
➢ If we write ‘whos’ it will show all variables including ans and also showing how its matrix
will be formed.

Example No 02

Find the volume of a sphere of radius 2 m.

Solution:

The volume of a sphere is given by

V = 𝟒πR3
𝟑

>> r = 2;
>> V = (4/3) *pi*r^3

V=

33.5103

Another famous number that shows up in many mathematical applications is the exponential
function. That is, e ≈ 2.718. We can reference e in MATLAB by typing exp(a) which gives us the
value of ea . Here are a few quick examples

>> exp(1)

ans =

2.7183
>> exp(2)

ans =

7.3891

To find the square root of a number, we type sqrt.

For Example

>> x = sqrt(9)

x=

3
>> y = sqrt(11)

y=

3.3166

To find the natural log of a number x, type log(x).

>> log(3.2)

ans =

1.1632

>> x = 5; log(5)

ans =

1.6094

If you want the base ten logarithm, type log10(x):

>> x = 3; log10(x)

ans =

0.4771

If you want the find any value of cosine :

>> cos(pi/4)

ans =

0.7071

To use an inverse of a trignometric function, add on an a before the name of the trignometric
function. For example, to compute the inverse tangent of a number we can use the following

>> format rat

>> atan(pi/3)

ans =
1110/1373

If we want to enter complex number in MATLAB:

We can also enter complex numbers in MATLAB. To remind members of our audience who are
Aggie graduates, the square root of –1 is defined as i

A complex number is one that can be written in the form z = x +iy, where x is the real part of z
and y is the imaginary part of z. It is easy to enter complex numbers in MATLAB, by default it
recognizes i as the square root of minus one.

For Example:

>> format short

>> a = 2 + 3i;

>> b = 1 - i;

>> c = a +

bc=

3.0000 + 2.0000i
If we want to show value in form of matrix in MATLAB:

>>x = [1:2:3:4];

>>y = exp(x)

y=

2.7183 7.3891 20.0855 54.5982

If you want to show the size of matrix in MATLAB:

For Example:

>>x = [1:2:3:4];
>>y = exp(x)

y=

2.7183 7.3891 20.0855 54.5982

To compute the size of a above matrix y we can use the following;

>>size (y)

ans =

1 4

If you want to show the transpose of any matrix in MATLAB:

For Example:

y=

2.7183 7.3891 20.0855 54.5982

To compute the transpose of above matrix y we can use the following;

>> transpose (y)

ans =
2.7183

7.3891

20.0855

54.5982
Lab Report 02
Objective:
To perform basic operations and learn about vector and matrices on MATLAB.

Vector:
A vector is a one-dimensional array of numbers. MATLAB allows you to create column
vectors or row vectors. A column vector can be created in MATLAB by enclosing a set of
semicolon delimited numbers in square brackets. Vectors can have any number of
elements.

Column Vector:

For Example:

To create a column vector with five elements we write:

>> a = [2; 1; 3; 6]

a=

6
Row Vector:

To create a row vector, we enclose a set of numbers in square brackets but this time use a space or
comma to delimit the numbers. For example:

>> v = [2 0 4]

v=

2 0 4

Or using commas:

>> w = [1,1,9]

w=

1 1 9

If we find maximum or minimum value in matrix:

For Example:

>> a = [2: 14]

a=

2 3 4 5 6 7 8 9 10 11 12 13 14
For Maximum Value;

>>max (a)

ans =

14

For Minimum Value;

>> min (a)

ans =

For Transpose of Any Matrix:

For Example:

First we imagin any matrix;

>> a = [2: 10]

a=

2 3 4 5 6 7 8 9 10

For transpose of this matrix ‘a’ we write

>> b = a’
b=

10

Multiplication corresponding values of matrix:

For multiplication of one matrix with another matrix (same order of both matrix) ,we write as
follows

>> a = (1:3)
a=

1 2 3

>> b = (4:6)

b=

4 5 6

>> c = (a.*b)

c=

4 10 18

Addition of values of matrix:

For Example:

c=

4 10 18

>> d = sum (c)

d=

32
Conjugate of any complex number:

First imagin any complex number in the form of x+yi,

For Example:

>> a = 3 + 4i

a=

3.0000 + 4.0000 i

For conjugate of complex number ‘a’ we write

>> b = conj (a)

b=

3.0000 - 4.0000i

Dot Product of any vector:

For Example:

First we imagin two matrix

>> a = (1:5)
a=

1 2 3 4 5

>> b = (6:10)

b=

6 7 8 9 10

>> c= dot(a , b)

c=

130

Cross Product of any vector:

>> A = [1 2 3];

>>B = [2 3 4];

>> C = cross(A,B)

C=

–1 2 –1
Chracterizing a vector:

The length command returns the number of elements that a vector contains. For example:

>> A = [2;3;3;4;5];

>> length(A)

ans =

Refrencing Vector Components:

MATLAB has several techniques that can be used to reference one or more of the components of
a vector. The ith component of a vector v can be referenced by writing v(i).

For Example:

>> A = [12; 17; –2; 0; 4; 4; 11; 19; 27];

>> A(2)

ans =

17
Referencing the vector with a colon, such as v(:); tells MATLAB to list all of the components of
the vector:

>> A(:)

ans =

12

17

11

19

27

We can also pick out a range of elements out of a vector. We can reference components four to six
by writing A(4:6) and use these to create a new vector with three components:

>> v = A(4:6)

v=

0 4 4

Basic Operations with Matrices:

A matrix is a two-dimensional array of numbers. To create a matrix in MATLAB, we enter each


row as a sequence of comma or space delimited numbers, and then use semicolons to mark the end
of each row.

For Example

>> A = [1,6; 7, 11]


A=

1 6

7 11

If two matrices have the same number of rows and columns, we can add and subtract them:

>> A = [5 1 ; 0 9];

>> B = [2 –2 ; 1 1];

>> A + B

ans =

7 –1

1 10

>> A – B

ans =

3 3

–1 8
Matrix Multiplication:

Consider two matrices A and B. If A is an m × p matrix and B is a p × n matrix, they can be


multiplied together to produce an m × n matrix. To do this in MATLAB, we leave out the period
(.) and simply write A*B. Keep in mind that if the dimensions of the two matrices are not correct,
the operation will generate an error.

For Example:

>> A = [2 1; 1 2]

A=

2 1

1 2
>> B = [3 4; 5 6]

B=

3 4

5 6

These are both 2 × 2 matrices, so matrix multiplication is permissible.

>> A.*B

ans =

6 4

5 12

Special Matrix Types:


➢ Identity Matrix
The identity matrix is a square matrix that has ones along the diagonal and zeros elsewhere.To
create an n × n identity matrix, type the following MATLAB command:
eye(n)
Let’s create a 4 × 4 identity matrix:
>> eye(4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

➢ Null Matrix
In mathematics, the zero matrix, also called null matrix, is a matrix which all its elements are equal
to zero. The zero matrix is denoted by the symbol O.

Let’s create a 4 × 4 null matrix:


>> zeros(4)
ans =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

Refrencing Matrix Elements:


Individual elements and columns in a matrix can be referenced using MATLAB.
Consider the matrix:
>> A = [1 2 3; 4 5 6; 7 8 9]
A=

1 2 3

4 5 6

7 8 9

We can pick out the element at row position m and column position n by typing A(m,n).

For Example:

>> A(2,3)

ans =

To reference all the elements in the ith column we write A(:,i).

For Example:

we can pick out the second column of A:

>> A(:,2)

ans =

We can pick out pieces or submatrices as well. Continuing with the same matrix,to pick out the
elements in the second and third rows that are also in the first and second columns, we write:

>> A(2:3,1:2)

ans =

4 5

7 8
We can change the value of matrix elements using these references as well.Let’s change the
element in row 1 and column 1 to ‘18’:

We write;

>> A(1,1) = 18

A=

18 2 3

4 5 6

7 8 9

To create an empty array in MATLAB, simply type an empty set of square braces [ ].This can be
used to delete a row or column in a matrix.

For Example:

Let’s delete the second row of A:

>> A(2,:)=[ ]
A=

18 2 3

7 8 9
Lab Report No 03
Objective:

Perform Basic 2D Plotting (plot a function, adding labels and titles to the plot) in MATLAB.

Basic 2D Plotting:

Let’s start with the most basic type of plot we can create, the graph of a function of one
variable. Plotting a function in MATLAB involves the following three steps:

1. Define the function


2. Specify the range of values over which to plot the function
3. Call the MATLAB plot(x, y) function

Let’s plot the function y = cos(x) over the range 0 ≤ x ≤ 10. To start, we want to define this
interval and tell MATLAB what increment to use. The interval is defined using square
brackets [] that are filled in the following manner:

[ start : interval : end ]

For example, if we want to tell MATLAB to plot over 0 ≤ x ≤ 10 with an interval of 0.1, we type:

[0:0.1:10]

To assign this range to a variable name,we use the assignment operator.We also do this to
tell MATLAB what the dependent variable is and what function we want to plot.Hence to
plot y = cos(x), we enter the following commands:

>> x = [0:0.1:10];

>> y = cos(x)
Notice that we ended each line with semicolons. Remember, this suppresses MATLAB
output. It’s unlikely you would want MATLAB to spit out all the x values over the interval
onto the screen, so we use the semicolon to prevent this.Now we can plot the function. This
is done by entering the following command:

>> plot(x, y)
A plot of y = cos(x) generated by MATLAB for 0 ≤ x ≤ 10.
Example No 02:

A plot of y = cos(x) generated by MATLAB for 0 ≤ x ≤ 10.

Solution:

>> x = [0:0.1:10];

>>y = cos(x);

>> plot(x, y)
>> x = [0:1:10];

>>y = cos(x);

>>plot(x, y)
Plotting with Title and axis labels:

If we want to add labels and a title to the plot in fig:(2), the command used to add label to horizontal
axis is xlabel(‘x’) and to vertical axis is ylabel(‘y’). To add title to the plot command used is
title(‘Plot of y = cos(x) generated by MATLAB for 0 ≤ x ≤ 10 with interval of 1’).

Following above commands and using them in MATLAB we get,


Lab Report N04

Objective:

By using ‘For Loops or While Loop’ and also learn about conditional statements.

Programming with For Loops:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times. The for loop in Matlab grants the programmers to repeat the
certain commands. Therefore, if you want to repeat a few actions in a predefined manner, one can
use this loop. There are several loop syntax in Matlab that is starting with the keyword like while
or for and end with the statement ‘end’. The for loop statement is coded around a few sets of
statements; therefore, it becomes necessary to tell the Matlab function that where to initiate and
where to stop the execution.

A For Loop is an instruction to MATLAB telling it to execute the enclosed statements a certain
number of times. The syntax used in a For Loop is:

for index = start : increment :

finish statements

end

We can illustrate this idea by writing a simple function that sums the elements in a row or column
vector. If we leave the increment parameter out of the For Loop statement, MATLAB assumes that
we want the increment to be one.

We can illustrate this idea by writing a simple function that sums the elements in a row or column
vector . If we leave the increment parameter out of the For Loop statement, MATLAB assumes
that we want the increment to be one.
The first step in our function is to declare the function name and get the size of the array passed to
our function:
function sumx = mysum(x)
%get number of elements
num = size(x);
We’ve added a new programming element here—we included a comment. A comment is an
explanatory line for the reader that is ignored by MATLAB. We indicate comments by placing a
% character in the first column of the line. Now let’s create a variable to hold the sum and initializeit
to zero:
%initialize total
sumx = 0;
Now we use a For Loop to step through the elements in the column vector 1 at a time:
for i = 1:num(2)
sumx = sumx + x(i);
end
Example No 01:
While Loop:
A "while" loop in MATLAB is a fundamental programming construct that allows you to repeatedly
execute a block of code as long as a specified condition is true. It's particularly useful when you
don't know in advance how many times you need to execute the code.

Let's delve into the theory behind while loops in MATLAB:

1. Initialization: Before entering the loop, you typically initialize variables that will be used in the
loop. This step ensures that your variables have initial values and sets the stage for the loop's
execution.

2. Condition Evaluation: Once inside the loop, MATLAB evaluates the condition specified after the
"while" keyword. If the condition is true, MATLAB executes the code block inside the loop.

3. Code Execution: The code within the loop block is executed sequentially. This block can contain
any valid MATLAB code, such as calculations, function calls, or conditional statements.

4. Updating Variables: To prevent infinite loops, it's crucial to include code within the loop that
updates variables involved in the condition evaluation. This step ensures that the condition
eventually becomes false, terminating the loop.

5. Loop Termination: When the condition evaluates to false, MATLAB exits the loop and continues
with the code after the "end" statement following the loop block.

While loops are versatile and can be used for various tasks, such as iterating through arrays, performing
repetitive calculations, or implementing algorithms that require iterative steps.

However, it's essential to use while loops judiciously and ensure that the condition eventually becomes
false to prevent infinite loops. Debugging infinite loops can be challenging, and they can consume
excessive computational resources or even crash your MATLAB session.
Example No 01:
Lab Report 05
Objective:
Introduction about Taylor’s Series Method.

Taylor’s Series Method:


Taylor series is a powerful mathematical tool used to represent functions as infinite
series of polynomials. It's named after the British mathematician Brook Taylor, who introduced
the concept in the 18th century. This method provides a way to approximate a complex function
by expressing it as a sum of terms that are derived from the function's derivatives at a single point.

At the heart of the Taylor series method lies the notion of approximation. It enables us to
approximate complicated functions with simpler ones, making it easier to analyze and manipulate
them. The key idea is to represent a function f(x) as an infinite sum of terms involving its
derivatives evaluated at a specific point.

Let's delve into the foundational concept behind Taylor series. Consider a function f(x) that is
infinitely differentiable in some interval containing a point 'a'. The Taylor series expansion of f(x)
about the point 'a' is given by:

f(x)=f(a)+f′(a)(x−a)+f′′(a)2!(x−a)2+f′′′(a)3!(x−a)3+⋯f(x) = f(a) + f'(a)(x-a) + \frac{f''(a)}{2!}(x-


a)^2 + \frac{f'''(a)}{3!}(x-a)^3 + \cdotsf(x)=f(a)+f′(a)(x−a)+2!f′′(a)(x−a)2+3!f′′′(a)(x−a)3+⋯

Here, f'(a), f''(a), f'''(a), etc., represent the first, second, third, and higher-order derivatives of f(x)
evaluated at the point 'a'. The terms (x-a), (x-a)^2, (x-a)^3, etc., are powers of the difference
between the variable x and the point 'a'.

The Taylor series provides a polynomial approximation to the function f(x) centered around the
point 'a'. As more terms are included in the series, the approximation becomes increasingly
accurate, especially near the point 'a'. However, it's important to note that the accuracy of the
approximation diminishes as you move further away from 'a', especially for functions with
complex behavior.

One of the primary applications of Taylor series is in calculus, where it facilitates the analysis of
functions and their behavior. By expressing a function as a Taylor series, mathematicians can study
its properties, such as continuity, differentiability, and convergence, with greater ease.
Additionally, Taylor series are instrumental in solving differential equations, as they enable the
transformation of a differential equation into an algebraic one.

Another significant application of Taylor series is in numerical analysis and scientific computing.
Since many functions encountered in real-world problems cannot be expressed in closed form,
Taylor series provide a means to approximate these functions using a finite number of terms. This
approximation is particularly useful in numerical methods for solving equations, optimization
problems, and simulating physical systems.

Despite its utility, Taylor series have limitations. They are only valid within a certain radius of
convergence, which depends on the behavior of the function and the point of expansion. Beyond
this radius, the series may diverge or fail to accurately represent the function. Moreover, computing
Taylor series with a large number of terms can be computationally intensive, limiting their
practicality in some scenarios.
Lab Report 06
Objective:
Introduction about Bisection method.

Bisection Method

The bisection method is used for finding the roots of transcendental equations or algebraic
equations. This is also called a bracketing method as its brackets the root within the interval. The
selection of the interval must be such that the function changes its sign at the end points of the
interval. This method is basically used for solving the equations of the form of f(x)=0. This is
actually a graphical method where the graph of the function is drawn and we notice where the
function cuts the x -axis. This point is called the root of the equation.
Graphical methods gives us an approximation of the roots plus also some very useful information
that can help us for finding the number of roots.
If both the upper and lower point gives the positive value of the function, then either the function
has no root or even number of roots. If the functions has opposite signs at the end points of the
interval then there will be odd number of roots as shown in the figure below;

Figure. Graphical method for root location


When the function is tangent to x-axis then multiple roots exist. In that case the function may be
changing its sig at the end points of the interval, there will be even number of roots as depicted in
the following figure;

Figure. Roots location when graph is tangential

Steps for solving Bisection Method:

Step 01:

Choose lower xl and upper xu guesses for the root such that the function changes sign over the
interval. This can be checked by ensuring that f(xl )f(xu) < 0.

Step 02:

An estimate of the root xr is determined by

𝑥𝑙 + 𝑥𝑢2
𝑥𝑟 =

Step 03:

Make the following evaluations to determine in which subinterval the root lies:

➢ If f(xl )f(xr)< 0, the root lies in the lower subinterval. Therefore, set xu=xr and return to
step 2.
➢ If f(xl )f(xr)>0, the root lies in the upper subinterval. Therefore, set xl=xr and return to
step 2.
➢ If f(xl )f(xr)= 0, the root equals xr; terminate the computation.
Implementation of Bisection method on MATLAB:

Example No 01:

Determine the real root of f(x)=5x3-5x2+6x-2 by using the bisection method.Employ initial guesses
of xl=0 and xu=1 and iterate until the estimated error ea falls below a level of es=10%.

Solution:

>>clear all
>>close all
>>clc
>>xl = input ('Enter lower limit of this function=')
>>fxl = (5*(xl^3))-(5*(xl^2))+(6*xl)-2
>>xu = input ('Enter upper limit of this function=')
>>fxu = (5*(xu^3))-(5*(xu^2))+(6*xu)-2
>>for i=1:1:10
>>xr(i)=(xl+xu)/2
>>fxr(i) = (5*(xr(i)^3))-(5*(xr(i)^2))+(6*xr(i))-2
>>if fxl*fxr(i)<0
>>xu=xr(i)
>>else if fxl*fxr(i)>0
>>xl=xr(i)
>>else
>>xr(i)
>>end
>>end
>>if i>1
>>e(i) = ((xr(i)-xr(i-1))/xr(i))*100
>>if norm(e(i))<10
>>xr(i-1)
>>break
>>end
>>end
>>end
>>xr(i)
Screenshots:
Enter lower limit of this function=10

xl =

10

fxl =

4558

Enter upper limit of this function=15

xu =

15

fxu =

15838
xr =

12.5000

fxr =

9.0574e+03

xl =

12.5000

xr =
12.5000 13.7500

fxr =

1.0e+04 *

0.9057 1.2133

xl =

13.7500

e=

0 9.0909

ans =

12.5000

ans =

13.7500
Lab Report 07
Objective:
Introduction and implementation of Newton Raphson and Secant method.

Newton Raphson method

In numerical analysis, Newton's method, also known as the Newton–Raphson method, named
after Isaac Newton and Joseph Raphson, is a root-finding algorithm which produces
successivelybetter approximations to the roots (or zeroes) of a real-valued function. The most
basic version starts with a single-variable function f defined for a real variable x, the function's
derivative f ′, andan initial guess x0 for a root of f. If the function satisfies sufficient
assumptions and the initial guessis close,then

is a better approximation of the root than x0. Geometrically, (x1, 0) is the intersection of the x-
axis and the tangent of the graph of f at (x0, f (x0)): that is, the improved guess is the unique root
of thelinear approximation at the initial point. The process is repeated as

until a sufficiently precise value is reached. This algorithm is first in the class of Householder's
methods, succeeded by Halley's method. The method can also be extended to complex
functions and to systems of equations.
The idea is to start with an initial guess, then to approximate the function by its tangent line,
and finally to compute the x-intercept of this tangent line. This x-intercept will typically be a
better approximation to the original function's root than the first guess, and the method can be
iterated.

If the tangent line to the curve f(x) at x=xn intercepts the x-axis at xn+1 then the slope is
Solving for xn + 1 gives

We start the process with some arbitrary initial value x0. (The closer to the zero, the better. But, in
the absence of any intuition about where the zero might lie, a "guess and check" method might
narrow the possibilities to a reasonably small interval by appealing to the intermediate value
theorem.) The method will usually converge, provided this initial guess is close enough to the
unknown zero, and that f ′(x0) ≠ 0. Furthermore, for a zero of multiplicity 1, the convergence is at
least quadratic (see rate of convergence) in a neighbourhood of the zero, which intuitively means
that the number of correct digits roughly doubles in every step.

Implementation of Newton Raphson method on MATLAB:

c=

2.0000
1.7500
0
0
0
0
0
0
0
0
0

c=

2.0000
1.7500
1.7321
0
0
0
0
0
0
0
0

c=

2.0000
1.7500
1.7321
1.7321
0
0
0
0
0
0
0

c=

2.0000
1.7500
1.7321
1.7321
1.7321
0
0
0
0
0
0
c=

2.0000
1.7500
1.7321
1.7321
1.7321
1.7321
0
0
0
0
0

c=

2.0000
1.7500
1.7321
1.7321
1.7321
1.7321
1.7321
0
0
0
0

c=

2.0000
1.7500
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
0
0
0

c=

2.0000
1.7500
1.7321
1.7321
1.7321
1.7321
1.7321
0
0

c=

2.0000
1.7500
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
0

c=

2.0000
1.7500
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321

c=

2.0000
1.7500
1.7321
1.7321
1.7321
1.7321
1.7321
1.7321
Secant Method

A potential problem in implementing the Newton-Raphson method is the evaluation of the


derivative. Although this is not inconvenient for polynomials and many other functions, there are
certain functions whose derivatives may be extremely difficult or inconvenient to evaluate. For
these cases, the derivative can be approximated by a backward finite divided difference.

This approximation can be substituted to yield the following iterative equation:

This technique is similar to the Newton-Raphson technique in the sense that an estimate of the root
is predicted by extrapolating a tangent of the function to the x axis. However, the secant method
uses a difference rather than a derivative to estimate the slope.Graphical depiction of the secant
method is given below:

Steps for solving Secant Method:

There are some steps which are involved in secant method.

Step 01: Initialization ,two initial guesses x0 and x1 of r are chosen.


Step 02: Iteration: For n = 1; 2; 3; · · ·,

until certain stopping criterion is satisfied (required solution accuracy or maximal number of
iterations is reached).

For Example
Lab Report 08

Objective:

Implementation of gauss elimination to find out the number of solutions by appropriate row and
column operations to form upper and lower triangular matrix.

Gauss Elimination method

In the previous section, the elimination of unknowns was used to solve a pair of simultaneous
equations. The procedure consisted of two steps:

➢ The equations were manipulated to eliminate one of the unknowns from the equations. The
result of this elimination step was that we had one equation with one unknown.
➢ Consequently, this equation could be solved directly and the result back-substituted into one
of the original equations to solve for the remaining unknown.

This basic approach can be extended to large sets of equations by developing a systematic scheme
or algorithm to eliminate unknowns and to back-substitute. Gauss elimination is the most basic of
these schemes.

This section includes the systematic techniques for forward elimination and back substitution that
comprise Gauss elimination. Although these techniques are ideally suited for implementation on
computers, some modifications will be required to obtain a reliable algorithm. In particular, the
computer program must avoid division by zero. The following method is called “naive” Gauss
elimination because it does not avoid this problem. Subsequent sections will deal with the
additional features required for an effective computer program.

The approach is designed to solve a general set of n equations


As was the case with the solution of two equations, the technique for n equations consists of two
phases: elimination of unknowns and solution through back substitution.

Forward Elimination of Unknowns: The first phase is designed to reduce the set of equations to
an upper triangular system .The initial step will be to eliminate the first unknown, x1, from the
second through the nth equations. To do this, multiply Eq b1 by a21/a11 to give

Now, this equation can be subtracted from Eq b2 to give

Or

where the prime indicates that the elements have been changed from their original values.

The procedure is then repeated for the remaining equations. For instance, Eq b1 can be multiplied
by a31/a11 and the result subtracted from the third equation. Repeating the procedure for the
remaining equations results in the following modified system:

Note that the process of multiplying the fi rst row by a21/a11 is equivalent to dividing it by a11
and multiplying it by a21. Sometimes the division operation is referred to as normalization. We
make this distinction because a zero pivot element can interfere with normalization by causing a
division by zero. We will return to this important issue after we complete our description of naive
Gauss elimination.

Now repeat the above to eliminate the second unknown.

Back Substitution:

Above equation can now be solved for xn

This result can be back-substituted into the (n - l)th equation to solve for xn-1. The procedure, which
is repeated to evaluate the remaining x’s, can be represented by the following formula:

The two phases of Gauss elimination ,forward elimination and back substitution. The primes
indicate the number of times that the coefficients and constants have been modified shown below;
Question:Implementation of gauss elimination to find out the number of solutions by appropriate
row and column operations to form upper and lower triangular matrix.

Solution:

MATLAB code

C = [1 2 -1; 2 1 -2; -3 1 1]

b= [3 3 -6]'

A=[C b]; %Augmented Matrix

n= size(A,1);

x = zeros(n,1); %variable matrix [x1 x2 ... xn] coulmn

for i=1:n-1

for j=i+1:n

m = A(j,i)/A(i,i)

A(j,:) = A(j,:) - m*A(i,:)

end

end

x(n) = A(n,n+1)/A(n,n)

for i=n-1:-1:1

summ = 0

for j=i+1:n

summ = summ + A(i,j)*x(j,:)

x(i,:) = (A(i,n+1) - summ)/A(i,i)

end

e
Lab Report 09

Objective:

Implementation of 4th order range kutta to find out the solutions for ordinary differential equation.

Runge Kutta Method


In numerical analysis, the Runge–Kutta methods are iterative methods, which include the
Euler method, used in temporal discretization for the approximate solutions of simultaneous
non-linear equations. These methods were developed around 1900 by the German
mathematicians Carl Runge and Wilhelm Kutta.Runge–Kutta method is an effective and
widely used method for solving the initial-value problems of differential equations. Runge–
Kutta method can be used to construct high order accurate numerical method by functions'
self without needing the high order derivatives of functions.
The main advantages of Runge-Kutta methods are that they are easy to implement, they are
very stable, and they are ``self-starting'' (i.e., unlike muti-step methods, we do not have to
treat the first few steps taken by a single-step integration method as special cases).
Runge Kutta 4th Order:
The most commonly used Runge Kutta method to find the solution of a differential equation
is the RK4 method, i.e., the fourth-order Runge-Kutta method. The Runge-Kutta method
provides the approximate value of y for a given point x. Only the first order ODEs can be
solved using the Runge Kutta RK4 method.

The formula for the fourth-order Runge-Kutta method is given by:

y1 = y0 + (⅙) (k1 + 2k2 + 2k3 + k4)

Here,

k1 = f (x0, y0)

k2 = f [x0 + (½)h, y0 + (½)k1]

k3 = f [x0 + (½)h, y0 +

(½)k2] k4 = f (x0 + h, y0

+ k3)
MATLAB Code:

>>clc;
>>clear all;
>>close all;
>>h=1;
>>x = 0:h:3;
>>y = zeros(1,length(x));
>>y(1) = 5;
>>F_xy = @(m,n) 9.*exp(-m)-0.8*n;
>>for i=1:(length(x)-1)
>>k1 = F_xy(x(i),y(i));
>>k2 = F_xy(x(i)+0.5*h,y(i)+0.5*h*k1)
>>k3 = F_xy((x(i)+0.5*h),(y(i)+0.5*h*k2));
>>k4 = F_xy((x(i)+h),(y(i)+k3*h));
>>y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h;
>>end

K2=

-0.5412

K3=

-2.1353
K4= -1.6602
Example No 2
Lab Report 10

Objective:
Introduction about Trapezoidal Rule.

Trapezoidal Rule
The Trapezoidal Rule is a numerical method used for estimating the definite integral of a function.
It's particularly useful when the function lacks an elementary antiderivative or when direct
integration is impractical. Developed as a part of calculus, it provides an approximation of the area
u At its core, the Trapezoidal Rule approximates the area under a curve by partitioning the interval into
smaller segments and approximating the area of each segment with a trapezoid. The width of each
trapezoid corresponds to the width of the interval, while the height is determined by the function values at
the endpoints of the interval.

Derivation of the Formula

The formula for the Trapezoidal Rule can be derived using basic geometric principles. Consider
dividing the interval [a, b] into n subintervals of equal width h = (b - a) / n. The area of each
trapezoid is then given by the formula:

Ai=12(f(xi)+f(xi+1))(xi+1−xi)A_i = \frac{1}{2}(f(x_{i}) + f(x_{i+1}))(x_{i+1} - x_{i})Ai=21


(f(xi)+f(xi+1))(xi+1−xi)

where xix_ixi and xi+1x_{i+1}xi+1 are the endpoints of the i-th subinterval.

Summing up the areas of all trapezoids from i = 0 to n-1 gives an approximation of the integral:

∫abf(x)dx≈∑i=0n−1Ai\int_{a}^{b} f(x) dx \approx \sum_{i=0}^{n-1} A_i∫abf(x)dx≈∑i=0n−1Ai

Error Analysis

Like any numerical method, the Trapezoidal Rule introduces error in its approximation. However,
the error can be quantified and controlled. The error depends on several factors, including the
choice of partition size and the behavior of the function within the interval. In general, decreasing
the width of the subintervals leads to a more accurate approximation.
The error in the Trapezoidal Rule can be expressed using Taylor series expansion and is
proportional to h2h^2h2, where h is the width of the subintervals. This makes the Trapezoidal Rule
a member of the class of quadrature methods known as O(h^2) methods.

Applications

The Trapezoidal Rule finds widespread application in various fields, including engineering,
physics, economics, and computer science. It is particularly useful in problems where analytical
solutions are difficult to obtain or where computational efficiency is paramount.

In engineering, for example, the Trapezoidal Rule is used to approximate the area under the curve
in problems involving the calculation of work, fluid flow, and heat transfer. In physics, it finds
application in problems related to motion, energy, and electromagnetism. In economics, it is used
to estimate consumer and producer surplus in market analysis.

Extensions and Improvements

While the basic Trapezoidal Rule provides a reasonable approximation of the integral, several
extensions and improvements have been developed to enhance its accuracy and efficiency. One
such extension is Simpson's Rule, which approximates the area under the curve using quadratic
polynomials instead of straight lines. Simpson's Rule typically provides a more accurate
approximation than the Trapezoidal Rule for smooth functions.

Additionally, adaptive quadrature methods have been developed to automatically adjust the
partition size based on the behavior of the function. These methods offer improved accuracy and
efficiency by concentrating computational effort where it is most needed.
Example:

Output
Lab Report 11
Objective:
Introduction about simpson 1/3 Rule.

simpson 1/3 Rule.


In the vast landscape of numerical methods for integration, Simpson's 1/3 Rule stands out as a
powerful and widely-used technique. Named after Thomas Simpson, an English mathematician of
the 18th century, this rule provides an efficient means of approximating the definite integral of a
function. Over the years, it has found applications in various fields ranging from physics and
engineering to economics and computer science. In this comprehensive exploration, we delve into
the intricacies of Simpson's 1/3 Rule, uncovering its origins, principles, applications, and
limitations.

The Genesis of Simpson's Rule

The story of Simpson's Rule begins with the quest for efficient methods to approximate integrals.
Prior to Simpson's contributions, mathematicians relied on techniques like the trapezoidal rule,
which approximated the area under a curve by dividing it into trapezoids. However, Simpson
sought to refine this approach by introducing quadratic approximations instead of linear ones.

In 1743, Simpson published his seminal work, "The Doctrine and Application of Fluxions," where
he presented his method for numerical integration. This method, now known as Simpson's Rule,
approximated the area under a curve by fitting a quadratic function to three points and integrating
it. This marked a significant advancement in the field of numerical analysis, offering improved
accuracy compared to previous techniques.

Understanding the Principles

At its core, Simpson's 1/3 Rule is based on the principle of approximating a function by a quadratic
polynomial within small intervals. The rule states that if we divide the interval of integration into
an even number of subintervals and apply Simpson's formula to each pair of adjacent subintervals,
we can obtain an approximation to the integral with a high degree of accuracy.
Applications in Various Fields

Simpson's 1/3 Rule finds extensive applications across diverse domains due to its versatility and
accuracy. In physics and engineering, it is commonly used to approximate integrals that arise in
the calculation of areas, volumes, and work done. For instance, engineers use Simpson's Rule to
analyze the distribution of stress in mechanical structures or to model the trajectory of projectiles
under the influence of gravity.

In economics and finance, where numerical integration plays a crucial role in modeling complex
systems, Simpson's Rule enables analysts to estimate integrals involved in pricing financial
derivatives, calculating expected values, or simulating economic scenarios. Its ability to provide
accurate results makes it indispensable in decision-making processes.

Moreover, Simpson's Rule is extensively employed in computer science and numerical analysis
for tasks such as numerical quadrature, image processing, and signal processing. Algorithms based
on Simpson's Rule are implemented in software libraries and computational tools, facilitating
efficient and reliable computations in various applications.

While Simpson's 1/3 Rule offers significant advantages in terms of accuracy and efficiency, it is
not without limitations. One of the primary constraints is its requirement for an even number of
subintervals, which may not always be feasible or optimal, especially when dealing with irregular
functions or adaptive integration schemes.

Additionally, Simpson's Rule may encounter difficulties when applied to functions with rapidly
oscillating or highly non-linear behavior. In such cases, the approximation provided by the rule
may deviate significantly from the true value of the integral, necessitating alternative methods or
adaptive strategies to improve accuracy.

Furthermore, the computational complexity of Simpson's Rule increases with the number of
subintervals, leading to higher memory and processing requirements for large-scale problems. This
imposes practical constraints on its applicability in certain scenarios, where computational
resources are limited or scalability is a concern.
Lab Report 12
Objective:
Introduction about Optimization Method.
Optimization Method
optimization methods serve as the guiding compass, navigating through complex landscapes to
reach the most efficient and effective solutions. From enhancing industrial processes to fine-tuning
algorithms and models, optimization techniques play a pivotal role across various domains,
spanning engineering, economics, computer science, and beyond.

At its core, optimization is about finding the best possible solution from a set of feasible
alternatives. This journey often involves minimizing costs, maximizing profits, improving
performance, or achieving any other desired outcome. In this exploration of optimization methods,
we delve into the fundamental principles, diverse approaches, and real-world applications that
underscore this critical discipline.

Optimization encompasses a spectrum of mathematical techniques aimed at solving problems with


multiple constraints and objectives. At its foundation lies the concept of an objective function,
representing the quantity to be maximized or minimized. Constraints, on the other hand, delineate
the boundaries within which solutions must operate.

The journey toward optimization begins with defining the problem clearly, identifying the relevant
variables, constraints, and objectives. This step lays the groundwork for selecting an appropriate
optimization method tailored to the specific problem at hand.

Inspired by the principles of natural selection and genetics, evolutionary algorithms (EAs) simulate
the process of biological evolution to solve optimization problems. Techniques like Genetic
Algorithms (GA), Differential Evolution (DE), and Particle Swarm Optimization (PSO) iteratively
evolve a population of candidate solutions over successive generations, gradually improving
fitness and converging towards optimal or near-optimal solutions.

Evolutionary algorithms excel in tackling complex, multimodal, or poorly understood optimization


problems, making them indispensable in diverse fields ranging from engineering design and
finance to robotics and bioinformatics.
Future Directions:

Despite their efficacy, optimization methods grapple with challenges such as computational
complexity, scalability, and robustness in real-world settings. As problem sizes grow larger and
complexities escalate, there's a growing demand for scalable, parallelizable optimization
algorithms capable of harnessing the power of distributed computing and emerging hardware
architectures.

Furthermore, the integration of optimization with machine learning, uncertainty quantification,


and decision-making under uncertainty opens new avenues for research and innovation.
Techniques like Reinforcement Learning, Bayesian Optimization, and Multi-objective
Optimization promise to push the frontiers of optimization, enabling autonomous systems to adapt,
learn, and optimize in dynamic environments.

Manufacturing:

In the manufacturing sector, optimization methods are employed to optimize production planning,
scheduling, and resource allocation. By optimizing production processes, companies can
maximize throughput, minimize idle time, and reduce production costs. Techniques such as linear
programming, integer programming, and simulation-based optimization help manufacturers
optimize production layouts, machine utilization, and workforce scheduling, leading to improved
productivity and competitiveness.

Finance and Investment:

In finance, optimization methods play a crucial role in portfolio optimization, risk management,
and trading strategies. Portfolio optimization models leverage optimization techniques to allocate
investments across various asset classes to achieve a desired risk-return profile. Optimization
methods help investors diversify their portfolios, minimize risk exposure, and maximize returns,
taking into account factors such as asset correlations, volatility, and investor preferences.
Additionally, optimization algorithms are used in algorithmic trading to execute trades efficiently
and optimize trading strategies in real-time.

You might also like