Lab Manual
Lab Manual
Lab Manual
of
First 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.
I Basics of Python
II Programming Structure
Lab 2. Finding Angle Between Two Polar Curves, Curvature and Radius of Curvature
Lab 5. Solution of First Order Differential Equations and Plotting the Solution Curve
Lab 8. Numerical Solution of System of Equations, Test for Consistency and Graphical
Representation of the Solution.
Lab 10. Compute Eigen Value and Corresponding Eigen Vectors, Find the Dominant Eigen
Value and Corresponding Eigen Vector by Rayleigh Power Method.
1
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.
2
I. Introduction to PYTHON
https://drive.google.com/file/d/1gVG2IJ8BIjhYDwDx6jWJns59h9dGOGVi/view?usp=
share_link
# Syntax :
if condition :
statements
Enter an integer: 5
Entered value is positive
# Synatx :
# if condition :
# statements 1
# else :
# statements 2
3
print ( " Number entered is positive " )
else :
print ( " Number entered is negative " )
Enter an integer: -5
Number entered is negative
# Syntax :
# if condition 1 :
# statements 1
# elif condition 2 :
# statements 2
# elif condition 3 :
# statements 3
# else :
# statements 4
# Example :
perc = float ( input ( " Enter the percentage of marks obtained by a student : "
))
if perc > = 75 :
print ( perc , ' % - Grade : Distinction ')
elif perc > = 60 :
print ( perc , ' % - Grade : First class ')
elif perc > = 50 :
print ( perc , ' % - Grade : Second class ')
else :
print ( perc , ' % - Grade : Fail ')
Enter a number:45
The given number is not divisible by 7
4
# Conversion Celsius to Fahrenheit and vice - versa :
def print_menu () :
print ( " 1 . Celsius to Fahrenheit " )
print ( " 2 . Fahrenheit to Celsius " )
def Far () :
c = float ( input ( " Enter Temperature in Celsius : " ) )
f = c * ( 9 / 5 ) + 32
print ( " Temperature in Fahrenheit : { 0 : 0 . 2f } " . format ( f ) )
def Cel () :
f = float ( input ( " Enter Temperature in Fahrenheit : " ) )
c = ( f - 32 ) * ( 5 / 9 )
print ( " Temperature in Celsius : { 0 : 0 . 2f } " . format ( c ) )
print_menu ()
choice = input ( " Which conversion would you like : " )
if ( choice = = '1 ') :
Far ()
elif ( choice = = '2 ') :
Cel ()
else : print ( " INVALID " )
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Which conversion would you like: 1
Enter Temperature in Celsius: 34
Temperature in Fahrenheit: 93.20
for loop
- Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
nested loops
- You can use one or more loop inside any another while, for or do..while loop.
5
1. While loop
• Is used to execute a block of statements repeatedly until a given condition is satis-
fied.
• When the condition becomes false, the line immediately after the loop in the pro-
gram is executed
• Syntax:
while expression :
statement ( s )
# Fibonacci series :
# the sum of two elements defines the next
a, b = 0, 1 # First step : a = 0 ; b = 1 second step : a = 1 ; b = 1 + 0
while a < 10 :
a , b =b , a + b
print ( a )
1
1
2
3
5
8
13
6
break statement
• It terminates the current loop and resumes execution at the next statement.
• The most common use for break is when some external condition is triggered re-
quiring a hasty exit from a loop.
• The break statement can be used in both while and for loops.
• If you are using nested loops, the break statement stops the execution of the inner-
most loop and start executing the next line of code after the block.
1
2
3
Continue statement
• The continue statement rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the loop.
• The continue statement can be used in both while and for loops.
i=0
while i < 6 :
i+=1
if i = = 3 :
continue
print ( i )
1
2
4
5
6
7
2. for loop
• are used for sequential traversal
• also used to access elements from a container (for example list, string, tuple) using
built-in function range()
• Syntax:
for variable_name in sequence :
statement_1
statement_2
....
# Print numbers from 101 to 130 with a step length 2 excluding 130 .
for i in range ( 101 , 130 , 2 ) :
print ( i )
101
103
105
107
109
111
113
115
117
119
121
123
125
127
129
8
One can type the following examples and observe the outputs.
# Sum of first n natural numbers
sum = 0
n = int ( input ( " Enter n : " ) )
for i in range (1 , n + 1 ) : # i =1 , sum = 1 ; i =2 , sum = 3 ; i =4 , sum =7 , ....
sum = sum + i
print ( " Sum of first " ,n , " natural numbers = " , sum )
# Multiplication table
n = int ( input ( " Enter the number " ) )
for i in range (1 , 11 ) :
print (n , 'x ' ,i , '= ' ,n * i )
apple
banana
cherry
orange
Exercise:
1. Finding the factors of a number using for loop.
9
LAB 1: 2D plots of Cartesian and polar curves.
1.1 Objectives:
Use python
1. to plot Cartesian curves.
2. to plot polar curves.
3. to plot implicit functions.
3. Return num evenly spaced numbers over a specified interval [start, stop]. The
endpoint of the interval can optionally be excluded.
numpy . linspace ( start , stop , num = 50 , endpoint = True , retstep = False ,
dtype = None , axis = 0 )
4. Return evenly spaced values within a given interval. arange can be called with a
varying number of positional arguments.
numpy . arange ( [ start , ] stop , [ step , ] dtype = None , * , like = None )
https://matplotlib.org/stable/api/pyplot_summary.html#module-matplotlib.pyplot
x = [1 ,2 ,3 ,4 ,6 ,7 , 8 ] # x axis values
y = [2 ,7 ,9 ,1 ,5 , 10 , 3 ] # corresponding y axis values
plt . scatter (x , y ) # plotting the points
plt . xlabel ( 'x - axis ') # naming the x axis
plt . ylabel ( 'y - axis ') # naming the y axis
plt . title ( ' Scatter points ') # giving a title to my graph
plt . show () # function to show the plot
10
1.3 Example: Plotting a line(Line plot)
# importing the required module
import matplotlib . pyplot as plt
x = [1 ,2 ,3 ,4 ,6 ,7 , 8 ] # x axis values
y = [2 ,7 ,9 ,1 ,5 , 10 , 3 ] # corresponding y axis values
plt . plot (x , y , 'r + - - ') # plotting the points
plt . xlabel ( 'x - axis ') # naming the x axis
plt . ylabel ( 'y - axis ') # naming the y axis
plt . title ( ' My first graph ! ') # giving a title to my graph
plt . show () # function to show the plot
11
1.4 Functions
1. Exponential curve, y = ex
import numpy as np
import matplotlib . pyplot as plt
x = np . arange ( - 10 , 10 , 0 . 001 )
y1 = np . sin ( x )
y2 = np . cos ( x )
plt . plot (x , y1 ,x , y2 ) # plotting sine and cosine function together with
same values of x
plt . title ( " sine curve and cosine curve " )
plt . xlabel ( " Values of x " )
plt . ylabel ( " Values of sin ( x ) and cos ( x ) " )
plt . grid ()
plt . show ()
12
# A simple graph
import matplotlib . pyplot as plt
import numpy as np
x = np . linspace (0 , 2 , 100 )
plt . title ( " Simple Plot " ) # Add a title to the axes .
plt . legend () # Add a legend
plt . show () # to show the complete graph
13
1.5 Implicit Function
Syntax:
14
2. Strophoid: y 2 (a − x) = x2 (a + x), a > 0
p3 = plot_implicit (
Eq (( y ** 2 ) * ( 2 - x ) , ( x ** 2 ) * ( 2 + x ) ) , (x , -5 , 5 ) , (y , -5 , 5 ) ,
title = ' Strophoid : $y ^ 2 (a - x ) = x ^ 2 ( a + x ) , a > 0$ ') # a=2
3. Cissiod: y 2 (a − x) = x3 , a > 0
15
p4 = plot_implicit (
Eq (( y ** 2 ) * ( 3 - x ) ,x ** 3 ) ,(x , -2 , 5 ) ,(y , -5 , 5 ) ) # a = 3
4. Lemniscate: a2 y 2 = x2 (a2 − x2 )
p5 = plot_implicit (
Eq ( 4 * ( y ** 2 ) ,( x ** 2 ) * ( 4 - x ** 2 ) ) ,(x , -5 , 5 ) ,(y , -5 , 5 ) ) # a = 2
16
5. Folium of De-Cartes: x3 + y 3 = 3axy
p6 = plot_implicit (
Eq ( x ** 3 + y ** 3 , 3 * 2 * x * y ) ,(x , -5 , 5 ) ,(y , -5 , 5 ) ) # a = 2
• r: It is the distance.
import numpy as np
import matplotlib . pyplot as plt
17
# plotting the circle
for i in rads :
plt . polar (i , r , 'g . ')
plt . show ()
18
4. Four leaved Rose: r = 2|cos2x|
import numpy as np
import matplotlib . pyplot as plt
import math
rad = np . arange (0 , ( 2 * np . pi ) , 0 . 01 )
# plotting the cardioid
for i in rad :
r = a + ( a * np . cos ( i ) )
plt . polar (i ,r , 'g . ')
r1 = a - ( a * np . cos ( i ) )
plt . polar (i , r1 , 'r . ')
# display the polar plot
plt . show ()
19
1.7 Parametric Equation
1. Circle: x = acos(θ); y = asin(θ)
import numpy as np
import matplotlib . pyplot as plt
def circle ( r ) :
x = [ ] # create the list of x coordinates
y = [ ] # create the list of y coordinates
20
2. Cycloid: x = a(θ − sinθ); y = a(1 − sinθ)
def cycloid ( r ) :
x = [ ] # create the list of x coordinates
y = [ ] # create the list of y coordinates
1.8 Exercise:
Plot the following:
1. Parabola y 2 = 4ax
x2 y2
2. Hyperbola a2
− b2
=1
3. Lower half of the circle: x2 + 2x = 4 + 4y − y 2
4. cos( πx
2
)
5. 1 + sin(x + π4 )
6. Spiral of Archimedes: r = a + bθ
7. Limacon: r = a + b cosθ
21
LAB 2: Finding angle between two polar curves, cur-
vature and radius of curvature.
2.1 Objectives:
Use python
2. Derivative()
Derivative ( expression , reference variable )
3. doit()
doit ( x )
5. simplify()
simplify ( expression )
8. display()
display ( expression )
22
math_expression . subs ( variable , substitute )
1. Find the angle between the curves r = 4(1 + cos t) and r = 5(1 − cos t).
r1 = 4 * ( cos ( t ) ) ;
r2 = 5 * ( sin ( t ) ) ;
dr1 = diff ( r1 , t )
dr2 = diff ( r2 , t )
t1 = r1 / dr1
t2 = r2 / dr2
q = solve ( r1 - r2 , t )
23
w1 = t1 . subs ( { t : float ( q [ 0 ] ) } )
w2 = t2 . subs ( { t : float ( q [ 0 ] ) } )
y1 = atan ( w1 )
y2 = atan ( w2 )
w = abs ( y1 - y2 )
print ( ' Angle between curves in radians is % 0 . 4f '% float ( w ) )
24
from sympy import *
from sympy . abc import rho , x ,y ,r ,K ,t ,a ,b ,c , alpha # define all symbols
required
y = ( sqrt ( x ) - 4 ) ** 2
y = a * sin ( t ) # input the parametric equation
x = a * cos ( t )
dydx = simplify ( Derivative (y , t ) . doit () ) / simplify ( Derivative (x , t ) . doit () )
# find the derivative of parametric
equation
rho = simplify (( 1 + dydx ** 2 ) ** 1 . 5 / ( Derivative ( dydx , t ) . doit () / ( Derivative (x ,
t ) . doit () ) ) ) # substitute the
derivative in radius of curvature
formula
print ( ' Radius of curvature is ')
display ( ratsimp ( rho ) )
t1 = pi / 2
r1 = 5
rho1 = rho . subs (t , t1 ) ;
rho2 = rho1 . subs (a , r1 ) ;
print ( '\ n \ nRadius of curvature at r = 5 and t = pi / 2 is ' , simplify ( rho2 ) ) ;
curvature = 1 / rho2 ;
print ( '\ n \ n Curvature at (5 , pi / 2 ) is ' , float ( curvature ) )
2.5 Exercise:
Plot the following:
1. Find the angle between radius vector and tangent to the folloing polar curves
a) r = aθ and r = aθ
Ans: Angle between curves in radians is 90.000
b) r = 2sin(θ) and r = 2cos(θ)
Ans: Angle between curves in radians is 90.000
25
2. Find the radius of curvature of r = a(1 − cos(t)) at t = π2 .
2 )1.5
Ans: 0.942809041582063(a
a2
5. Find the radius of curvature of x = a(t − sin(t)) andy = a(1 − cos(t)) at t = π/2.
Ans: ρ = 2.82842712 and κ = 0.353553
26
LAB 3: Finding partial derivatives and Jacobian of
functions of several variables.
3.1 Objectives:
Use python
1. to find partial derivatives of functions of several variables.
2. to find Jacobian of function of two and three variables.
27
1. Prove that mixed partial derivatives , uxy = uyx for u = exp(x)(xcos(y) −
ysin(y)).
3.3 II Jacobians
Let x = g(u, v) and y = h(u, v) be a transformation of the plane. Then the Jacobian of
this transformation is ∂x ∂x
∂(x, y) ∂u
∂v .
J= = ∂y ∂y
∂(u, v) ∂x ∂v
u=x*y/z
v=y*z/x
w=z*x/y
# find the all first order partial derivates
dux = diff (u , x )
28
duy = diff (u , y )
duz = diff (u , z )
dvx = diff (v , x )
dvy = diff (v , y )
dvz = diff (v , z )
dwx = diff (w , x )
dwy = diff (w , y )
dwz = diff (w , z )
u = x + 3 * y ** 2 - z ** 3
v = 4 * x ** 2 * y * z
w = 2 * z * z ** 2 - x * y
dux = diff (u , x )
duy = diff (u , y )
duz = diff (u , z )
dvx = diff (v , x )
dvy = diff (v , y )
dvz = diff (v , z )
dwx = diff (w , x )
dwy = diff (w , y )
dwz = diff (w , z )
J = Matrix ( [ [ dux , duy , duz ] ,[ dvx , dvy , dvz ] ,[ dwx , dwy , dwz ] ] ) ;
J1 = J . subs ( [ (x , 1 ) , (y , - 1 ) , (z , 0 ) ] )
29
Jac1 = Determinant ( J1 ) . doit ()
display ( Jac1 )
∂(X,Y,Z)
3. X = ρ ∗ cos(ϕ) ∗ sin(θ), Y = ρ ∗ cos(ϕ) ∗ cos(θ), Z = ρ ∗ sin(ϕ) then find ∂(ρ,ϕ,θ)
.
3.4 Exercise:
Plot the following:
∂2u ∂2u
1. If u = tan−1 (y/x) verify that ∂y∂x
= ∂x∂y
.
Ans:True
2 2
2. If u = log( xx+y
+y
) show that xux + yuy = 1.
Ans: True
30
LAB 4: Applications of Maxima and Minima of func-
tions of two variables, Taylor series expansion and
L’Hospital’s Rule
4.1 Objectives:
Use python
2. to expand the given single variable funtion as Taylor’s and Maclaurin series.
2. To evaluate an expression
sympy . evalf ()
import sympy
from sympy import Symbol , solve , Derivative , pprint
x = Symbol ( 'x ')
y = Symbol ( 'y ')
f = x ** 2 + x * y + y ** 2 + 3 * x - 3 * y + 4
31
d1 = Derivative (f , x ) . doit ()
d2 = Derivative (f , y ) . doit ()
criticalpoints1 = solve ( d1 )
criticalpoints2 = solve ( d2 )
s1 = Derivative (f ,x , 2 ) . doit ()
s2 = Derivative (f ,y , 2 ) . doit ()
s3 = Derivative ( Derivative (f , y ) ,x ) . doit ()
print ( ' function value is ')
1. Expand sin(x) as Taylor series about x = pi/2 upto 3rd degree term. Also
find sin(1000 )
import numpy as np
from matplotlib import pyplot as plt
from sympy import *
x = Symbol ( 'x ')
y = sin ( 1 * x )
format
x0 = float ( pi / 2 )
dy = diff (y , x )
d2y = diff (y ,x , 2 )
d3y = diff (y ,x , 3 )
yat = lambdify (x , y )
dyat = lambdify (x , dy )
d2yat = lambdify (x , d2y )
d3yat = lambdify (x , d3y )
y = yat ( x0 ) + (( x - x0 ) / 2 ) * dyat ( x0 ) + (( x - x0 ) ** 2 / 6 ) * d2yat ( x0 ) + (( x - x0 ) ** 3 / 24 ) *
d3yat ( x0 )
print ( simplify ( y ) )
yat = lambdify (x , y )
print ( " % . 3f " % yat ( pi / 2 + 10 * ( pi / 180 ) ) )
32
def f ( x ) :
return np . sin ( 1 * x )
x = np . linspace ( - 10 , 10 )
import numpy as np
from matplotlib import pyplot as plt
from sympy import *
x = Symbol ( 'x ')
y = sin ( x ) + cos ( x )
format
x0 = float ( 0 )
dy = diff (y , x )
d2y = diff (y ,x , 2 )
d3y = diff (y ,x , 3 )
yat = lambdify (x , y )
dyat = lambdify (x , dy )
d2yat = lambdify (x , d2y )
d3yat = lambdify (x , d3y )
y = yat ( x0 ) + (( x - x0 ) / 2 ) * dyat ( x0 ) + (( x - x0 ) ** 2 / 6 ) * d2yat ( x0 ) + (( x - x0 ) ** 3 / 24 ) *
d3yat ( x0 )
print ( simplify ( y ) )
yat = lambdify (x , y )
print ( " % . 3f " % yat ( 10 * ( pi / 180 ) ) )
def f ( x ) :
return np . sin ( 1 * x ) + np . cos ( x )
x = np . linspace ( - 10 , 10 )
33
sin(x)
1. lim x
x→0
1 x
3. Prove that limx→∞ 1 + x
=e
4.6 Exercise:
Plot the following:
1. Find the Taylor Series expansion of y = e−2x at x = 0 upto third degree term.
Ans: −0.333333333333333 ∗ x3 + 0.666666666666667 ∗ x2 − 1.0 ∗ x + 1.0
2
2. Expand y = xe−3x as Maclaurin’s series upto fifth degree term.
Ans: x ∗ (0.75 ∗ x4 − 0.75 ∗ x2 + 0.5)
34
LAB 5: Solution of First order differential equation
and ploting the solution curves
5.1 Objectives:
Use python
Parameters
• eq: eq can be any supported ordinary differential equation (see the ode doc-
string for supported methods). This can either be an Equality, or an expres-
sion, which is assumed to be equal to 0.
• func: f(x) is a function of one variable whose derivatives in that variable make
up the ordinary differential equation eq. In many cases it is not necessary to
provide this; it will be autodetected (and an error raised if it could not be
detected).
• hint: hint is the solving method that you want dsolve to use. Use classify ode(eq,
f(x)) to get all of the possible hints for an ODE. The default hint, default,
will use whatever hint is returned first by classify ode(). See Hints below
for more options that you can use for hint.
• simplify: simplify enables simplification by odesimp(). See its docstring for
more information. Turn this off, for example, to disable solving of solutions
for func or simplification of arbitrary constants. It will still integrate with this
hint. Note that the solution may contain more arbitrary constants than the
order of the ODE with this option enabled.
• xi and eta: are the infinitesimal functions of an ordinary differential equa-
tion. They are the infinitesimals of the Lie group of point transformations
for which the differential equation is invariant. The user can specify values
for the infinitesimals. If nothing is specified, xi and eta are calculated using
infinitesimals() with the help of various heuristics.
• ics: is the set of initial/boundary conditions for the differential equation.It
should be given in the form of {f(x0): x1, f(x).diff(x).subs(x, x2):
x3} and so on. For power series solutions, if no initial conditions are specified
f(0) is assumed to be C0 and the power series solution is calculated about 0.
35
• x0: is the point about which the power series solution of a differential equation
is to be evaluated.
• n: gives the exponent of the dependent variable up to which the power series
solution of a differential equation is to be evaluated. also be much faster than
all, because integrate() is an expensive routine.
• Usage:
– Solves any kind of ordinary differential equation and system of ordinary
differential equations.
– Usage dsolve(eq, f(x), hint) − > Solve ordinary differential equation
eq for function f(x), using method hint.
Parameters:
3. linspace():
linspace ( start , stop , num = 50 , endpoint = True , retstep = False , dtype =
None , axix = 0 )
Prameters
36
dP (t)
1. Solve : dt
= r.
# General solution
print ( " \ nGeneral Solution " )
dy
2: Solve: dx
+ tanx − y 3 secx = 0.
y1 = Derivative (y , x )
z1 = dsolve ( Eq ( y1 + y * tan ( x ) - y ** 3 * sec ( x ) ) ,y )
display ( z1 )
dy
3: Solve: x3 dx − x2 y + y 4 cosx = 0.
37
dy
1. Solve dt
= −ky with parameter k = 0.3 and y(0) = 5.
import numpy as np
from scipy . integrate import odeint
import matplotlib . pyplot as plt
# Function returns dy / dt
def model (y , t ) :
k=0.3
# dydt = - k * y
return - k * y
# initial condition
y0 = 5
# solve ODE
y = odeint ( model , y0 , t )
plt . plot (t , y )
plt . title ( ' Solution of dy / dt = - ky ; k = 0 .3 , y ( 0 ) = 5 ')
plt . xlabel ( ' time ')
plt . ylabel ( 'y ( t ) ')
plt . show ()
2. Simulate τ dy
dt
= −y + Kp u; Kp = 3.0, τ = 2.0.
import numpy as np
import matplotlib . pyplot as plt
from scipy . integrate import odeint
Kp = 3
taup = 2
# Differential Equation :
def model (y , t ) :
u = 1
return ( - y + Kp * u ) / taup
t3 = np . linspace (0 , 14 , 100 )
# ODE integrator
y3 = odeint ( model ,0 , t3 )
plt . plot ( t3 , y3 , 'r - ' , linewidth =1 , label = ' ODE Integrator ')
plt . xlabel ( ' Time ')
plt . ylabel ( ' Response ( y ) ')
plt . legend ( loc = ' best ')
plt . show ()
38
3. Application problem
A culture initially has P0 number of bacteria. At t = 1 hour the number of bacteria is
measured to be 23 P0 . If the rate of growth is proportional to the number of bacteria P (t)
present at time t, determine the time necessary for the number of bacteria to triple.
The differential equation is : dp dt
= kp; P (1) = 32 p0 .
0.405465108108164t
The solution is : y = P0 e , y0 = 20.
from pylab import *
t = arange (0 , 10 , 0 . 5 ) # Define the range where we want solution
P0 = 20
y = 20 * exp ( 0 . 405465108108164 * t )
plot (t , y )
xlabel ( ' Time ')
ylabel ( ' no of bacteria ')
title ( ' Law of Natural Growth ')
show ()
import numpy as np
from sympy import *
from matplotlib import pyplot as plt
t2 = 20 # surrounding temp
t1 = 100 # inital temp
# one reading t = 1 minute temp is 75 degree
t = 10
T = 75
k1 = ( 1 / t ) * log (( t1 - t2 ) / ( T - t2 ) ) # k calculation
print ( 'k = ' , k1 )
k = Symbol ( 'k ')
t = Symbol ( 't ')
T = Function ( 'T ') ( t )
T = t2 + ( t1 - t2 ) * exp ( - k * t ) # solution
print ( 'T = ' ,T )
# ploting the solution curve
T = T . subs (k , k1 )
T = lambdify (t , T )
t = np . linspace (0 , 70 )
39
# When time t = 30 minute T is
print ( ' When time t = 30 minute T is , ' ,T ( 30 ) , 'o C ')
5.3 Exercise:
Plot the following:
4. Solve x2 y ′ = ylog(y) − y ′ .
−1
Ans:y(x) = eC1 tan (x)
40
LAB 8: Numerical solution of system of equations,
test for consistency and graphical representation of
the solution.
8.1 Objectives:
Use python
2. numpy.linalg.matrix rank(A):
numpy . linalg . matrix_rank ( A )
3. numpy.shape(A):
numpy . shape ( A )
4. sympy.Matrix()
sympy . Matrix ()
Creates a matrix.
41
Example 1:
Check whether the following system of homogenous linear equation has non-trivial solu-
tion. x1 + 2x2 − x3 = 0, 2x1 + x2 + 4x3 = 0, 3x1 + 3x2 + 4x3 = 0.
import numpy as np
A = np . matrix ( [ [1 ,2 , - 1 ] ,[2 ,1 , 4 ] ,[3 ,3 , 4 ] ] )
B = np . matrix ( [ [ 0 ] ,[ 0 ] ,[ 0 ] ] )
r = np . linalg . matrix_rank ( A )
n = A . shape [ 1 ]
if ( r = = n ) :
print ( " System has trivial solution " )
else :
print ( " System has " , n -r , " non - trivial solution ( s ) " )
Example 2:
Check whether the following system of homogenous linear equation has non-trivial solu-
tion. x1 + 2x2 − x3 = 0, 2x1 + x2 + 4x3 = 0, x1 − x2 + 5x3 = 0.
import numpy as np
A = np . matrix ( [ [1 ,2 , - 1 ] ,[2 ,1 , 4 ] ,[1 , -1 , 5 ] ] )
B = np . matrix ( [ [ 0 ] ,[ 0 ] ,[ 0 ] ] )
r = np . linalg . matrix_rank ( A )
n = A . shape [ 1 ]
if ( r = = n ) :
print ( " System has trivial solution " )
else :
print ( " System has " , n -r , " non - trivial solution ( s ) " )
42
Example 3:
Examine the consistency of the following system of equations and solve if consistent.
x1 + 2x2 − x3 = 1, 2x1 + x2 + 4x3 = 2, 3x1 + 3x2 + 4x3 = 1.
A = np . matrix ( [ [1 ,2 , - 1 ] ,[2 ,1 , 4 ] ,[3 ,3 , 4 ] ] )
B = np . matrix ( [ [ 1 ] ,[ 2 ] ,[ 1 ] ] )
AB = np . concatenate (( A , B ) , axis = 1 )
rA = np . linalg . matrix_rank ( A )
rAB = np . linalg . matrix_rank ( AB )
n = A . shape [ 1 ]
if ( rA = = rAB ) :
if ( rA = = n ) :
print ( " The system has unique solution " )
print ( np . linalg . solve (A , B ) )
else :
print ( " The system has infinitely many solutions " )
else :
print ( " The system of equations is inconsistent " )
Example 4:
Examine the consistency of the following system of equations and solve if consistent.
x1 + 2x2 − x3 = 1, 2x1 + x2 + 5x3 = 2, 3x1 + 3x2 + 4x3 = 1.
A = np . matrix ( [ [1 ,2 , - 1 ] ,[2 ,1 , 5 ] ,[3 ,3 , 4 ] ] )
B = np . matrix ( [ [ 1 ] ,[ 2 ] ,[ 1 ] ] )
AB = np . concatenate (( A , B ) , axis = 1 )
rA = np . linalg . matrix_rank ( A )
rAB = np . linalg . matrix_rank ( AB )
n = A . shape [ 1 ]
if ( rA = = rAB ) :
if ( rA = = n ) :
print ( " The system has unique solution " )
print ( np . linalg . solve (A , B ) )
else :
print ( " The system has infinitely many solutions " )
else :
print ( " The system of equations is inconsistent " )
import sympy as sp
x , y , z = sp . symbols ( 'x y z ')
43
A = sp . Matrix ( [ [1 ,2 , - 1 ] ,[2 ,1 , 5 ] ,[3 ,3 , 4 ] ] )
B = sp . Matrix ( [ [ 1 ] ,[ 2 ] ,[ 1 ] ] )
AB = A . col_insert ( A . shape [ 1 ] ,B )
rA = A . rank ()
rAB = AB . rank ()
n = A . shape [ 1 ]
print ( " The coefficient matrix is " )
sp . pprint ( A )
print ( f " The rank of the coefficient matrix is { rA } " )
print ( " The augmented matrix is " )
sp . pprint ( AB )
print ( f " The rank of the augmented matrix is { rAB } " )
print ( f " The number of unkowns are { n } " )
if ( rA = = rAB ) :
if ( rA = = n ) :
print ( " The system has unique solution " )
else :
print ( " The system has infinitely many solutions " )
print ( sp . s o lv e _ li n e ar _ s y st e m ( AB ,x ,y , z ) )
else :
print ( " The system of equations is inconsistent " )
y1 = ( 1 - 3 * x ) / 5
y2 = 1 - x
plt . plot (x , y1 ,x , y2 )
plt . plot (p ,q , marker = 'o ')
44
plt . legend ( [ ' $3x + 5y = 1$ ' , ' $x + y = 1$ '] )
plt . grid ()
plt . show ()
Point of intersection is A ( 2 , -1 )
Example 6:
Obtain the solution of 2x + y = 7; 3x − y = 3 graphically.
from sympy import *
import numpy as np
import matplotlib . pyplot as plt
y1 = 7 - 2 * x
y2 = 3 * x - 3
plt . grid ()
plt . show ()
Point of intersection is A ( 2 , 3 )
8.5 Exercise:
1. Find the solution of the system homogeneous equations x+y+z = 0, 2x+y−3z = 0
and 4x − 2y − z = 0.
Ans: The system has trivial solution.
45
2. Find the solution of the system non-homogeneous equations 25x + y + z = 27,
2x + 10y − 3z = 9 and 4x − 2y − 12z = −10.
Ans: [1, 1, 1]
46
LAB 9: Solution of system of linear equations by
Gauss-Seidel method.
9.1 Objectives:
Use python
Example 1:
Solve the system of equations using Gauss-Seidel method: 20x+y−2z = 17; 3x+20y−z =
−18; 2x − 3y + 20z = 25.
# Gauss Seidel Iteration
# Defining equations to be solved
# in diagonally dominant form
f1 = lambda x ,y , z : ( 17 - y + 2 * z ) / 20
f2 = lambda x ,y , z : ( - 18 - 3 * x + z ) / 20
f3 = lambda x ,y , z : ( 25 - 2 * x + 3 * y ) / 20
# Initial setup
x0 = 0
y0 = 0
z0 = 0
count = 1
condition = True
while condition :
x1 = f1 ( x0 , y0 , z0 )
y1 = f2 ( x1 , y0 , z0 )
z1 = f3 ( x1 , y1 , z0 )
print ( '% d \ t % 0 . 4f \ t % 0 . 4f \ t % 0 . 4f \ n ' % ( count , x1 , y1 , z1 ) )
e1 = abs ( x0 - x1 ) ;
e2 = abs ( y0 - y1 ) ;
e3 = abs ( z0 - z1 ) ;
count + = 1
x0 = x1
y0 = y1
z0 = z1
47
condition = e1 > e and e2 > e and e3 > e
Count x y z
Example 2:
Solve x + 2y − z = 3; 3x − y + 2z = 1; 2x − 2y + 6z = 2 by Gauss-Seidel Iteration method.
# Defining equations to be solved
# in diagonally dominant form
f1 = lambda x ,y , z : ( 1 + y - 2 * z ) / 3
f2 = lambda x ,y , z : ( 3 - x + z ) / 2
f3 = lambda x ,y , z : ( 2 - 2 * x + 2 * y ) / 6
# Initial setup
x0 , y0 , z0 = 0 ,0 , 0
x0 = x1
y0 = y1
z0 = z1
48
break
Example 3:
Apply Gauss-Siedel method to solve the system of equations: 20x + y − 2z = 17; 3x +
20y − z = −18; 2x − 3y + 20z = 25.
from numpy import *
def seidel (a , x ,b ) :
# Finding length of a ( 3 )
n = len ( a )
# for loop for 3 times as to calculate x , y , z
for j in range (0 , n ) :
# temp variable d to store b [ j ]
d = b[j]
# to calculate respective xi , yi , zi
for i in range (0 , n ) :
if ( j ! = i ) :
d=d-a[j][i] * x[i]
# updating the value of our solution
x[j] = d / a[j][j]
# returning our updated solution
return x
a = array ( [ [ 20 .0 , 1 .0 , - 2 . 0 ] ,[ 3 .0 , 20 .0 , - 1 . 0 ] ,[ 2 .0 , - 3 .0 , 20 . 0 ] ] )
x = array ( [ [ 0 . 0 ] ,[ 0 . 0 ] ,[ 0 . 0 ] ] )
b = array ( [ [ 17 . 0 ] ,[ - 18 . 0 ] ,[ 25 . 0 ] ] )
for i in range (0 , 25 ) :
x = seidel (a , x , b )
print ( x )
[[ 1.]
[-1.]
[ 1.]]
Note: In the next example we will check whether the given system is diagonally
dominant or not.
49
Example 4:
Solve the system of equations 10x + y + z = 12; x + 10y + z = 12; x + y + 10z = 12 by
Gauss-Seidel method.
from numpy import *
import sys
# This programme will check whether the given system is diagonally
dominant or not
def seidel (a , x ,b ) :
# Finding length of a ( 3 )
n = len ( a )
# for loop for 3 times as to calculate x , y , z
for j in range (0 , n ) :
# temp variable d to store b [ j ]
d = b[j]
# to calculate respective xi , yi , zi
for i in range (0 , n ) :
if ( j ! = i ) :
d=d-a[j][i] * x[i]
# updating the value of our solution
x[j] = d/a[j][j]
# returning our updated solution
return x
a = array ( [ [ 10 .0 , 1 .0 , 1 . 0 ] ,[ 1 .0 , 10 .0 , 1 . 0 ] ,[ 1 .0 , 1 .0 , 10 . 0 ] ] )
x = array ( [ [ 1 . 0 ] ,[ 0 . 0 ] ,[ 0 . 0 ] ] )
b = array ( [ [ 12 . 0 ] ,[ 12 . 0 ] ,[ 12 . 0 ] ] )
if ( asum < = a [ i ] [ i ] ) :
continue
else :
for i in range (0 , 25 ) :
x = seidel (a , x , b )
print ( x )
# Note here that the inputs if float gives the output in float .
[[1.]
[1.]
[1.]]
Note: In the next example, the Upper triangular matrix is calculated by the numpy
function for finding lower triangular matrix. this upper triangular matrix is multiplied by
50
the chosen basis function and subtracted by the rhs B column matrix. the new x found is
the product of inverse(lower triangular matrix) and the B-UX. This program is available
on github
Example 5:
Apply Gauss-Siedel method to solve the system of equations: 5x−y−z = −3; x−5y+z =
−9; 2x + y − 4z = −15.
import numpy as np
from scipy . linalg import solve
def gauss (A , b , x , n ) :
L = np . tril ( A )
U = A - L
for i in range ( n ) :
xnew = np . dot ( np . linalg . inv ( L ) , b - np . dot (U , x ) )
x = xnew
print ( x )
# print ( x )
return x
A = np . array ( [ [ 5 .0 , - 1 .0 , - 1 . 0 ] , [ 1 .0 , - 5 .0 , 1 . 0 ] , [ 2 .0 , 1 .0 , - 4 . 0 ] ] )
b = [ - 3 .0 , - 9 .0 , - 15 . 0 ]
x = [1 , 0 , 1 ]
n = 20
gauss (A , b , x , n )
solve (A , b )
[1. 3. 5.]
array([1., 3., 5.])
9.2 Exercise:
1. Check whether the following system are diagonally dominant or not
a. 25x + y + z = 27, 2x + 10y − 3z = 9 and 4x − 2x − 12z = −10.
b. x + y + z = 7, 2x + y − 3z = 3 and 4x − 2x − z = −1.
Ans: a. Yes b. No
51
LAB 10: Compute eigenvalues and corresponding eigen-
vectors. Find dominant and corresponding eigenvec-
tor by Rayliegh power method.
10.1 Objectives:
Use python
• w(. . . , M) array
The eigenvalues, each repeated according to its multiplicity. The eigenvalues
are not necessarily ordered. The resulting array will be of complex type, unless
the imaginary part is zero in which case it will be cast to a real type. When
a is real the resulting eigenvalues will be real (0 imaginary part) or occur in
conjugate pairs.
• v(. . . , M, M) array
The normalized (unit “length”) eigenvectors, such that the column v[:,i] is the
eigenvector corresponding to the eigenvalue w[i].
• This function can have any number of arguments but only one expression,
which is evaluated and returned.
• They are are syntactically restricted to a single expression.
• Example: f=lambda x : x ∗ ∗2 − 3 ∗ x + 1 (Mathematically f (x) = x2 − 3x + 1)
52
10.2 Eigenvalues and Eigenvectors
Eigenvector of a matrix A is a vector represented by a matrix X such that when X is
multiplied with matrix A, then the direction of the resultant matrix remains same as
vector X.
Example 1:
Obtain the eigen values and eigen vectors for the given matrix.
4 3 2
1 4 1 .
3 10 4
import numpy as np
I = np . array ( [ [4 ,3 , 2 ] ,[1 ,4 , 1 ] ,[3 , 10 , 4 ] ] )
print ( " \ n Given matrix : \ n " , I )
# x = np . linalg . eigvals ( I )
w , v = np . linalg . eig ( I )
Given matrix:
[[ 4 3 2]
[ 1 4 1]
[ 3 10 4]]
Eigen values:
[8.98205672 2.12891771 0.88902557]
Eigen vectors:
[[-0.49247712 -0.82039552 -0.42973429]
[-0.26523242 0.14250681 -0.14817858]
[-0.82892584 0.55375355 0.89071407]]
Eigen value:
8.982056720677654
53
Example 2:
Obtain the eigen values and eigen vectors for the given matrix.
1 −3 3
A = 3 −5 3 .
6 −6 4
import numpy as np
I = np . array ( [ [1 , -3 , 3 ] ,[3 , -5 , 3 ] ,[6 , -6 , 4 ] ] )
w , v = np . linalg . eig ( I )
Given matrix:
[[ 1 -3 3]
[ 3 -5 3]
[ 6 -6 4]]
Eigen values:
[ 4.+0.00000000e+00j -2.+1.10465796e-15j -2.-1.10465796e-15j]
Eigen vectors:
[[-0.40824829+0.j 0.24400118-0.40702229j 0.24400118+0.40702229j]
[-0.40824829+0.j -0.41621909-0.40702229j -0.41621909+0.40702229j]
Example 4:
6 −2 2
Compute the numerically largest eigenvalue of P = −2 3 −1 by power method.
2 −1 3
import numpy as np
def normalize ( x ) :
fac = abs ( x ) . max ()
x_n = x / x . max ()
54
return fac , x_n
x = np . array ( [1 , 1 , 1 ] )
a = np . array ( [ [6 , -2 , 2 ] ,
[ -2 ,3 , - 1 ] ,[2 , -1 , 3 ] ] )
for i in range ( 10 ) :
x = np . dot (a , x )
lambda_1 , x = normalize ( x )
Eigenvalue: 7.999988555930031
Eigenvector: [ 1. -0.49999785 0.50000072]
Example 5:
1 1 3
Compute the numerically largest eigenvalue of P = 1 5 1 by power method.
3 1 1
import numpy as np
def normalize ( x ) :
fac = abs ( x ) . max ()
x_n = x / x . max ()
return fac , x_n
x = np . array ( [1 , 1 , 1 ] )
a = np . array ( [ [1 ,1 , 3 ] ,
[1 ,5 , 1 ] ,[3 ,1 , 1 ] ] )
for i in range ( 10 ) :
x = np . dot (a , x )
lambda_1 , x = normalize ( x )
Eigenvalue: 6.001465559355154
Eigenvector: [0.5003663 1. 0.5003663]
10.4 Exercise:
1. Find the eigenvalues
and eigenvectors of the following matrices
25 1
a. P =
1 3
Ans. Eigenvalues are 25.04536102 and 2.95463898; and corresponding eigenvectors
are [0.99897277 − 0.04531442] and [0.04531442 0.99897277].
25 1 2
b. P = 1 3 0
2 0 −4
Ans. Eigenvalues are 25.18215138, −4.13794129 and 2.95578991; and corresponding
55
eigenvectors are [0.9966522 0.06880398 0.04416339], [0.04493037 − 0.00963919 −
0.99894362] and [0.0683056 − 0.99758363 0.01269831].
11 1 2
c. P = 0 10 0
0 0 12
Ans. Eigenvalues are 11., 10. and 12.; and corresponding eigenvectors are [1. −
0.70710678 0.89442719], [0. 0.70710678 0.], and [0. 0. 0.4472136].
3 1 1
d. P = 1 2 1
1 1 12
Ans. Eigenvalues are 12.22971565, 3.39910684 and 1.37117751; and eigenvectors are
[−0.11865169 −0.85311963 0.50804396], [−0.10808583 −0.49752078 −0.86069189]
and [−0.98703558 0.1570349 0.03317846].
25 1 2
2. Find the dominant eigenvalue of the matrix P = 1 3 0 by power method.
2 0 −4
T
Take X0 = (1, 0, 1) .
Ans. 25.182151221680012
6 1 2
3. Find the dominant eigenvalue of the matrix P = 1 10 −1 by power method.
2 1 −4
T
Take X0 = (1, 1, 1) .
Ans. 10.107545112667367
5 1 1
4. Find the dominant eigenvalue of the matrix P = 1 3 −1 by power method.
2 −1 −4
T
Take X0 = (1, 0, 0) .
Ans. 5.544020973078026
56
Computer Science and Engineering Stream
LAB 6: Finding GCD using Euclid’s algorithm.
6.1 Objectives:
Use python
1. to find the GCD of two given integers by Euclid’s algorithm
Euclidean algorithm
is useful to find GCD of two numbers. The algorithm is as follows:
The two numbers a and b can be assumed positive such that a < b. Let r1 be the
remainder when b is divided by a. Then 0 ≤ r1 < a. That is b = ak1 + r1 .
Now let r2 be the remainder when a is divided by r1 . That is a = r1 k2 + r2 . Where
0 ≤ r2 < r1 . Continue this process of dividing each divisor by the next remainder. At
some stage we obtain remainder 0. The last non-zero remainder is the GCD of a
and b. This is known as Euclid’s algorithm.
Algorithm analysis:
1. Recursive process - operations are repeated till stopping criterion is reached
2. The output of one step is used as the input of the next step.
Example 1:
Find the GCD of (614,124).
"""
The function is named " gcd1 " , which takes as inputs two numbers :
1 . 'a ', and
2 . 'b '
where , a < b .
In case the first number is larger than the second number , the function
will interchange the numerals . The answer however remains unchanged .
"""
def gcd1 (a , b ) :
c = 1 # Assume non - zero remainder
if b < a : # Preprocessing of input
t = b # Temporary variable 't ' used to swap values of 'a ' and '
b'
b = a
a = t
while ( c > 0 ) : # Condition checked : Is the remainder non - zero ?
c = b%a
print (a , c ) # Display divisor and remainder
b = a
57
a = c
continue # This command gets activated whenever ' while ' is TRUE
"""
At this stage , ' while ' loop no longer works because 'c > 0 ' is
FALSE .
Remainders can 't be negative , so the
"""
print ( ' GCD = ' ,b )
gcd1 ( 614 , 124 )
124 118
118 6
6 4
4 2
2 0
GCD = 2
Relatively prime
Two numbers a and b are called relatively prime or co-prime if their GCD (also known
as HCF) is equal to 1.
For example: 2 and 19 are relatively prime, because 1 is the largest natural number
that divides both 2 and 19.
Example 2:
Prove that 163 and 512 are relatively prime.
def gcd1 (a , b ) :
c=1;
if b < a :
t=b;
b=a;
a=t;
while ( c > 0 ) :
c=b%a;
print (a , c ) ;
b=a;
a=c;
continue
print ( ' GCD = ' ,b ) ;
gcd1 ( 163 , 512 )
163 23
23 2
2 1
1 0
GCD= 1
58
Divides
If GCD of a and b is a, then a divides b.
Note that when GCD(a, b) = a is equivalent to the statement a is that the largest
natural number that divides both a and b.
For example: The GCD of 4 and 8 is 4, as 4 is the largest number that divides both
4 and 8. Since 4 is one of the given numbers, 4 divides 8.
Example 4:
Prove that 8 divides 128.
def gcd1 (a , b ) :
c=1;
if b < a :
t=b;
b=a;
a=t;
while ( c > 0 ) :
c=b%a;
print (a , c ) ;
b=a;
a=c;
continue
print ( ' GCD = ' ,b ) ;
gcd1 (8 , 128 )
8 0
GCD= 8
Example 5:
Calculate GCD of (a,b) and express it as linear combination of a and b. Calculate GCD=d
of 76 and 13 , express th GCD as 76x + 13y = d
from sympy import *
a = int ( input ( ' enter the first number : ') )
b = int ( input ( ' enter the second number : ') )
s1 = 1 ;
s2 = 0 ;
t1 = 0 ;
t2 = 1 ;
r1 = a ;
r2 = b ;
r3 = ( r1 % r2 ) ;
q = ( r1 - r3 ) / r2 ;
s3 = s1 - s2 * ( q ) ;
t3 = t1 - t2 * q ;
while ( r3 ! = 0 ) :
r1 = r2 ;
r2 = r3 ;
s1 = s2 ;
59
s2 = s3 ;
t1 = t2 ;
t2 = t3 ;
r3 = ( r1 % r2 ) ;
q = ( r1 - r3 ) / r2 ;
s3 = s1 - s2 * ( q ) ;
t3 = t1 - t2 * q ;
print ( ' the GCD of ' ,a , ' and ' ,b , ' is ' , r2 ) ;
print ( '% d x % d + % d x % d = % d \ n '% (a , s2 ,b , t2 , r2 ) ) ;
Note:
SymPy is a Python library for symbolic mathematics and has an inbuilt command for
GCD.
The functions gcd and igcd can be imported to compute the GCD of numbers.
from sympy import gcd
gcd ( 1235 , 2315 )
6.2 Exercise:
1. Find the GCD of 234 and 672 using Euclidean algorithm.
Ans: 6
2. What is the largest number that divides both 1024 and 1536?
Ans: 512
60
5. Are 9797 and 7979 coprime?
Ans: No, their gcd is 101
6. Write a function in Python to compute the greatest common divisor of 15625 and
69375.
Alternate tip: SymPy is a library (module) providing gcd function
Advanced tip: from sympy.abc import x allows to find GCD of algebraic ex-
pressions.
61
LAB 7: Solving linear congruence of the form ax ≡
b( mod m).
7.1 Objectives:
Use python
Example 1:
Show that the linear congruence 6x ≡ 5( mod 15) has no solution.
from sympy import *
from math import * 5
enter integer a 6
enter integer b 5
enter integer m 15
the congruence has no integer solution
Example 2:
Find the solution of the congruence 5x ≡ 3(mod 13).
from sympy import *
# Linear congruence
# Consider ax = b ( mod m ) ,x is called the solution of the congrunce
62
if ( x // 1 = = x ) : # check whether x is an integer
print ( ' the solution of the congruence is ' , x )
break
enter integer a 5
enter integer b 3
enter integer m 13
the solution of the congruence is 11.0
Note:
The solution of the congruence ax ≡ 1(mod p) is called multiplicative inverse of a mod p.
Example 4:
Find the inverse of 5 mod 13.
from sympy import gcd
# Linear congruence
# Consider ax = b ( mod m ) ,x is called the solution of the congrunce
enter integer a 5
enter integer b 1
enter integer m 13
the solution of the congruence is 8.0
7.2 Exercise:
1. Find the solution of the congruence 12x ≡ 6( mod 23).
Ans: 12
3. Prove that 12x ≡ 7( mod 14) has no solution. Give reason for the answer.
Ans: Because GCD(12,14)=2 and 2 doesnot divide 7.
63
Electrical & Electronics Engineering Stream
LAB 6: Programme to compute area, volume and cen-
ter of gravity
6.1 Objectives:
Use python
1. to evaluate double integration.
2. to compute area and volume.
3. to calculate center of gravity of 2D object.
2. integrate:
integrate ( function ,( variable , min_limit , max_limit ) )
1/3
Example 2:
R 3−x−y
R3 3−x R
Evaluate the integral (xyz)dzdydx
0 0 0
from sympy import *
x = Symbol ( 'x ')
y = Symbol ( 'y ')
z = Symbol ( 'z ')
w2 = integrate (( x * y * z ) ,(z ,0 , 3 - x - y ) ,(y ,0 , 3 - x ) ,(x ,0 , 3 ) )
print ( w2 )
81/80
64
Example 3:
RR 2 RR 2
Prove that (x + y 2 )dydx = (x + y 2 )dxdy
from sympy import *
x = Symbol ( 'x ')
y = Symbol ( 'y ')
z = Symbol ( 'z ')
w3 = integrate ( x ** 2 + y ** 2 ,y , x )
pprint ( w3 )
w4 = integrate ( x ** 2 + y ** 2 ,x , y )
pprint ( w4 )
Example 4:
√
Ra (b/a) R a2 −x2
Find the area of an ellipse by double integration. A=4 dydx
0 0
from sympy import *
x = Symbol ( 'x ')
y = Symbol ( 'y ')
# a = Symbol ( ' a ')
# b = Symbol ( ' b ')
a=4
b=6
w3 = 4 * integrate (1 ,( y ,0 ,( b / a ) * sqrt ( a ** 2 - x ** 2 ) ) ,(x ,0 , a ) )
print ( w3 )
24.0*pi
RR
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 sympy import *
r = Symbol ( 'r ')
t = Symbol ( 't ')
a = Symbol ( 'a ')
#a=4
65
RRR
6.4 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, xa + yb + zc = 1
from sympy import *
x = Symbol ( 'x ')
y = Symbol ( 'y ')
z = Symbol ( 'z ')
a = Symbol ( 'a ')
b = Symbol ( 'b ')
c = Symbol ( 'c ')
w2 = integrate (1 ,( z ,0 , c * ( 1 - x / a - y / b ) ) ,(y ,0 , b * ( 1 - x / a ) ) ,(x ,0 , a ) )
print ( w2 )
a*b*c/6
rad = np . arange (0 , ( 2 * np . pi ) , 0 . 01 )
66
6.6 Exercise:
R1 Rx
1. Evaluate (x + y)dydx
0 0
Ans: 0.5
log(2)
R Rx x+log(y)
R
2. Find the (ex+y+z )dzdydx
0 0 0
Ans: -0.2627
4. Find the volume of the tetrahedron bounded by the planes x=0,y=0 and z=0,
x
2
+ y3 + z4 = 1
Ans: 4
67
LAB 7: Evaluation of improper integrals, Beta and
Gamma functions
7.1 Objectives:
Use python
1. to find partial derivatives of functions of several variables.
2. to find Jacobian of fuction of two and three variables.
Parameters :
x : The number whose gamma value needs to be computed.
2. beta
math . beta (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:
R∞
Evaluate e−x dx.
0
from sympy import *
x = symbols ( 'x ')
w1 = integrate ( exp ( - x ) ,(x ,0 , float ( ' inf ') ) )
print ( simplify ( w1 ) )
1
R∞
Gamma function is x(n) = 0
e−x xn−1 dx
Example 2:
Evaluate Γ(5) by using definition
from sympy import *
x = symbols ( 'x ')
w1 = integrate ( exp ( - x ) * x ** 4 ,( x ,0 , float ( ' inf ') ) )
print ( simplify ( w1 ) )
24
68
Example 3:
R∞
Evaluate e−st cos(4t)dt . That is Laplace transform of cos(4t)
0
from sympy import *
t , s = symbols ( 't , s ')
# for infinity in sympy we use oo
w1 = integrate ( exp ( - s * t ) * cos ( 4 * t ) ,(t ,0 , oo ) )
display ( simplify ( w1 ) )
Example 4:
Find Beta(3,5), Gamma(5)
# beta and gamma functions
from sympy import beta , gamma
m = input ( 'm : ') ;
n = input ( 'n : ') ;
m = float ( m ) ;
n = float ( n ) ;
s = beta (m , n ) ;
t = gamma ( n )
print ( ' gamma ( ' ,n , ') is % 3 . 3f '% t )
print ( ' 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 sympy import beta , gamma
m = float ( input ( 'm : ') ) ;
n = float ( input ( 'n : ') ) ;
s = beta (m , n ) ;
t = gamma ( n )
print ( ' gamma ( ' ,n , ') is % 3 . 3f '% t )
print ( ' Beta ( ' ,m ,n , ') is % 3 . 3f '% s )
m : 2.5
n :3.5
gamma ( 3.5 ) is 3.323
Beta ( 2.5 3.5 ) is 0.037
69
Example 6:
Verify that Beta(m, n) = Gamma(m)Gamma(n)/Gamma(m + n) for m=5 and n=7
from sympy import beta , gamma
m=5;
n=7;
m = float ( m ) ;
n = float ( n ) ;
s = beta (m , n ) ;
t = ( gamma ( m ) * gamma ( n ) ) / gamma ( m + n ) ;
print (s , t )
if ( abs ( s - t ) < = 0 . 00001 ) :
print ( ' beta and gamma are related ')
else :
print ( ' given values are wrong ')
0.000432900432900433 0.000432900432900433
beta and gamma are related
7.2 Exercise:
R∞
1. Evaluate e−t cos(2t)dt
0
Ans: 1/5
70
Mechanical & Civil Engineering Stream
LAB 6: Solution of second order ordinary differential
equation and plotting the solution curve
6.1 Objectives:
Use python
Example 1:
Solve: y ′′ − 5y ′ + 6y = cos(4x).
# Import all the functions available in the SymPy library .
from sympy import *
y1 = Derivative (y , x )
y2 = Derivative ( y1 , x )
display ( diff1 )
display ( z )
# Let c1 =1 , c2 = 2
PS = z . subs ( { C1 :1 , C2 : 2 } )
print ( " \ n \ n Particular Solution :\ n " )
display ( PS )
71
Example 2:
Plot the solution curve (particular solution) of the above differential equation.
import matplotlib . pyplot as plt
import numpy as np
x1 = np . linspace (0 ,2 , 1000 )
y1 = 2 * np . exp ( 3 * x1 + np . exp ( 2 * x1 ) - np . sin ( 4 * x1 ) / 25 - np . cos ( 4 * x1 ) / 50 )
plt . plot ( x1 , y1 )
plt . title ( " Solution curve " )
plt . show ()
Example 3:
Plot the solution curves of y ′′ + 2y ′ + 2y = cos(2x), y(0) = 0, y ′ (0) = 0
We can turn this into two first-order equations by defining a new depedent variable.
For example,
z = y ′ ⇒ z ′ + 2z + 2y = cos(2x), z(0) = y(0) = 0.
y ′ = z; y(0) = 0
z ′ = cos(2x) − 2z − 2y; z(0) = 0.
import numpy as np
from scipy . integrate import odeint
import matplotlib . pyplot as plt
def dU_dx (U , x ) :
# Here U is a vector such that y = U [ 0 ] and z = U [ 1 ]. This function
should return [ y ', z ']
return [ U [ 1 ] , - 2 * U [ 1 ] - 2 * U [ 0 ] + np . cos ( 2 * x ) ]
U0 = [0 , 0 ]
xs = np . linspace (0 , 10 , 200 )
Us = odeint ( dU_dx , U0 , xs )
Example 4:
2
Solve: 3 ddt2x + 2 dx
dt
− 2x = cos(2x) with x(0) = 0; x′ (0) = 0 and plot the solution curve.
72
import numpy as np
from scipy . integrate import odeint
import matplotlib . pyplot as plt
def f (u , x ) :
return ( u [ 1 ] ,- 2 * u [ 1 ] + 2 * u [ 0 ] + np . cos ( 2 * x ) )
y0 = [0 , 0 ]
xs = np . linspace (1 , 10 , 200 )
us = odeint (f , y0 , xs )
ys = us [ : ,0 ]
6.2 Exercise:
1. An object weighs 2 kg stretches a spring 6 m. The spring is then released from
the equilibrium position with an upward velocity of 16 m/sec. The motion of the
object is denoted by x′′ + (82 )x = 0 where ω = 8 is the angular frequency. Find
x(t) using initial conditions x(0) = 0 and x′ (0) = −16 and plot the solution.
Ans: x(t) = −2 sin(8t)
Sketch of all solutions in this exercise: Note that x(t) = c1 cos(8t) + c2 sin(8t),
where c1 = x(0) = 0 and c2 = x′ (0) = −16.
Hint: Use from scipy.integrate import odeint and check the first column of
the simulation result.
2. The mass of 16 kg stretches a spring by 89 such that there is no damping and no exter-
nal forces acting on the system. The spring is initially displaced 6 inches upwards
from its equilibrium position and given an initial velocity of 1 ft/sec downward.
Find the displacement at any time t, u(t) denoted by the second order differential
1 d2 1
equation 2
u(t) + 18u(t) = 0 with initial conditions u(0) = − and u′ (0) = 1
2 dt 2
and plot the solution curve.
Ans: u(t) = − 12 cos(6t) + 61 sin(6t)
https://tutorial.math.lamar.edu/classes/de/Vibrations.aspx
73
1 1 1
Ans: 200
cos(10t) + 200
sin(10t) + 20
cos(10t)
https://www.sjsu.edu/me/docs/hsu-Chapter%208%20Second%20order%20DEs_04-25-19.
pdf
74
LAB 7: Solution of differential equation of oscillations
of a spring with various load
7.1 Objectives:
Use python
Example 1:
d2 x
Solve dt2
+ 64x = 0, x(0) = 14 , x′ (0) = 1 and plot the solution curve.
import numpy as np
from scipy . integrate import odeint
import matplotlib . pyplot as plt
def f (u , x ) :
return ( u [ 1 ] ,- 64 * u [ 0 ] )
y0 = [ 1 /4 , 1 ]
xs = np . linspace (0 ,5 , 50 )
us = odeint (f , y0 , xs )
ys = us [ : ,0 ]
print ( ys )
plt . plot ( xs , ys , 'r - ')
75
Example 2:
2
Solve 9 ddt2x + 2 dx
dt
+ 1.2x = 0, x(0) = 1.5, x′ (0) = 2.5 and plot the solution curve.
import numpy as np
from scipy . integrate import odeint
import matplotlib . pyplot as plt
def f (u , x ) :
return ( u [ 1 ] ,- ( 1 / 9 ) * ( 1 . 2 * u [ 1 ] + 2 * u [ 0 ] ) )
y0 = [ 2 .5 , 1 . 5 ]
xs = np . linspace (0 , 20 * np . pi , 2000 )
us = odeint (f , y0 , xs )
print ( us )
ys = us [ : ,0 ]
7.2 Exercise:
1. An object weighs 2 kg stretches a spring 6 m. The spring is then released from
the equilibrium position with an upward velocity of 16 m/sec. The motion of the
object is denoted by x′′ + (82 )x = 0 where ω = 8 is the angular frequency. Find
x(t) using initial conditions x(0) = 0 and x′ (0) = −16 and plot the solution.
Ans: x(t) = −2 sin(8t)
Sketch of all solutions in this exercise: Note that x(t) = c1 cos(8t) + c2 sin(8t),
where c1 = x(0) = 0 and c2 = x′ (0) = −16.
Hint: Use from scipy.integrate import odeint and check the first column of
the simulation result.
2. The mass of 16 kg stretches a spring by 89 such that there is no damping and no exter-
nal forces acting on the system. The spring is initially displaced 6 inches upwards
from its equilibrium position and given an initial velocity of 1 ft/sec downward.
Find the displacement at any time t, u(t) denoted by the second order differential
1 d2 1
equation 2
u(t) + 18u(t) = 0 with initial conditions u(0) = − and u′ (0) = 1
2 dt 2
and plot the solution curve.
Ans: u(t) = − 12 cos(6t) + 61 sin(6t)
https://tutorial.math.lamar.edu/classes/de/Vibrations.aspx
76