0% found this document useful (0 votes)
374 views51 pages

Lab Manual-MatLab CSE

Uploaded by

Ajith G J
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)
374 views51 pages

Lab Manual-MatLab CSE

Uploaded by

Ajith G J
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/ 51

lOMoARcPSD|370 367 39

Lab Component
of
Second Semester Engineering Mathematics
as prescribed by Visvesvaraya Technological University, Belagavi

Compiled by:
Dr. Ramananda H. S. Dr. K. Sushan Bairy
St Joseph Engineering College, SOAS, REVA University,
Mangaluru, INDIA. Bengaluru, INDIA.

Dr. Smita S. Nagouda Dr. Madhukar Krishnamurthy


CHRIST(Deemed to be University), BMS College of Engineering,
Central Campus, Bengaluru, INDIA. Bull Temple Road, Bengaluru, INDIA.

Dr. Chandra Shekara G. Mr. Sonam Kumar


BMS College of Engineering, AMC Engineering college,
Bull Temple Road, Bengaluru, INDIA. Bannerghatta Road, Bengaluru, INDIA.
lOMoARcPSD|370 367 39

Message from BOS Chair


Dear Readers,
Welcome to the world of mathematics brought to life through the power of Python!
In your hands, you hold a unique manual that combines the elegance of mathematics
with the versatility of programming. Prepare to embark on a captivating journey where
the realm of numbers, algorithms, and problem-solving converge.
This mathematics lab manual, infused with Python, is your gateway to experiencing
mathematics in a dynamic and interactive way. By integrating programming into the
study of mathematics, we aim to inspire you to explore, experiment, and develop a deep
understanding of mathematical concepts through hands-on coding activities.
Python, a powerful and user-friendly programming language, serves as our trusty com-
panion throughout this manual. It enables us to go beyond pen-and-paper calculations,
unleashing the potential to solve complex problems, visualize mathematical concepts, and
uncover patterns through the magic of coding. As you progress through the chapters,
you will witness how Python becomes a bridge between abstract mathematical ideas and
concrete computational implementations.
Inside these pages, you will embark on a variety of coding adventures that will chal-
lenge your logical thinking, enhance your problem-solving skills, and ignite your creativ-
ity. From building algorithms to solve equations, to simulating mathematical models,
to analyzing data sets, each activity has been carefully crafted to reinforce fundamental
mathematical principles while simultaneously developing your proficiency in Python.
Remember, programming is a skill that grows with practice. Don’t be discouraged
by the occasional hurdle or setback. Embrace the challenges as opportunities to learn,
adapt, and improve. The exercises and examples provided in this manual will guide you
through the intricacies of Python, gradually expanding your knowledge and confidence
as you progress.
We extend our heartfelt appreciation to the authors, educators, and programmers who
have contributed their expertise and passion to create this invaluable resource. Their
dedication ensures that you have in your hands a manual that will equip you with the
skills and knowledge to unravel the mysteries of mathematics using Python.
So, dear readers, let this mathematics lab manual with Python be your guide as you
embark on a thrilling voyage of exploration and discovery. May it inspire you to develop
a deep appreciation for the beauty of mathematics, the artistry of programming, and the
infinite possibilities that arise when these two worlds intertwine.
Take hold of your imagination, harness the power of Python, and delve into the
captivating world of mathematics like never before. Prepare to witness the magic of
algorithms, to unravel the secrets of mathematical patterns, and to develop a lifelong
love for the boundless synergy of mathematics and programming.
Wishing you a remarkable journey filled with mathematical enlightenment and Pythonic
adventures!
I am very much thankful to the authors of this lab manual, Dr. K. Sushan Bairy,
REVA University, Bengaluru, Dr. Ramananda H. S., St Joseph Engineering College,
Mangaluru, Dr. Smita S. Nagouda, Christ(Deemed to be University), Bengaluru, Dr.
Chandra Shekara G., BMS College of Enginering, Bengaluru, Dr. Madhukar Krishna-
murthy, BMS College of Enginering, Bengaluru, Mr. Sonam Kumar, AMC Engineering

1
lOMoARcPSD|370 367 39

College, Bengaluru for their continuous effort to prepare this lab manual.
I am very much thankful to Dr. Vidyashankar S. Vice Chancellor VTU, Dr. Ran-
gaswamy B E, Registrar VTU, Dr. T Srinivasa, Registrar Evaluation VTU, Dr. Sadashive
Gowda, Dean Academic VTU, Dr. Sadashiv Halbhavi, Special officer VTU, All the BOS
members, Basic Science & Humanities for their guidance, support and encouragement for
bringing out this manual.

Dr Suresha M
Chairman Board of Studies in Basic Sciences & Humanities

2
lOMoARcPSD|370 367 39

Instructions and method of evaluation


1. In each Lab student have to show the record of previous Lab.

2. Each Lab will be evaluated for 15 marks and finally average will be taken for 15
marks.

3. Viva questions shall be asked in labs and attendance also can be considered for
everyday Lab evaluation.

4. Tests shall be considered for 5 marks and final Lab assessment is for 20 marks.

5. Student has to score minimum 8 marks out of 20 to pass Lab component.

3
lOMoARcPSD|370 367 39

Contents: Computer Science and Engineering Stream


Lab 1. Programme to compute area, volume and center of gravity.

Lab 2. Evaluation of improper integrals , Beta and Gamma functions.

Lab 3. Finding gradient, divergent, curl and their geometrical interpretation

Lab 4. Computation of basis and dimension for a vector space and graphical representation
of linear transformation

Lab 5. Computing the inner product and orthogonality

Lab 6. Solution of algebraic and transcendental equation by Regula-Falsi and Newton-


Raphson method

Lab 7. Interpolation /Extrapolation using Newton’s forward and backward difference for-
mula
1 rd
Lab 8. Computation of area under the curve using Trapezoidal, Simpson’s and Simp-
3
3 th
sons 8
rule

Lab 9. Solution of ODE of first order and first degree by Taylor’s series and Modified
Euler’s method

Lab 10. Solution of ODE of first order and first degree by Runge-Kutta 4th order method
and Milne’s predictor and corrector method

51
lOMoARcPSD|370 367 39

LAB 1: Programme to compute area, volume and cen-


ter of gravity
1.1 Objectives:
Use python

1. to evaluate double integration.

2. to compute area and volume.

3. to calculate center of gravity of 2D object.

Syntax for the commands used:


1. Data pretty printer in Python:
ppri nt ()

2. integrate:
i nt eg rat e ( functi on ,( vari able , mi n_li mit , max _l i mi t ) )

1.2 Double and triple integration


Example 1:
∫1∫x
Evaluate the integral (x2 + y2)dydx
0 0
from sy mpy i mport *
x , y , z= s y mbol s ( 'x y z ')
w1 = i nt eg rat e ( x ** 2 +y ** 2 ,( y , 0 , x) ,( x , 0 , 1 ) )
pri nt ( w1 )

1/3

Example 2:
∫3 3∫−x 3−∫x−y
Evaluate the integral (xyz)dzdydx
0 0 0
from sy mpy i mport *
x = Sy mbol ( 'x ')
y = Sy mbol ( 'y ')
z= Sy mbol ( 'z ')
w2 = i nt eg rat e (( x* y * z) ,(z , 0 , 3 - x - y) ,( y , 0 , 3 - x) ,( x , 0 , 3 ) )
pri nt ( w2 )

81/80

52
lOMoARcPSD|370 367 39

Example 3:
∫∫ ∫∫
Prove that (x2 + y 2)dydx = (x2 + y2)dxdy
from sy mpy i mport *
x = Sy mbol ( 'x ')
y = Sy mbol ( 'y ')
z= Sy mbol ( 'z ')
w3 = i nt eg rat e ( x ** 2 +y ** 2 , y , x )
ppri nt ( w3 )
w4 = i nt eg rat e ( x ** 2 +y ** 2 , x , y )
ppri nt ( w4 )

1.3 Area and Volume


∫∫
Area of the region R in the cartesian form is dxdy
R

Example 4:

∫a (b/a) ∫ a 2 −x2
Find the area of an ellipse by double integration. A=4 dydx
0 0
from sy mpy i mport *
x = Sy mbol ( 'x ')
y = Sy mbol ( 'y ')
# a= Sym bol ( ' a ')
# b= Sym bol ( ' b ')
a= 4
b= 6
w3 = 4 * i nt eg rat e ( 1 ,( y , 0 ,( b/ a) * sqrt ( a ** 2 - x ** 2 ) ) ,( x , 0 , a) )
pri nt ( w3 )

24.0*pi
∫ ∫
1.4 Area of the region R in the polar form is rdrdθ
R
Example 5:
Find the area of the cardioid r = a(1 + cosθ) by double integration
from sy mpy i mport *
r= Sy mbol ( 'r ')
t = Sy mbol ( 't ')
a= Sy mbol ( 'a ')
# a= 4

w3 = 2 * i nt eg rat e ( r ,( r, 0 , a*( 1 + cos ( t ) ) ) ,( t ,0 , pi ))


ppri nt ( w3 )

53
lOMoARcPSD|370 367 39

∫ ∫∫
1.5 Volume of a solid is given by dxdydz
V
Example 6:
Find the volume of the tetrahedron bounded by the planes x=0,y=0 and z=0, x + y + z = 1
a b c
from sy mpy i mport *
x = Sy mbol ( 'x ')
y = Sy mbol ( 'y ')
z= Sy mbol ( 'z ')
a= Sy mbol ( 'a ')
b= Sy mbol ( 'b ')
c= Sy mbol ( 'c ')
w2 = i nt eg rat e ( 1 ,( z, 0 , c* ( 1 - x / a- y / b) ) ,(y , 0 , b*( 1 - x / a) ) ,( x , 0 , a) )
pri nt ( w2 )

a*b*c/6

1.6 Center of Gravity


Find the center of gravity of cardioid . Plot the graph of cardioid and mark the center
of gravity.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt
i mport mat h
from sy mpy i mport *
r= Sy mbol ( 'r ')
t = Sy mbol ( 't ')
a= Sy mbol ( 'a ')
I1 = i nt egrat e ( cos ( t ) * r ** 2 ,( r , 0 , a* ( 1 + cos ( t ) ) ) ,( t ,- pi , pi ) )
I2 = i nt egrat e ( r ,( r, 0 , a* ( 1 + cos ( t ) ) ) ,( t , - pi , pi ) )
I = I1 / I2
pri nt ( I )
I =I . subs ( a , 5 )
plt . axes ( proj ect i on = ' pol ar ')
a= 5

rad = np . arang e ( 0 , ( 2 * np . pi ) , 0 . 01 )

# plotting the cardioid


for i in rad :
r = a + ( a* np . cos ( i ))
plt . pol ar ( i , r, 'g . ')

plt . pol ar ( 0 , I , 'r. ')


plt . show ()

5*a/6

54
lOMoARcPSD|370 367 39

1.7 Exercise:
∫1∫x
1. Evaluate (x + y)dydx
0 0
Ans: 0.5
lo∫
g(2) ∫x x+l∫og(y)
2. Find the (ex+y+z)dzdydx
0 0 0
Ans: -0.2627
3. Find the area of positive quadrant of the circle x2 + y2 = 16
Ans: 4π

4. Find the volume of the tetrahedron bounded by the planes x=0,y=0 and z=0,
x
+y+z =1
2 3 4
Ans: 4

55
lOMoARcPSD|370 367 39

LAB 2: Evaluation of improper integrals, Beta and


Gamma functions
2.1 Objectives:
Use python
1. to evaluate improper integrals using Beta function.
2. to evaluate improper integrals using Gamma function.

Syntax for the commands used:


1. gamma
mat h . g amma ( x )

Parameters :
x : The number whose gamma value needs to be computed.
2. beta
mat h . bet a ( x , y )

Parameters :
x ,y: The numbers whose beta value needs to be computed.
3. Note: We can evaluate improper integral involving infinity by using inf.

Example 1:
∫∞
Evaluate e−xdx.
0
from sy mpy i mport *
x = sy mbol s ( 'x ')
w1 = i nt eg rat e ( exp (- x ) ,(x , 0 , fl oat ( ' inf ') ) )
pri nt ( s i mpl if y ( w1 ) )

1
∫∞
Gamma function is x(n) = e−xx n−1dx
0

Example 2:
Evaluate Γ(5) by using definition
from sy mpy i mport *
x = sy mbol s ( 'x ')
w1 = i nt eg rat e ( exp (- x ) * x ** 4 ,( x , 0 , fl oat ( ' inf ') ) )
pri nt ( s i mpl if y ( w1 ) )

24

56
lOMoARcPSD|370 367 39

Example 3:
∫∞
Evaluate e−st cos(4t)dt . That is Laplace transform of cos(4t)
0
from sy mpy i mport *
t , s= sy mbol s ( 't , s ')
# for infinity in sympy we use oo
w1 = i nt eg rat e ( exp (- s * t ) * cos ( 4 * t) ,( t , 0 , oo ) )
di s pl ay ( s i mpli f y ( w1 ) )

Example 4:
Find Beta(3,5), Gamma(5)
# beta and gamma functions
from sy mpy i mport beta , g amma
m= i nput ( 'm : ') ;
n= i nput ( 'n : ') ;
m= f l oat ( m) ;
n= f l oat ( n) ;
s = beta ( m , n);
t= gamma ( n)
pri nt ( ' g amma ( ',n , ') is % 3 . 3f '% t )
pri nt ( ' Beta ( ',m , n , ') is % 3 . 3f '% s )

m :3
n :5
gamma ( 5.0 ) is 24.000
Beta ( 3.0 5.0 ) is 0.010

Example 5:
Calculate Beta(5/2,7/2) and Gamma(5/2).
# beta and gamma functions
# If the number is a fraction give it in decimals . Eg 5 / 2 = 2 . 5
from sy mpy i mport beta , g amma
m= f l oat ( i nput ( 'm : ') ) ;
n= f l oat ( i nput ( 'n : ') ) ;

s = beta ( m , n);
t= gamma ( n)
pri nt ( ' g amma ( ',n , ') is % 3 . 3f '% t )
pri nt ( ' Beta ( ',m , n , ') is % 3 . 3f '% s )

57
lOMoARcPSD|370 367 39

m : 2.5
n :3.5
gamma ( 3.5 ) is 3.323
Beta ( 2.5 3.5 ) is 0.037

Example 6:
Verify that Beta(m, n) = Gamma(m)Gamma(n)/Gamma(m + n) for m=5 and n=7
from sy mpy i mport beta , g amma
m= 5 ;
n= 7 ;
m= f l oat ( m) ;
n= f l oat ( n) ;
s = beta ( m , n);
t =( g amma ( m) * g amma ( n) ) / g amma ( m+n) ;
pri nt (s , t )
if ( abs( s- t) <= 0 . 00001 ):
pri nt ( ' bet a and g amma are rel at ed ')
else :
pri nt ( ' gi ven v al ue s are wrong ')

0.000432900432900433 0.000432900432900433
beta and gamma are related

2.2 Exercise:
∫∞
1. Evaluate e−tcos(2t)dt
0
Ans: 1/5
2. Find the value of Beta(5/2,9/2)
Ans: 0.0214

3. Find the value of Gamma(13)


Ans: 479001600

4. Verify that Beta(m, n) = Gamma(m)Gamma(n)/Gamma(m + n) for m=7/2 and


n=11/2
Ans: True

58
lOMoARcPSD|370 367 39

LAB 3: Finding gradient, divergent, curl and their


geometrical interpretation
1.1 Objectives:
Use python

1. to find the gradient of a given scalar function.

2. to find find divergence and curl of a vector function.

1.2 Method I:
To find gradient of ϕ = x2y + 2xz − 4.
# To find gradient of scalar point function .
from sy mpy . vect or i mport *
from sy mpy i mport sy mbol s
N= Coor d Sy s 3 D ( 'N ') # Sett in g the c o or d in a te s yste m
x , y , z= s y mbol s ( 'x y z ')
A= N. x ** 2 * N. y+ 2 * N. x * N. z - 4 # Var ia bl e s x , y , z to be used with co or d in at e
system N
del op = Del () # Del op er at or
di s pl ay ( del op ( A) ) # Del op er at or a pp li ed to A
g rad A = g radie nt ( A) # Grad ie n t fu nc ti on is used
pri nt ( f " \ n Gradi ent of { A} is \ n" )
di s pl ay ( grad A )

To find divergence of F⃗ = x2 yz î + y 2 zxĵ + z 2 xyk̂


# To find divergence of a vector point function
from sy mpy . vect or i mport *
from sy mpy i mport sy mbol s
N= Coor d Sy s 3 D ( 'N ')
x , y , z= s y mbol s ( 'x y z ')
A= N. x ** 2 * N. y* N. z* N. i +N. y ** 2 * N. z * N. x * N. j+N. z ** 2 * N. x * N. y* N. k
del op = Del ()
div A = del op . dot ( A)
di s pl ay ( divA )

pri nt ( f " \ n Div erg ence of { A} is \ n" )


di s pl ay ( div e rg ence ( A) )

59
lOMoARcPSD|370 367 39

To find curl of F⃗ = x2 yz î + y 2 zxĵ + z 2 xyk̂


# To find curl of a vector point function
from sy mpy . vect or i mport *
from sy mpy i mport sy mbol s
N= Coor d Sy s 3 D ( 'N ')
x , y , z= s y mbol s ( 'x y z ')
A= N. x ** 2 * N. y* N. z* N. i +N. y ** 2 * N. z * N. x * N. j+N. z ** 2 * N. x * N. y* N. k
del op = Del ()
curl A = del op . cross ( A)
di s pl ay ( curl A )

pri nt ( f " \ n Curl of { A} is \ n" )


di s pl ay ( curl ( A) )

1.3 Method II:


To find gradient of ϕ = x2yz.
# To find gradient of a scalar point function x^ 2yz
from sy mpy . phys ics . vect or i mport *
from sy mpy i mport var , ppri nt
var('x,y, z')
v = R eference Frame ( 'v ')
F=v[ 0 ] ** 2 * v[ 1 ]* v[ 2 ]
G = gradi ent ( F , v )
F= F. subs( [( v[ 0 ],x ) ,( v[ 1 ],y) ,( v[ 2 ],z) ])
pri nt ( " Given scal ar f uncti on F=" )
di s pl ay ( F)
G =G . subs ( [ ( v[ 0 ] , x ) ,( v [ 1 ] , y) ,( v [ 2 ] , z) ] )
pri nt ( " \ n G radient of F=" )
di s pl ay ( G )

60
lOMoARcPSD|370 367 39

To find divergence of F⃗ = x2 y î + yz 2ĵ + x2 zk̂.


# To find divergence of F=x^ 2yi+yz^ 2j+x^ 2zk
from sy mpy . phys ics . vect or i mport *
from sy mpy i mport var
var('x,y, z')
v = R eference Frame ( 'v ')
F=v[ 0 ] ** 2 * v[ 1 ]* v. x+ v[ 1 ]* v[ 2 ] ** 2 * v. y+ v[ 0 ] ** 2 * v[ 2 ]* v. z
G = div erg ence ( F , v )
F= F. subs( [( v[ 0 ],x ) ,( v[ 1 ],y) ,( v[ 2 ],z) ])
pri nt ( " Given vect or poi nt f unct i on is ")
di s pl ay ( F)

G =G . subs ( [ ( v[ 0 ] , x ) ,( v [ 1 ] , y) ,( v [ 2 ] , z) ] )
pri nt ( " Di vergence of F=" )
di s pl ay ( G )

To find curl of F⃗ = xy 2 î + 2x2 yz ĵ − 3yz 2 k̂


# To find curl of F=xy^ 2i+ 2x^ 2yzj - 3yz^ 2k
from sy mpy . phys ics . vect or i mport *
from sy mpy i mport var
v a r ('x ,y, z')
v = R eference Frame ( 'v ')
F=v[ 0 ]* v[ 1 ] ** 2 * v. x+ 2 * v[ 0 ] ** 2 * v[ 1 ]* v[ 2 ]* v. y- 3 * v[ 1 ]* v[ 2 ] ** 2 * v. z
G = curl ( F , v )
F= F. s ubs ([ ( v[ 0 ] ,x) ,( v[ 1 ],y) ,( v[ 2 ] ,z )] )
pri nt ( " Given vect or poi nt f unct i on is ")
di s pl ay ( F)

G =G . subs ( [ ( v[ 0 ] , x ) ,( v [ 1 ] , y) ,( v [ 2 ] , z) ] )
pri nt ( " curl of F=" )
di s pl ay ( G )

61
lOMoARcPSD|370 367 39

1.4 Exercise:
1. If u = x + y + z, v = x2 + y2 + z2, w = yz + zx + xy, find gradu, gradv and gradw.
Ans: î + ĵ + k̂, 2(xî + y ĵ + zk̂), (y + z)î + (z + x)ĵ + (z + x)k̂.

2. Evaluate divF and curlF at the point (1,2,3), given that F⃗ = x2 yz î+xy 2 zĵ
+xyz 2 k̂. Ans: 6xyz, x(z 2 − y 2 )î + y(x2 − z 2 )ĵ + z(y 2 − x2 )k̂.

3. Prove that the vector (yz − x2 )î + (4y − z 2 x)ĵ + (2xz − 4z)k̂ is solenoidal.

4. Find the vector normal to the surface xy3z2 = 4 at the point (−1, −1, 2).
Ans: −4î − 12ĵ + 4k̂.
⃗ = xî + yĵ + zk̂, show that (i) ∇ · R
5. If R ⃗ = 3, (ii) ∇ × R
⃗ = 0.

62
lOMoARcPSD|370 367 39

LAB 4: Computation of basis and dimension for a vec-


tor space and graphical representation of linear trans-
formation
4.1 Objectives:
Use python

1. to verify the Rank nullity theorem of given linear transformation

2. to compute the dimension of vector space

3. to represent linear transformations graphically

4.2 Rank Nullity Theorem


Verify the rank-nullity theorem for the linear transformation T : R3 → R3 defined by
T (x, y, z) = (x + 4y + 7z, 2x + 5y + 8z, 3x + 6y + 9z).
i mport numpy as np
from sci py . li nal g i mport nul l _s pace

# Define a linear t rans for mati on interms of matrix


A = np . array ( [[ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] )

# Find the rank of the matrix A


rank = np . l i nal g . mat ri x _rank ( A)
pri nt ( " Rank of the mat rix " , rank )

# Find the null space of the matrix A


ns = nul l _s pace ( A)
pri nt ( " Null s pace of the mat rix " , ns )
# Find the dimension of the null space
nul l i ty = ns . s hape [ 1 ]
pri nt ( " Null s pace of the mat rix " , nul li ty )
# Verify the rank - nullity theorem
if rank + nul li t y == A. s hape [ 1 ] :
pri nt ( " Rank - null it y t heorem hol ds . " )
else :
pri nt ( " Rank - null it y t heorem does not hold . " )

Rank of the matrix 2


Null space of the matrix [[-0.40824829]
[ 0.81649658]
[-0.40824829]]
Null space of the matrix 1
Rank-nullity theorem holds.

63
lOMoARcPSD|370 367 39

4.3 Dimension of Vector Space


Find the dimension of subspace spanned by the vectors (1, 2, 3), (2, 3, 1) and (3, 1, 2).
i mport numpy as np

# Define the vector space V


V = np . array ( [
[1 , 2 , 3 ],
[2 , 3 , 1 ],
[3 , 1 , 2 ]])
# Find the dimension and basis of V
bas i s = np . l i nal g . mat ri x _rank ( V )
di mens i on = V . s hape [ 0 ]
pri nt ( " Bas is of the matri x " , basis )
pri nt ( " Di mensi on of the matri x " , di mens ion )

Basis of the matrix 3


Dimension of the matrix 3

Extract the linearly independent rows in given matrix : Basis of Row space
from numpy i mport *
i mport sy mpy as sp
A=[ [ 1 , - 1 , 1 , 1 ] ,[ 2 , - 5 , 2 , 2 ] , [ 3 ,- 3 , 5 , 3 ] ,[ 4 ,- 4 , 4 , 4 ] ]
AB= array( A)
S= shape ( A)
n= len ( A)
for i in rang e ( n) :
if AB[ i , i ] == 0 :
ab= copy( AB)
for k in range ( i+1 , S[ 0 ]) :
if ab [ k , i ] ! = 0 :
ab [ i , : ] = AB[ k ,: ]
ab [ k , : ] = AB[ i ,: ]
AB= copy( ab)
for j in range ( i+1 , n) :
Fact = AB [ j , i ] / AB[ i , i]
for k in range ( i , n) :
AB [ j , k ] = AB [ j , k ]- Fact * AB[ i , k ]
di s pl ay ( " REF of given matrix : " , sp . Mat ri x ( AB ) )
temp = { ( 0 , 0 , 0 , 0 )}
res ul t = [ ]
for idx , row in enumerat e ( map ( tuple , AB) ) :
if row not in temp :
res ul t . append ( idx )
pri nt ( " \ n Bas is are non - zero rows of A: " )
di s pl ay ( sp . Mat ri x ( AB [ res ul t ] ))

64
lOMoARcPSD|370 367 39

4.4 Graphical representation of a transformation


4.4.1 Horizontal stretch:
Represent the horizontal stretch transformation T : R2ßR2 geometrically
Find the image of vector (10, 0) when it is stretched horizontally by 2 units.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt
V = np . array ( [[ 10 , 0 ]] )
origi n = np . array ( [[ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ]) # origi n p oin t
A= np . mat rix ( [[ 2 , 0 ] ,[ 0 , 1 ]] )
V1 = np . mat rix ( V )
V2 = A* np . t rans pos e ( V1 )
V2 = np . array ( V2 )
plt . qui v er ( * origin , V [: , 0 ] , V[ : , 1 ] , color =[ 'b '] , s c al e = 50 )
plt . qui v er ( * origin , V2 [ 0 , :] , V2 [ 1 ,: ] , col or =[ 'r '] , scale = 50 )
plt . show ()

Another example.
from mat h i mport pi , sin , cos

65
lOMoARcPSD|370 367 39

i mport mat pl ot l i b . py pl ot as plt


i mport numpy as np

coords = np . array ( [[ 0 , 0 ] , [ 0 . 5 , 0 . 5 ] ,[ 0 . 5 , 1 . 5 ] ,[ 0 , 1 ] ,[ 0 , 0 ] ] )
coords = coords . trans pos e ()
coords
x = coords[0 ,:]
y = coords[1 ,:]

A = np . array ( [[ 2 , 0 ] ,[ 0 , 1 ] ] )
A_coords = A@ coords
x_LT1 = A_ coor ds[ 0 ,:]
y_LT1 = A_ coords[ 1 ,:]

# Create the figure and axes objects


fig , ax = plt . s ubpl ot s ()

# Plot the points. x and y are original vectors , x_LT1 and y_LT1 are
images
ax . plot ( x , y , ' ro ')
ax . plot ( x_LT1 , y_LT1 , ' bo ')

# Connect the points by lines


ax . plot ( x , y , 'r ', ls =" -- " )
ax . plot ( x_LT1 , y_LT1 , 'b ')

# Edit some settings


ax . ax vl i ne ( x=0 , col or =" k " , ls =" : " )
ax . ax hl i ne ( y=0 , col or =" k" , ls =" : " )
ax . grid ( True )
ax . axis ( [ - 2 , 2 , - 1 , 2 ] )
ax . set_as pec t ( ' equal ')
ax . s et _t it l e (" H ori zont al Stret c h " ) ;

66
lOMoARcPSD|370 367 39

4.4.2 Reflection:

Represent the reflection transformation T : R2 → R2 geometrically.


Find the image of vector (10, 0) when it is reflected about y axis.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt
V = np . array ( [[ 10 , 0 ]] )
origi n = np . array ( [[ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ]) # origi n p oin t
A= np . mat rix ( [ [- 1 , 0 ] ,[ 0 , 1 ] ] )
V1 = np . mat rix ( V )
V2 = A* np . t rans pos e ( V1 )
V2 = np . array ( V2 )
plt . qui v er ( * origin , V [: , 0 ] , V[ : , 1 ] , color =[ 'b '] , s c al e = 50 )
plt . qui v er ( * origin , V2 [ 0 , :] , V2 [ 1 ,: ] , col or =[ 'r '] , scale = 50 )
plt . show ()

Another example.
B = np . array ( [ [- 1 , 0 ] ,[ 0 , 1 ] ] )
B_coords = B@ coords

x_LT2 = B_coords [0 ,:]


y_LT2 = B_ coords [1 ,:]

# Create the figure and axes objects


fig , ax = plt . s ubpl ot s ()

# Plot the points. x and y are original vectors , x_LT1 and y_LT1 are
images
ax . plot ( x , y , ' ro ')
ax . plot ( x_LT2 , y_LT2 , ' bo ')

# Connect the points by lines


ax . plot ( x , y , 'r ', ls =" -- " )
ax . plot ( x_LT2 , y_LT2 , 'b ')

# Edit some settings


ax . ax vl i ne ( x=0 , col or =" k " , ls =" : " )

67
lOMoARcPSD|370 367 39

ax . ax hl i ne ( y=0 , col or =" k" , ls =" : " )


ax . grid ( True )
ax . axis ( [ - 2 , 2 , - 1 , 2 ] )
ax . set_as pec t ( ' equal ')
ax . s et _t it l e (" Refl ect i on " ) ;

4.4.3 Rotation:

Represent the rotation transformation T : R2 → R2 geometrically.


Find the image of vector (10, 0) when it is rotated by π/2 radians.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt
V = np . array ( [[ 10 , 0 ]] )
origi n = np . array ( [[ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ]) # origi n p oin t
A= np . mat rix ( [[ 0 ,- 1 ] ,[ 1 , 1 ] ] )
V1 = np . mat rix ( V )
V2 = A* np . t rans pos e ( V1 )
V2 = np . array ( V2 )
plt . qui v er ( * origin , V [: , 0 ] , V[ : , 1 ] , color =[ 'b '] , s c al e = 50 )
plt . qui v er ( * origin , V2 [ 0 , :] , V2 [ 1 ,: ] , col or =[ 'r '] , scale = 50 )
plt . show ()

68
lOMoARcPSD|370 367 39

Another example.
t het a = pi / 6
R = np . array ( [[ cos ( t het a ) , - sin ( t het a ) ] ,[ sin ( t het a ) , cos ( t het a ) ] ] )
R_coords = R@ coords

x_LT3 = R_ coords [0 ,:]


y_LT3 = R_ coords [1 ,:]

# Create the figure and axes objects


fig , ax = plt . s ubpl ot s ()

# Plot the points. x and y are original vectors , x_LT1 and y_LT1 are
images
ax . plot ( x , y , ' ro ')
ax . plot ( x_LT3 , y_LT3 , ' bo ')

# Connect the points by lines


ax . plot ( x , y , 'r ', ls =" -- " )
ax . plot ( x_LT3 , y_LT3 , 'b ')

# Edit some settings


ax . ax vl i ne ( x=0 , col or =" k " , ls =" : " )
ax . ax hl i ne ( y=0 , col or =" k" , ls =" : " )
ax . grid ( True )
ax . axis ( [ - 2 , 2 , - 1 , 2 ] )
ax . set_as pec t ( ' equal ')

69
lOMoARcPSD|370 367 39

4.4.4 Shear Transformation

Represent the Shear transformation T : R2 → R2 geometrically.


Find the image of (2, 3) under shear transformation.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt
V = np . array ( [[ 2 , 3 ]] )
origi n = np . array ( [[ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ]) # origi n p oin t
A= np . mat rix ( [[ 1 , 2 ] ,[ 0 , 1 ]] )
V1 = np . mat rix ( V )
V2 = A* np . t rans pos e ( V1 )
V2 = np . array ( V2 )
pri nt ( " I mage of gi ven v ect ors is : " , V2 )
plt . qui v er ( * origin , V [: , 0 ] , V[ : , 1 ] , color =[ 'b '] , s c al e = 20 )
plt . qui v er ( * origin , V2 [ 0 , :] , V2 [ 1 ,: ] , col or =[ 'r '] , scale = 20 )
plt . show ()

70
lOMoARcPSD|370 367 39

Another example.
S = np . array ( [[ 1 , 2 ] ,[ 0 , 1 ] ] )
S_coords = S@ coords

x_LT4 = S_ coords [0 ,:]


y_LT4 = S_ coords [1 ,:]

# Create the figure and axes objects


fig , ax = plt . s ubpl ot s ()

# Plot the points. x and y are original vectors , x_LT1 and y_LT1 are
images
ax . plot ( x , y , ' ro ')
ax . plot ( x_LT4 , y_LT4 , ' bo ')

# Connect the points by lines


ax . plot ( x , y , 'r ', ls =" -- " )
ax . plot ( x_LT4 , y_LT4 , 'b ')

# Edit some settings


ax . ax vl i ne ( x=0 , col or =" k " , ls =" : " )
ax . ax hl i ne ( y=0 , col or =" k" , ls =" : " )
ax . grid ( True )
ax . axis ( [ - 2 , 4 , - 1 , 2 ] )
ax . set_as pec t ( ' equal ')
ax . s et _t it l e (" Shear " ) ;

71
lOMoARcPSD|370 367 39

4.4.5 Composition
Represent the composition of two 2D transformations.
Find the image of vector (10, 0) when it is rotated by π/2 radians then stretched hori-
zontally 2 units.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt
V = np . array ( [[ 2 , 3 ]] )
origi n = np . array ( [[ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ]) # origi n p oin t
A= np . mat rix ( [[ 0 ,- 1 ] ,[ 1 , 0 ] ] )
B= np . mat rix ( [[ 2 , 0 ] ,[ 0 , 1 ] ])
V1 = np . mat rix ( V )
V2 = A* np . t rans pos e ( V1 )
V3 =B * V2
V2 = np . array ( V2 )
V3 = np . array ( V3 )
pri nt ( " I mage of gi ven v ect ors is : " , V3 )
plt . qui v er ( * origin , V [: , 0 ] , V[ : , 1 ] , color =[ 'b '] , s c al e = 20 )
plt . qui v er ( * origin , V2 [ 0 , :] , V2 [ 1 ,: ] , col or =[ 'r '] , scale = 20 )
plt . qui v er ( * origin , V3 [ 0 , :] , V3 [ 1 ,: ] , col or =[ 'g '] , scale = 20 )
plt . t itl e ( ' Blue = original , Red = R ot at ed , Green = R ot at e d + St reached ')
plt . show ()

72
lOMoARcPSD|370 367 39

Another example.
C = np . array ( [ [- cos ( t het a ) , sin ( t het a ) ] ,[ sin ( t het a ) , cos ( t het a ) ] ] )
C_coords = C@ coords

x_LT5 = C_ coords [0 ,:]


y_LT5 = C _coords [1 ,:]

# Create the figure and axes objects


fig , ax = plt . s ubpl ot s ()

# Plot the points. x and y are original vectors , x_LT1 and y_LT1 are
images
ax . plot ( x , y , ' ro ')
ax . plot ( x_LT5 , y_LT5 , ' bo ')

# Connect the points by lines


ax . plot ( x , y , 'r ', ls =" -- " )
ax . plot ( x_LT5 , y_LT5 , 'b ')

# Edit some settings


ax . ax vl i ne ( x=0 , col or =" k " , ls =" : " )
ax . ax hl i ne ( y=0 , col or =" k" , ls =" : " )
ax . grid ( True )
ax . axis ( [ - 2 , 2 , - 1 , 2 ] )
ax . set_as pec t ( ' equal ')

73
lOMoARcPSD|370 367 39

4.5 Exercise:
1. Verify the rank nullity theorem for the following linear transformation

a) T : R2 → R3 defined by T (x, y) = (x + 4y, 2x + 5y, 3x + 6y).


Ans: Rank=2, Nullity=1, RNT verified
b) T : R3 → R4 defined by T (x, y, z) = (x+4y−z, 2x+5y+8z, 3x+y+2z, x+y+z).
Ans: Rank=3, Nullity=1, RNT verified

2. Find the dimension of the subspace spanned following set of vectors

a) S = (1, 2, 3, 4), (2, 4, 6, 8), (1, 1, 1, 1)


Ans: Dimension of subspace is 2
b) S = (1, −1, 3, 4), (2, 1, 6, 8), (1, 1, 1, 1), (3, 3, 3, 3)
Ans: Dimension of subspace is 3

3. Find the image of (1, 3) under following 2D transformations

a) Horizontal stretch
b) Reflection
c) Shear
d) Rotation

74
lOMoARcPSD|370 367 39

LAB 5: Computing the inner product and orthogo-


nality
5.1 Objectives:
Use python

1. to compute the inner product of two vectors.

2. to check whether the given vectors are orthogonal.

5.2 Inner Product of two vectors


Find the inner product of the vectors (2, 1, 5, 4) and (3, 4, 7, 8).
i mport numpy as np

# initialize arrays
A = np . array ([ 2 , 1 , 5 , 4 ] )
B = np . array ([ 3 , 4 , 7 , 8 ] )

# dot product
out put = np . dot ( A , B)

pri nt ( out put )

77

5.3 Checking orthogonality


Verify whether the following vectors (2, 1, 5, 4) and (3, 4, 7, 8) are orthogonal.
i mport numpy as np

# initialize arrays
A = np . array ([ 2 , 1 , 5 , 4 ] )
B = np . array ([ 3 , 4 , 7 , 8 ] )

# dot product
out put = np . dot ( A , B)
pri nt ( ' I nner product is : ', out put )
if output == 0 :
pri nt ( ' given vectors are ort hog nal ')
else :
pri nt ( ' gi ven vectors are not ort hog nal ')

Inner product is : 77
given vectors are not orthognal

75
lOMoARcPSD|370 367 39

5.4 Exercise:
1. Find the inner product of (1, 2, 3) and (3, 4, 5).
Ans: 26

2. Find the inner product of (1, −1, 2, 1) and (4, 2, 1, 0).


Ans: 4

3. Check whether the following vectors are orthogonal or not

a) (1, 1, −1) and (2, 3, 5). Ans: True


b) (1, 0, 2, 0) and (4, 2, −2, 5). Ans: True
c) (1, 2, 3, 4) and (2, 3, 4, 5) . Ans: False

76
lOMoARcPSD|370 367 39

LAB 6: Solution of algebraic and transcendental equa-


tion by Regula-Falsi and Newton-Raphson method
6.1 Objectives:
Use python

1. to solve algebraic and transcendental equation by Regula-Falsi method.

2. to solve algebraic and transcendental equation by Newton-Raphson method.

6.2 Regula-Falsi method to solve a transcendental equation


Obtain a root of the equation x3 − 2x − 5 = 0 between 2 and 3 by regula-falsi method.
Perform 5 iterations.
# Regula Falsi method
from sy mpy i mport *
x = Sy mbol ( 'x ')
g = i nput ( ' E nter the f uncti on ') # % x^3 - 2 * x- 5 ; % function
f = l ambdi f y ( x , g )
a= f l oat ( i nput ( ' E nter a v al us : ') ) # 2
b= f l oat ( i nput ( ' E nter b v al us : ') ) # 3
N= i nt ( i nput ( ' E nter number of i t erat i ons : ')) # 5

for i in rang e ( 1 , N+ 1 ) :
c=( a* f( b)- b* f( a ))/( f( b)- f( a))
if(( f( a)* f( c) < 0 )):
b=c
else :
a=c
pri nt ( ' it rati on % d \ t the root % 0 . 3f \ t f unc ti on v al ue % 0 . 3f \ n '%
(i,c, f( c)));

Using tolerance value we can write the same program as follows:


Obtain a root of the equation x3 − 2x − 5 = 0 between 2 and 3 by regula-falsi method.
Correct to 3 decimal places.

77
lOMoARcPSD|370 367 39

# Regula Falsi method while loop2


from sy mpy i mport *
x = Sy mbol ( 'x ')
g = i nput ( ' E nter the f uncti on ') # % x^3 - 2 * x- 5 ; % function
f = l ambdi f y ( x , g )
a= f l oat ( i nput ( ' E nter a v al us : ') ) # 2
b= f l oat ( i nput ( ' E nter b v al us : ')) # 3
N= f l oat ( i nput ( ' E nter t ol arence : ') ) # 0 . 001
x=a;
c=b;
i=0
whil e ( abs ( x - c) >=N) :
x=c
c=(( a* f( b)- b* f( a ))/( f( b)- f( a )));
if(( f( a)* f( c) < 0 )):
b=c
else :
a=c
i =i + 1
pri nt ( ' it rati on % d \ t the root % 0 . 3f \ t f unc ti on v al ue % 0 . 3f \ n '%
(i, c, f( c)));
pri nt ( ' fi nal v al ue of the root is % 0 . 5f '% c)

6.3 Newton-Raphson method to solve a transcendental equa-


tion
Find a root of the equation 3x = cos x+ 1, near 1, by Newton Raphson method. Perform
5 iterations
from sy mpy i mport *
x = Sy mbol ( 'x ')
g = i nput ( ' E nter the f uncti on ') # % 3x - cos( x)- 1 ; % function
f = l ambdi f y ( x , g )
dg = diff ( g ) ;

78
lOMoARcPSD|370 367 39

df = l ambdi f y (x , dg )
x0 = fl oat ( i nput ( ' E nter the i nt i al appr o x i mat i on ') ) ; # x0 = 1
n= int ( i nput ( ' E nter the number of i t erat i ons ') ) ; #n=5;
for i in rang e ( 1 , n+ 1 ) :
x1 =( x0 - ( f( x0 )/ df( x0 )))
pri nt ( ' it rati on % d \ t the root % 0 . 3f \ t f unc ti on v al ue % 0 . 3f \ n '%
(i, x1 , f( x1 ))); # print all
iteration value
x0 = x1

6.4 Exercise:
1. Find a root of the equation 3x = cos x+1, between 0 and 1, by Regula-falsi method.
Perform 5 iterations.
Ans: 0.607

2. Find a root of the equation xex = 2, between 0 and 1, by Regula-falsi method.


Correct to 3 decimal places.
Ans: 0.853

3. Obtain a real positive root of x4 − x = 0, near 1, by Newton-Raphson method.


Perform 4 iterations.
Ans: 1.856

4. Obtain a real positive root of x4 +x 3 − 7x2 − x+ 5 = 0, near 3, by Newton-Raphson


method. Perform 7 iterations.
Ans: 2.061

79
lOMoARcPSD|370 367 39

LAB 7: Interpolation /Extrapolation using Newton’s


forward and backward difference formula
7.1 Objectives:
Use python
1. to interpolate using Newton’s Forward interpolation method.

2. to interpolate using Newton’s backward interpolation method.

3. to extrapolate using Newton’s backward interpolation method.


1. Use Newtons forward interpolation to obtain the interpolating polynomial and hence
x: 1 3 5 7 9
calculate y(2) for the following:
y: 6 10 62 210 502
from sy mpy i mport *
i mport numpy as np
n = int ( i nput ( ' E nter number of data point s : ') )
210
x = np . zeros (( n) )
y = np . zeros (( n , n) )

# Reading data points


pri nt ( ' E nter dat a for x and y : ')
for i in rang e ( n) :
x [ i] = f l oat ( i nput ( 'x [ '+ str ( i ) + ']= '))
y [ i ][ 0 ] = f l oat ( i nput ( 'y [ '+ str ( i ) + ']= ') )

# Generating forward difference table


for i in rang e ( 1 , n) :
for j in range ( 0 , n- i ):
y [ j ][ i ] = y [ j + 1 ] [ i- 1 ] - y [ j ] [ i - 1 ]

pri nt ( '\ n FO R WAR D DI FFE R E NCE T ABL E \ n ') ;

for i in rang e ( 0 , n) :
pri nt ( '% 0 . 2f ' %( x [ i ]) , end = '')
for j in range ( 0 , n- i ):
pri nt ( '\ t \ t % 0 . 2f ' %( y[ i ] [ j ] ) , end = '')
pri nt ()
# obtaining the polynomial
t = sy mbol s ( 't ')
f=[] # f is a list type data

p=( t- x[ 0 ])/( x[ 1 ]- x[ 0 ])
f. append ( p)
for i in rang e ( 1 , n- 1 ) :
f . append ( f [ i - 1 ] *( p- i ) /( i+ 1 ) )
poly =y [ 0 ] [ 0 ]
for i in rang e ( n- 1 ):
poly = poly +y [ 0 ] [ i+ 1 ] * f [ i ]

80
lOMoARcPSD|370 367 39

s i mp_pol y = s i mpl if y ( poly )


pri nt ( '\ nTHE I NT ER PO L AT I NG PO L Y NO MI AL IS \ n ') ;
ppri nt ( si mp_ pol y )
# if you want to interpolate at some point the next session will help
i nter = i nput ( ' Do you want to i nt erpol at e at a poi nt ( y / n) ? ') # y
if i nter == 'y ':
a= f l oat ( i nput ( ' enter the poi nt ') ) # 2
i nt erpol = l ambdi f y (t , si mp_pol y )
res ul t = i nterpol ( a)
pri nt ( '\ nT he v al ue of the f unct i on at ' ,a , ' is \ n ', resul t ) ;

2. Use Newtons backward interpolation to obtain the interpolating polynomial and


x: 1 3 5 7 9
hence calculate y(8) for the following data:
y: 6 10 62 210 502
from sy mpy i mport *
i mport numpy as np
i mport sys
pri nt ( " This will use Newt on 's backword i nt epol at i on f ormul a " )
# Reading number of unknowns
n = int ( i nput ( ' E nter number of data point s : ') )

# Making numpy array of n & n x n size and ini tia lizi ng


# to zero for storing x and y value along with di ffe renc es of y
x = np . zeros (( n) )
y = np . zeros (( n , n) )

# Reading data points

81
lOMoARcPSD|370 367 39

pri nt ( ' E nter dat a for x and y : ')


for i in rang e ( n) :
x [ i] = f l oat ( i nput ( 'x [ '+ str ( i ) + ']= '))
y [ i ][ 0 ] = f l oat ( i nput ( 'y [ '+ str ( i ) + ']= ') )

# Generating backward difference table


for i in rang e ( 1 , n) :
for j in range ( n- 1 , i- 2 ,- 1 ) :
y[ j][ i] = y[ j][ i- 1 ] - y[ j- 1 ][ i- 1 ]

pri nt ( '\ n BACKWAR D DI FFE R E NCE T ABLE \ n ') ;

for i in rang e ( 0 , n) :
pri nt ( '% 0 . 2f ' %( x [ i ]) , end = '')
for j in range ( 0 , i + 1 ) :
pri nt ( '\ t % 0 . 2f ' %( y [ i ][ j ] ) , end = '')
pri nt ()

# obtaining the polynomial


t = sy mbols ( 't ')
f=[]

p=( t- x[ n- 1 ]) /( x[ 1 ]- x[ 0 ])
f. append ( p)
for i in rang e ( 1 , n- 1 ) :
f . append ( f [ i - 1 ] *( p+i ) /( i + 1 ))

poly =y [ n- 1 ][ 0 ]
pri nt ( poly )
for i in rang e ( n- 1 ):
poly = poly +y [ n- 1 ] [ i + 1 ] * f [ i]
s i mp_ pol y = s i mpl if y ( poly )
pri nt ( '\ nTHE I NT ER PO L AT I NG PO L Y NO MI AL IS \ n ') ;
ppri nt ( si mp_ pol y )
# if you want to interpolate at some point the next session will help
i nter = i nput ( ' Do you want to i nt erpol at e at a poi nt ( y / n) ? ')
if i nter == 'y ':
a= f l oat ( i nput ( ' enter the poi nt ') )
i nt erpol = l ambdi f y (t , si mp_pol y )
res ul t = i nterpol ( a)
pri nt ( '\ nT he v al ue of the f unct i on at ' ,a , ' is \ n ', resul t ) ;

82
lOMoARcPSD|370 367 39

7.2 Exercise:
1. Obtain the interpolating polynomial for the following data
x: 0 1 2 3
y: 1 2 1 10
Ans: 2x3 − 7x2 + 6x + 1
2. Find the number of men getting wage Rs. 100 from the following table:
wage: 50 150 250 350
No. of men: 9 30 35 42
Ans: 23 men

3. Using Newton’s backward interpolation method obtain y(160) for the following data
x : 100 150 200 250 300
y : 10 13 15 17 18
Ans: 13.42

4. Using Newtons forward interpolation polynomial and calculate y(1) and y(10).
x: 3 4 5 6 7 8 9
y : 4.8 8.4 14.5 23.6 36.2 52.8 73.9
Ans: 3.1 and 100

83
lOMoARcPSD|370 367 39

LAB 8: Computation of area under the curve using


rd th
Trapezoidal, Simpson’s 13 and Simpsons 38 rule
8.1 Objectives:
Use python

1. to find area under the curve represented by a given function using Trapezoidal rule.
1 rd
2. to find area under the curve represented by a given function using Simpson’s 3
rule.
3 th
3. to find area under the curve represented by a given function using Simpson’s 8
rule.

4. to find the area below the curve when discrete points on the curve are given.

8.2 Trapezoidal Rule


∫5 1
Evaluate 1+x 2
.
0
# Definition of the function to integra te
def my _f unc ( x ) :
return 1 / ( 1 + x ** 2 )

# Function to implement trapezoidal method


def t rapezoi d al ( x0 , xn , n):
h = ( xn - x0 ) / n # Calculating step
size
# Finding sum
i nt eg rat i on = my _f unc ( x0 ) + my _f unc ( xn ) # Adding first and
last terms
for i in range ( 1 , n) :
k = x0 + i * h # i- th step value
i nt eg rat i on = i nt eg rat i on + 2 * my_f unc ( k ) # Add in g a rea s of the
trapezoids
# Proportioning sum of trapezoid areas
i nt eg rat i on = i nt eg rat i on * h / 2
ret urn i nt eg rat i on

# Input section
l ow er_l i mi t = fl oat ( i nput ( " E nt er l ower li mi t of i nt eg rat i on : " ) )
up per_l i mi t = fl oat ( i nput (" E nt er upper li mi t of i nt eg rat i on : " ) )
s ub_i nt erv al = int ( i nput ( " E nter number of sub i nt erv als : " ) )

# Call trapezoidal () method and get result


res ul t = t rapezoi dal ( l ower_li mit , upper_li mi t , s ub_ i nt erv al )

# Print result
pri nt ( " I nt egrat i on res ul t by Trapezoi d a l met hod is : " , res ul t )

84
lOMoARcPSD|370 367 39

1 rd
8.3 Simpson’s 3
Rule
∫5 1
Evaluate 1+x 2
.
0
# Definition of the function to integra te
def my _f unc ( x ) :
return 1 / ( 1 + x ** 2 )

# F un ct io n to im pl em en t the Si mp so n ' s one - th ir d rule

def s i mps on 13 ( x0 , xn , n) :
h = ( xn - x0 ) / n # ca lcu lati ng step size
# Finding sum
i nt eg rat i on = ( my _f unc ( x0 ) + my _f unc ( xn) )
k = x0
for i in range ( 1 , n) :
if i % 2 = = 0 :
i nt eg rat i on = i nt eg rat i on + 4 * my_ f unc ( k )
else :
i nt eg rat i on = i nt eg rat i on + 2 * my_ f unc ( k )
k += h
# Finding final integration value
i nt eg rat i on = i nt eg rat i on * h * ( 1 / 3 )
ret urn i nt eg rat i on

# Input section
l ow er_l i mi t = fl oat ( i nput ( " E nte r l ower li mi t of i nt eg rat i on : "))
up per_l i mi t = f l oat ( i nput ( " E nt er upper li mi t of i nt eg rat i on : "))
s ub_i nt erv al = int ( i nput ( " E nter number of sub i nt erv als : " ) )

# Call trapezoidal () method and get result


res ul t = s i mps on 13 ( l ower_li mit , upper_li mit , s ub_i nt erv al )
pri nt ( " I nt egrat i on res ul t by Si mps on 's 1 / 3 met hod is : % 0 . 6f " % ( res ul t )
)

8.4 Simpson’s 3/8th rule


∫6
Evaluate 1
dx using Simpson’s 3/8 th rule, taking 6 sub intervals
0 1+x2
def si mps ons _ 3 _ 8 _rul e ( f , a , b , n) :

85
lOMoARcPSD|370 367 39

h = (b - a) / n
s = f( a) + f( b)
for i in rang e ( 1 , n , 3 ):
s += 3 * f( a + i * h)
for i in range (3 , n-1 , 3 ):
s += 3 * f( a + i * h)
for i in range (2 , n-2 , 3 ):
s += 2 * f( a + i * h)
return s * 3 * h / 8

def f( x):
return 1 /( 1 +x ** 2 ) # function here

a = 0 # lower limit
b = 6 # upper limit
n = 6 # number of sub intervals

res ul t = s i mps ons _ 3 _ 8 _ rul e ( f , a , b , n)


pri nt ( '% 3 . 5f '% res ul t )

1.27631

8.5 Exercise:
∫1 1
x2 rule.
1. Evaluate the integral dx using Simpson’s
1 + x3 3
0
Ans: 0.23108
∫0.6
3 2
2. Use Simpson’s rule to find e−x dx by taking seven ordinates.
8
0
Ans: 0.5351
∫π
3. Evaluate using trapezoidal rule sin 2xdx. Take n = 6.
0

Ans: π/2

4. A solid of revolution is formed by rotating about the x-axis, the area between the
x-axis, the lines x = 0 and x = 1, and a curve through the points with the following
co-ordinates:

x y
0.00 1.0000
0.25 0.9896
0.50 0.9589
0.75 0.9089
1.00 0.8415

86
lOMoARcPSD|370 367 39

1
Estimate the volume of the solid formed using Simpson’s rd rule. Hint: Required
∫1 3
volume is 0 y 2 ∗ πdx. **[Ans: 2.8192]**
5. The velocity v(km/min) of a moped which starts from rest, is given at fixed intervals
of time t(min) as follows:
t: 2 4 6 8 10 12 14 16 18 20
v: 10 18 25 29 32 20 11 5 2 0
Estimate approximately the distance covered in twenty minutes.

Answer for 5.
We know that ds/dt=v. So to get distance (s) we have to integrate.
Here h = 2.2, v0 = 0, v1 = 10, v2 = 18, v3 = 25 etc.
# we sh al l use si mp so n 's 1 / 3 rule di re c tl y to e st im at e

h= 2
y = [ 0 , 10 , 18 , 25 , 29 , 32 , 20 , 11 , 5 , 2 , 0 ]
res ul t =( h/ 3 ) * (( y [ 0 ] +y [ 10 ]) + 4 *( y [ 1 ] +y [ 3 ] +y [ 5 ] +y [ 7 ] +y [ 9 ]) + 2 *( y [ 2 ] +y [ 4 ] +y[
6 ] +y[ 8 ]))

pri nt ( '% 3 . 5f '% result , ' km . ')

309.33333 km.

87
lOMoARcPSD|370 367 39

LAB 9: Solution of ODE of first order and first degree


by Taylor’s series and Modified Euler’s method
9.1 Objectives:
Use python

1. to solve ODE by Taylor series method.

2. to solve ODE by Modified Euler method.

3. to trace the solution curves.

9.2 Taylor series method to solve ODE


dx − 2y = 3ex with y(0) = 0 using Taylor series method at x = 0.1(0.1)0.3.
dy
Solve:
## module taylor
'''X , Y = ta ylo r ( deriv , x , y , xStop , h ) .
4th - order Taylor series method for solving the initial value problem { y
}' = { F( x, { y } ) } , where
{ y } = { y[ 0 ], y[ 1 ] ,... y[ n- 1 ] } .
x, y = initial conditions
x Stop = terminal value of x
h = increment of x
'''
from numpy i mport array
def t ay l or ( deriv , x , y , xStop , h) :
X = []
Y = []
X . append ( x )
Y. append ( y)
whil e x < xStop : # Loop over in tegr ati on steps
D = deriv (x , y) # Derivatives of y
H = 1.0
for j in rang e ( 3 ) : # Build Taylor series
H = H* h/( j + 1 )
y = y + D[ j ] * H # H = h^j/ j!
x = x + h
X . append ( x ) # Append results to
Y. append ( y) # lists X and Y

ret urn array ( X ) , array ( Y) # Con ve rt li st s into a rra ys

# deriv = user - supplied function that returns derivatives in the 4 x n


array
'''
[ y '[ 0 ] y '[ 1 ] y '[ 2 ] ... y '[ n - 1 ]
y ' '[ 0 ] y ' '[ 1 ] y ' '[ 2 ] ... y ''[ n - 1 ]
y '' '[ 0 ] y '''[ 1 ] y '' '[ 2 ] ... y '''[ n - 1 ]
y ''' '[ 0 ] y ' ''' [ 1 ] y ''' '[ 2 ] ... y ' ''' [ n - 1 ]]
'''
def deri v ( x , y ) :
D = zeros (( 4 , 1 ))

88
lOMoARcPSD|370 367 39

D[ 0 ] = [ 2 * y[ 0 ] + 3 * exp ( x)]
D[ 1 ] = [ 4 * y[ 0 ] + 9 * exp ( x)]
D[ 2 ] = [ 8 * y[ 0 ] + 21 * exp ( x)]
D[ 3 ] = [ 16 * y[ 0 ] + 45 * exp ( x)]
return D

x = 0.0 # Initial value of x


xStop = 0 . 3 # last value
y = arra y([ 0 . 0 ]) # Initial values of y
h = 0.1 # Step size
X , Y = t ayl or ( deriv ,x ,y , xStop , h)

pri nt ( " The requi red v al ues are : at x = % 0 . 2f , y =% 0 . 5f , x =% 0 . 2f , y =% 0 . 5f ,


x = % 0 . 2f , y=% 0 . 5f , x = % 0 . 2f , y=% 0
. 5f " %( X [ 0 ] , Y [ 0 ] , X [ 1 ] , Y[ 1 ] , X [ 2 ] , Y [ 2 ]
, X [ 3 ] , Y[ 3 ] ))

The required values are :at x= 0.00, y=0.00000, x=0.10, y=0.34850,


x = 0.20, y=0.81079,x = 0.30, y=1.41590

Solve y′ + 4y = x2 with initial conditions y(0) = 1 using Taylor series method at x =


0.1, 0.2.
from numpy i mport array
def t ay l or ( deriv , x , y , xStop , h) :
X = []
Y = []
X . append ( x )
Y. append ( y)
whil e x < xStop : # Loop over in tegr ati on steps
D = deriv (x , y) # Derivatives of y
H = 1.0
for j in rang e ( 3 ) : # Build Taylor series
H = H* h/( j + 1 )
y = y + D[ j ] * H # H = h^j/ j!
x = x + h
X . append ( x ) # Append results to
Y. append ( y) # lists X and Y

ret urn array ( X ) , array ( Y) # Con ve rt li st s into a rra ys

# deriv = user - supplied function that returns derivatives in the 4 x n


array
'''
[ y '[ 0 ] y '[ 1 ] y '[ 2 ] ... y '[ n - 1 ]
y"[ 0 ] y"[ 1 ] y"[ 2 ] ... y"[ n- 1 ]
y '' '[ 0 ] y '''[ 1 ] y '' '[ 2 ] ... y '''[ n - 1 ]
y""[ 0 ] y""[ 1 ] y""[ 2 ] ... y""[ n- 1 ]]
'''
def deri v ( x , y ) :
D = zeros (( 4 , 1 ))
D[ 0 ] = [ x ** 2 - 4 * y[ 0 ] ]
D[ 1 ] = [ 2 * x- 4 * x ** 2 + 16 * y[ 0 ] ]
D[ 2 ] = [ 2 - 8 * x + 16 * x ** 2 - 64 * y[ 0 ] ]
D[ 3 ] = [ - 8 + 32 * x- 64 * x ** 2 + 256 * y [ 0 ] ]

89
lOMoARcPSD|370 367 39

return D

x = 0.0 # Initial value of x


xStop = 0 . 2 # last value
y = arra y([ 1 . 0 ]) # Initial values of y
h = 0.1 # Step size
X , Y = t ayl or ( deriv ,x ,y , xStop , h)

pri nt ( " The requi red v al ues are : at x = % 0 . 2f , y =% 0 . 5f , x =% 0 . 2f , y =% 0 . 5f ,


x = % 0 . 2f , y = % 0 . 5f "%( X [ 0 ] , Y [ 0 ] , X[ 1
] , Y [ 1 ] ,X [ 2 ] , Y [ 2 ] ) )

The required values are :at x= 0.00, y=1.00000, x=0.10, y=0.66967,


x = 0.20, y=0.45026

9.3 Euler’s method to solve ODE:


To solve the ODE of the formdxdy = f(x, y) with initial conditions y(x0) = y0. The iterative
formula is given by : y(x(i+1) = y(xi) + hf(xi, y(xi)).
Solve: y′ = e−x with y(0) = −1 using Euler’s method at x = 0.2(0.2)0.6.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt

# Define parameters
f = l ambda x , y : np . exp ( - x) # ODE
h = 0 . 2 # Step size
y0 = - 1 # Initial Condition
n= 3
# Explicit Euler Method

y[ 0 ] = y0
x[ 0 ] = 0

for i in rang e ( 0 , n) :
x [ i+ 1 ] =x [ i ] +h
y[ i + 1 ] = y[ i] + h* f( x[ i], y[ i])

pri nt ( " The requi red v al ues are at x = % 0 . 2f , y =% 0 . 5f , x =% 0 . 2f , y =% 0 . 5f ,


x = % 0 . 2f , y=% 0 . 5f , x = % 0 . 2f , y=% 0 .
5f " %( x [ 0 ] , y [ 0 ] , x [ 1 ] , y [ 1 ] , x [ 2 ] , y [ 2 ] ,
x[ 3 ],y[ 3 ]))
pri nt ( " \ n\ n" )

plt . pl ot ( x , y , 'bo - - ', l abel = ' Approx i m a t e ')


plt . pl ot ( x , - np . exp ( - x) , 'g *- ', l abel = ' Ex act ')
plt . t itl e (" Appr ox i mat e and Ex act Sol ution " )
plt . x l abel ( 'x ')
plt . y l abel ( 'f ( x ) ')
plt . grid ()
plt . l eg end ( loc = ' best ')
plt . show ()

90
lOMoARcPSD|370 367 39

The required values are at x= 0.00, y=-1.00000, x=0.20, y=-0.80000,


x = 0.40, y=-0.63625,x = 0.60, y=-0.50219

Solve: y′ = −2y + x3e−2x with y(0) = 1 using Euler’s method at x = 0.1, 0.2.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt

# Define parameters
f = l ambda x , y : - 2 * y + ( x ** 3 ) * np . exp ( - 2 * x ) # ODE
h = 0 . 1 # Step size
y0 = 1 # Initial Condition
n= 2
# Explicit Euler Method

y[ 0 ] = y0
x[ 0 ] = 0

for i in rang e ( 0 , n) :
x [ i+ 1 ] =x [ i ] +h
y[ i + 1 ] = y[ i] + h* f( x[ i], y[ i])

pri nt ( " The requi red v al ues are at x = % 0 . 2f , y =% 0 . 5f , x =% 0 . 2f , y =% 0 . 5f , x


=% 0 . 2f , y =% 0 . 5f \ n\ n" %( x [ 0 ] , y [ 0 ] , x [ 1
],y[ 1 ],x [ 2 ], y[ 2 ]))

plt . pl ot ( x , y , 'bo - - ', l abel =" Approx i m a t e ( E uler 's met hod ) " )

plt . t itl e (" Sol ut i on by E ul er 's met hod " )


plt . x l abel ( 'x ')
plt . y l abel ( 'f ( x ) ')
plt . grid ()
plt . l eg end ( loc = ' best ')
plt . show ()

91
lOMoARcPSD|370 367 39

The required values are at x= 0.00, y=1.00000, x=0.10, y=0.80000,


x=0.20, y=0.64008

9.4 Modified Euler’s method


The iterative formula is:
h
y(n+1) = y 0 + [f(x , y ) + f(x , y (n) )], n = 0, 1, 2, 3, . . . ,
1 0 0 1 1
2
where, y1(n) is the nth approximation to y1.
The first iteration will use Euler’s method: y1 (0) = y0 + hf(x0, y0).
Solve y′ = −ky with y(0) = 100 using modified Euler’s method at x = 100, by taking
h = 25.
i mport numpy as np
i mport mat pl ot l i b . py pl ot as plt

def modi f i ed_eul er (f , x0 , y0 , h , n) :


x = np . zeros ( n+ 1 )
y = np . zeros ( n+ 1 )

x[ 0 ] = x0
y[ 0 ] = y0

for i in range ( n) :
x [ i+ 1 ] = x[ i ] + h
k1 = h * f( x[ i], y[ i])
k2 = h * f( x [ i + 1 ] , y [ i ] + k1 )
y [ i+ 1 ] = y[ i ] + 0 . 5 * ( k1 + k2 )

return x, y

92
lOMoARcPSD|370 367 39

def f(x, y):


return - 0 . 01 * y # ODE dy/ dx = - ky

x0 = 0 . 0
y0 = 100 . 0
h = 25
n = 4

x , y = modi f i ed_eul er (f , x0 , y0 , h , n)

pri nt ( " The requi red v al ue at x = % 0 . 2f , y = % 0 . 5f " %( x [ 4 ] , y [ 4 ]) )


pri nt ( " \ n\ n" )

# Plotting the results


plt . pl ot ( x , y , 'bo - ')
plt . x l abel ( 'x ')
plt . y l abel ( 'y ')
plt . t itl e ( ' Sol ut i on of dy / dx = - ky usi ng Modi f i ed E ul er \' s Met hod ')
plt . grid ( True )
plt . show ()

The required value at x= 100.00, y=37.25290

9.5 Exercise:
1. Find y(0.1) by Taylor Series exapnsion when y′ = x − y2, y(0) = 1.
Ans: y(0.1) = 0.9138

2. Find y(0.2) by Taylor Series exapnsion when y′ = x2y − 1, y(0) = 1, h = 0.1.


Ans: y(0.2) = 0.80227

93
lOMoARcPSD|370 367 39

3. Evaluate by modified Euler’s method: y′ = ln(x + y), y(0) = 2 at x = 0(0.2)0.8.


Ans: 2.0656, 2.1416, 2.2272, 2.3217

4. Solve by modified Euler’s method: y′ = x + y, y(0) = 1, h = 0.1, x = 0(0.1)0.3.


Ans: 1.1105, 1.2432, 1.4004

94
lOMoARcPSD|370 367 39

LAB 10: Solution of ODE of first order and first de-


gree by Runge-Kutta 4th order method and Milne’s
predictor and corrector method
10.1 Objectives:
1. To write a python program to solve first order differential equation using 4th order
Runge Kutta method.

2. To write a python program to solve first order differential equation using Milne’s
predictor and corrector method.

10.2 Runge-Kutta method


Apply the Runge Kutta method to find the solution of dy/dx = 1 + (y/x) at y(2) taking
h = 0.2. Given that y(1) = 2.
from sy mpy i mport *
i mport numpy as np
def R ung e Kut t a (g , x0 , h , y0 , xn ) :

x , y = sy mbol s ( 'x , y ')


f = l ambdi f y ([ x , y] , g)
xt=x0 +h
Y=[ y0 ]
w hil e xt <= xn :
k1 =h* f( x0 , y0 )
k2 =h* f( x0 +h/2 , y0 +k1 / 2 )
k3 =h* f( x0 +h/2 , y0 +k2 / 2 )
k4 =h* f ( x0 +h , y0 + k3 )
y1 =y0 +( 1 / 6 )*( k1 + 2 * k2 + 2 * k3 +k4 )
Y. append ( y1 )
# pri nt ( ' y( % 3 . 3f '% xt , ') is % 3 . 3f '% y1 )
x0 =xt
y0 =y1
xt=xt+ h
ret urn np . round ( Y , 2 )
R ung e Kut t a ( '1 +( y / x ) ',1 , 0 . 2 , 2 , 2 )

array([2. , 2.62, 3.27, 3.95, 4.66, 5.39])

10.3 Milne’s predictor and corrector method


Apply Milne’s predictor and corrector method to solve dy/dx = x2 + (y/2) at y(1.4).
Given that y(1)=2, y(1.1)=2.2156, y(1.2)=2.4649, y(1.3)=2.7514. Use corrector formula
thrice.
# Mil n e ' s me tho d to sol v e fi rs t o rde r DE
# Use corrector formula thrice
x0 = 1
y0 = 2

95
lOMoARcPSD|370 367 39

y1 = 2 . 2156
y2 = 2 . 4649
y3 = 2 . 7514
h= 0 . 1
x1 =x0 +h
x2 =x1 +h
x3 =x2 +h
x4 =x3 +h
def f (x, y):
return x ** 2 +( y/ 2 )

y10 =f( x0 , y0 )
y11 =f( x1 , y1 )
y12 =f( x2 , y2 )
y13 =f( x3 , y3 )
y4p =y0 +( 4 * h/ 3 )*( 2 * y11 - y12 + 2 * y13 )
pri nt ( ' predicted v al ue of y4 is % 3 . 3f '% y4p )
y14 =f( x4 , y4p );
for i in rang e ( 1 , 4 ) :
y4 =y2 +( h/ 3 )*( y14 + 4 * y13 +y12 );
pri nt ( ' correct ed v al ue of y4 after \ t it erati on %d is \ t % 3 . 5f \ t '%
(i, y4 ))
y14 =f( x4 , y4 );

predicted value of y4 is 3.079


corrected value of y4 after iteration 1 is 3.07940
corrected value of y4 after iteration 2 is 3.07940
corrected value of y4 after iteration 3 is 3.07940

In the next program, function will take all the inputs from the user and display the
answer.
Apply Milne’s predictor and corrector method to solve dy/dx = x2 + (y/2) at y(1.4).
Given that y(1)=2, y(1.1)=2.2156, y(1.2)=2.4649, y(1.3)=2.7514. Use corrector formula
thrice.
from sy mpy i mport *
def Mi l ne ( g , x0 , h , y0 , y1 , y2 , y3 ) :
x , y = sy mbol s ( 'x , y ')
f = l ambdi f y ( [x , y ] , g)
x1 =x0 +h
x2 =x1 +h
x3 =x2 +h
x4 =x3 +h

y10 =f( x0 , y0 )
y11 =f( x1 , y1 )
y12 =f( x2 , y2 )
y13 =f( x3 , y3 )
y4p =y0 +( 4 * h/ 3 )*( 2 * y11 - y12 + 2 * y13 )
pri nt ( ' predi ct ed v al ue of y4 ', y4p )
y14 =f( x4 , y4p )
for i in range ( 1 , 4 ) :
y4 =y2 +( h/ 3 )*( y14 + 4 * y13 +y12 )
pri nt ( ' correct ed v al ue of y4 , it erati on % d '% i , y4 )

96
lOMoARcPSD|370 367 39

y14 =f( x4 , y4 )
Mi l ne ( 'x ** 2 + y / 2 ',1 , 0 . 1 , 2 , 2 . 2156 , 2 . 4649 , 2 . 7514 )

predicted value of y4 3.0792733333333335


corrected value of y4 , iteration 1 3.0793962222222224
corrected value of y4 , iteration 2 3.079398270370371
corrected value of y4 , iteration 3 3.079398304506173

Apply Milne’s predictor and corrector method to solve dy/dx = x − y2 , y(0)=2 obtain
y(0.8). Take h=0.2. Use Runge-Kutta method to calculate required initial values.
Y = R ung e Kut t a ( 'x - y ** 2 ',0 , 0 . 2 , 0 , 0 . 8 )
pri nt ( 'y v al ues from R ung e - Kutt a met hod : ', Y )
Mi l ne ( 'x - y ** 2 ',0 , 0 . 2 , Y[ 0 ] ,Y [ 1 ] , Y [ 2 ] , Y [ 3 ] )

y values from Runge -Kutta method: [0. 0.02 0.08 0.18 0.3 ]
predicted value of y4 0.3042133333333334
corrected value of y4 , iteration 1 0.3047636165214815
corrected value of y4 , iteration 2 0.3047412758696499
corrected value of y4 , iteration 3 0.3047421836520892

10.4 Exercise:
1. Find y(0.1) by Runge Kutta method when y′ = x − y2, y(0) = 1.
Ans: y(0.1) = 0.91379

2. Evaluate by Runge Kutta method : y′ = log(x + y), y(0) = 2 at x = 0(0.2)0.8.


Ans: 2.155, 2.3418, 2.557, 2.801

3. Solve by Milnes method: y′ = x + y, y(0)=1, h=0.1, Calculate y(0.4) . Calculate


required initial values from Runge Kutta method.
Ans: 1.583649219

97

You might also like