Lab Manual - Master Copy-CSE BMATS201
Lab Manual - Master Copy-CSE BMATS201
Offering Department
DEPARTMENT OF MATHEMATICS
Beneficiary Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
(Accredited by NBA)
MASTER MANUAL
Course: MATHEMATICS II FOR CSE STREAM
Course Code: BMATS201
II SEMESTER
Prepared By:
Mrs. Vilma D’Souza
Assistant Professor
Department of Mathematics
Scheme: 2022
A J INSTITUTE OF ENGINEERING & TECHNOLOGY
(A unit of Laxmi Memorial Education Trust. (R))
NH - 66, Kottara Chowki, Kodical Cross - 575 006
Vision
To produce top-quality engineers who are groomed for attaining excellence in their
profession and competitive enough to help in the growth of nation and global society.
Mission
To offer affordable high-quality graduate program in engineering with value
education and make the students socially responsible.
To support and enhance the institutional environment to attain research excellence
in both faculty and students and to inspire them to push the boundaries of
knowledge base.
To identify the common areas of interest amongst the individuals for the effective
industry- institute partnership in a sustainable way by systematically working
together.
To promote the entrepreneurial attitude and inculcate innovative ideas among the
engineering professionals.
Program Outcome
PO1: Engineering knowledge Apply the knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering problems.
PO2: Problem Analysis Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
science and engineering sciences.
PO3: Design/development of solutions Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal and environmental considerations.
PO4: Conduct investigations of complex problems Use research based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern tool usage: create, select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment sustainability Understand the impact of the professional engineering solutions in
the societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and team work Function effectively as an individual and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10: Communication communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear instructions
PO11: Project management and finance Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO12: Lifelong learning recognize the need for, and have the preparation and ability to engage in
independent and lifelong learning in the broader context of technological change.
Mathematics-II for CSE Stream
(Effective from the academic year 2022 -2023)
SEMESTER – II
Hours/Week
(L:T:P:S)
Course objectives: The goal of the course Mathematics-II for ECE stream (BMATE201) is
Importance of numerical methods for discrete data in the field of computer science &
engineering.
Solution of algebraic and transcendental equations - Regula-Falsi and Newton-Raphson methods
(only formulae). Problems.
Finite differences, Interpolation using Newton’s forward and backward difference formulae,
Newton’s divided difference formula and Lagrange’s interpolation formula (All formulae
without proof). Problems.
Numerical integration: Trapezoidal, Simpson's (1/3)rd and (3/8)th rules (without proof).
Problems.
Course outcomes :
At the end of the course the student will be able to :
CO1: Apply the concept of change of order of integration and variables to evaluate multiple
integrals and their usage in computing area and volume
CO2: Understand the applications of vector calculus refer to solenoidal, and irrotational vectors.
Orthogonal curvilinear coordinates
CO3: Demonstrate the idea of Linear dependence and independence of sets in the vector space, and
linear transformation
CO4 Apply the knowledge of numerical methods in modelling of various physical and engineering
phenomena
CO5: Solve first order ordinary differential equations arising in engineering problems.
1. http://nptel.ac.in/courses.php?disciplineID=111
2. http://www.class-central.com/subject/math(MOOCs)
3. http://academicearth.org/
4. VTU e-Shikshana Program
5. VTU EDUSAT Program
9) Solution of ODE of first order and first degree by Taylor’s series and
Modified Euler’s method
10) Solution of ODE of first order and first degree by Runge-Kutta 4th order
and Milne’s predictor-corrector method
Instructions to students
Students should report to the concerned labs as per the given timetable. Be regular to the Lab Do
not come late to the Lab
Students should make an entry in the log book whenever they enter the labs during practical.
Students must bring Observation book, record and manual along with pen, pencil, and eraser Etc.,
no borrowing from others.
Students must use the computers carefully, as they are expensive. Each person may only use one
computer at a time
Any damage to the lab computers will be viewed seriously.
Students may not install software on lab computers. If you have a question regarding specific
software that you need to use, contact the concerned Faculty and Labs support team.
When the experiment is completed, students should shut down the computers and make the counter
entry in the logbook
Wear your College ID card
Avoid unnecessary talking while doing the experiment
Do not panic if you do not get the output
Students should not leave the lab without concerned faculty’s permission.
Before leaving the lab, students should check whether they have switched off the computers and
the power supplies and kept their chairs properly.
Rules for Maintaining Record
Write your name, USN and name of the subject on the outside front cover of the record. Write the
same information in the first page inside the cover page.
Update Table of Contents every time you start each new experiment or topic.
Always use pen and write neatly and clearly
Start each new topic (experiment, notes, calculation, etc.) on a right-side (odd numbered) page
Obvious care should be taken to make it readable, even if you have bad handwriting
Date to be written on every page on the top right-side corner
On each right-side page
Title of experiment
Aim/Objectives
Theory
Procedure described clearly in steps
Result
On each left side page
Diagrams
Tables
Graphs
Use labels and captions for figures and tables
Attach printouts and plots of data as needed. Stick printouts (A4 Size) on the right side of the lab
record
Strictly observe the instructions given by the Teacher/ Lab Instructor.
Introduction
WHAT IS PYTHON?
Python is a computer programming language. It is a high-level general purpose scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages. Beginner-
level language that supports development of wide range of applications.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
Guido van Rossum (1987) named it after the BBC television show ‘Monty Python’s Flying
Circus.’ (Comedy show).
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
JUPYTER NOTEBOOK
The notebook extends the console-based approach to interactive computing in a
qualitatively new direction, providing a web-based application suitable for capturing
the whole computation process: developing, documenting, and executing code, as
well as communi-
cating the results.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use
them as constant or variable or any other identifier names. All the Python keywords contain
lowercase letters only.
assert finally or
def If return
elif in while
else is with
DATA TYPES
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
QUOTATION IN PYTHON
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are
legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
COMMENTS IN PYTHON
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to
the end of the physical line are part of the comment and the Python interpreter ignores them.
# First comment
Hello, Python!
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.
EXAMPLES:
a=2.4
x=3
y = ’a ’
z=" Hello "
p r i n t ( type ( a ) ) #type ( ) gives the data type of the v a r i a b l e .
p r i n t ( type ( x ) )
p r i n t ( type ( y ) )
p r i n t ( type ( z ) )
EXAMPLE FOR NUMERIC TYPES:
x=1#int
y = 2.8 # f l o a t
z = 1 j # complex
X = 35e3 # e i n d i c a t e s the power of 10
Y = 12E4
Z = −87.7e100
EXAMPLE FOR TEXT TYPE:
OPERATORS
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
All the common algebraic operators presented in the following table are available in Python.
Addition +
Subtraction −
Multiplication ∗
Division /
Integer Division //
Power **
Remainder %
Comparison operators:
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
! = not equal to
Logical operators:
and logical and
or logical or
not logical not
ASSIGNMENT OPERATOR
=, is used as assignment operator. For example x = 5, means 5 is stored to variable
x.
+ =. The expression a+ = 3, give the result of a = a + 3.
− =. The expression x− = 3, give the result of x = x − 3.
∗ =. The expression a∗ = 3, give the result of a = a ∗ 3.
/ =. The expression a/ = 3, give the result of a = a/3.
// =. The expression a// = 3, give the result of a = a//3.
% =. The expression a% = 3, give the result of a = a%3.
∗∗ =. The expression a∗ = 3, give the result of a = a ∗ ∗3.
IDENTITY OPERATORS
is Returns True if both variables are the same object
is not Returns True if both variables are not the same object
MEMBERSHIP OPERATORS
in Returns True if a sequence with the specified value is present in the object
not in Returns True if a sequence with the
specified value is not present in the
object
PYTHON LISTS
Python Lists are used to group related data together. They are collection of data items. Lists are used
to store multiple items in a single variable. We enclose the items with in square brackets[ ]and
separate them by commas.
Lists are created using square brackets: for example
a=[1,2,3]
Ex: list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
PYTHON TUPLES
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values.
Ex:
Basics of Python
https://drive.google.com/file/d/1gVG2IJ8BIjhYDwDx6jWJns59h9dGOGVi/view?usp=share_link
Programming Structures
Conditional structure
What is conditioning in Python?
• Based on certain conditions, the flow of execution of the program is determined using proper
syntax.
How to use if conditions?
- if statement — for implementing one-way branching
- if-else statements —for implementing two-way branching
- nested if statements —for implementing multiple branching
- if-elif ladder — for implementing multiple branching
# Syntax:
if condition:
statements
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.
1 𝑥
1. Evaluate the integral ∫0 ∫0 (𝑥 2 + 𝑦 2 )𝑑𝑦𝑑𝑥
Output
1/3
3 3−𝑥 3−𝑥−𝑦
2. Evaluate the integral ∫0 ∫0 ∫0 𝑥𝑦𝑧 𝑑𝑧𝑑𝑦𝑑𝑥
Output
81/80
3. Prove that ∫ ∫(𝑥 2 + 𝑦 2 )𝑑𝑥𝑑𝑦 = ∫ ∫(𝑦 2 + 𝑥 2 )𝑑𝑥𝑑𝑦
Output
𝑏
𝑎
4. Find the area of an ellipse by double integration. 𝐴 = 4 ∫0 ∫0𝑎
Output
24.0 pi
1.4 Area of the region R in the polar form is ∫ ∫ 𝑟𝑑𝑟𝑑𝜃
Output
3𝜋𝑎 2
2
𝑥 𝑦 𝑧
6. Find the volume of the tetrahedron bounded by the planes x=0, y=0 and z=0, 𝑎
+𝑏+𝑐 =1
Output
𝑎 ∗ 𝑏 ∗ 𝑐 ⁄6
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.
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.
∞
1.Evaluate ∫0 𝑒 −𝑥 𝑑𝑥
Output
1
∞
Gamma function is 𝛤(𝑛) = ∫0 𝑒 −𝑥 𝑥 𝑛−1 𝑑𝑥
2. Evaluate Γ(5) by using definition
from sympy import *
x= Symbol ('x')
w1= integrate (exp (-x)*x ** 4 ,(x,0, float ('inf ')))
print ( simplify (w1))
Output:
24
∞
3. Evaluate ∫0 𝑒 −𝑠𝑡 𝑐𝑜𝑠(4𝑡)𝑑𝑡
Output
Output
m :3
n :5
gamma ( 5.0 ) is 24.000
Beta ( 3.0, 5.0 ) is 0.010
Output
m : 2.5
n :3.5
gamma ( 3.5 ) is 3.323
Beta ( 2.5 3.5 ) is 0.037
Output
0.000432900432900433 0.000432900432900433
beta and gamma are related
LAB 3: Finding gradient, divergence, curl and their geometrical interpretation
1.1 Objectives:
Use python
1.Finding gradient
2. Finding divergent
3. Finding curl
1) Find gradient of 𝐹 = 𝑥 2 𝑦𝑧
#To find gradient of a scalar point function 𝑥 2 𝑦𝑧
from sympy.physics.vector import *
from sympy import var
var('x,y,z')
v=ReferenceFrame('v')
F=v[0]**2*v[1]*v[2]
G=gradient(F,v)
F=F.subs([(v[0],x),(v[1],y),(v[2],z)])
print("Given scalar function F=")
display(F)
G=G.subs([(v[0],x),(v[1],y),(v[2],z)])
print("\n Gradient of F=")
display(G)
Output:
Given vector function F=x^2yi+yz^2j+x^2zk
Divergence of F=𝑥 2 + 2𝑥𝑦 + 𝑧 2
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
import numpy as np
from scipy.linalg import null_space
# Define a linear transformation interms of matrix
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Find the rank of the matrix A
rank = np.linalg.matrix_rank(A)
print("Rank of the matrix",rank)
# Find the null space of the matrix A
ns = null_space(A)
print("Null space of the matrix",ns)
# Find the dimension of the null space
nullity = ns.shape[1]
print("Null space of the matrix",nullity)
# Verify the rank-nullity theorem
if rank + nullity == A.shape[1]:
print("Rank-nullity theorem holds.")
else:
print("Rank-nullity theorem does not hold.")
import 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
basis = np.linalg.matrix_rank(V)
dimension = V.shape[0]
print("Basis of the matrix",basis)
print("Dimension of the matrix",dimension)
import numpy as np
array = np.array([[ 1, 1, 0], [ 0, 0, 0], [ 0, 2, 3], [ 0, 0, 0], [ 0, -1, 1], [ 0, 0, 0]])
print("Original array:")
print(array)
temp = {(0, 0, 0)}
result = []
for idx, row in enumerate(map(tuple, arra)):
if row not in temp:
result.append(idx)
print("\nNon-zero unique rows:")
print(arra[result])
Horizontal stretch:
Represent the horizontal stretch transformation geometrically T:R2→ 𝑅 2 geometrically
Find the image of the vector (10,0) when it is stretched horizontally by 2 units
import numpy as np
import matplotlib . pyplot as plt
V = np. array ([[10 ,0]])
origin = np. array ([[0, 0, 0],[0, 0, 0]]) # origin point
A=np. matrix ([[2,0],[0,1]])
V1=np. matrix (V)
V2=A*np. transpose (V1)
V2=np. array (V2)
plt . quiver (*origin , V[:,0], V[:,1], color =['b'], scale =50)
plt . quiver (*origin , V2[0,:], V2[1,:], color =['r'], scale =50)
plt . show ()
Output:
Reflection:
Represent the reflection transformation T : 𝑅 2 → 𝑅 2 geometrically.
import numpy as np
import matplotlib . pyplot as plt
V = np. array ([[10 ,0]])
origin = np. array ([[0, 0, 0],[0, 0, 0]]) # origin point
A=np. matrix ([[-1,0],[0,1]])
V1=np. matrix (V)
V2=A*np. transpose (V1)
V2=np. array (V2)
plt . quiver (*origin , V[:,0], V[:,1], color =['b'], scale =50)
plt . quiver (*origin , V2[0,:], V2[1,:], color =['r'], scale =50)
plt . show ()
Output:
Rotation:
Represent the rotation transformation T: 𝑅 2 → 𝑅 2 geometrically.
Find the image of vector (10, 0) when it is rotated by π/2 radians.
import numpy as np
import matplotlib . pyplot as plt
V = np. array ([[10 ,0]])
origin = np. array ([[0, 0, 0],[0, 0, 0]]) # origin point
A=np. matrix ([[0,-1],[1,1]])
V1=np. matrix (V)
V2=A*np. transpose (V1)
V2=np. array (V2)
plt . quiver (*origin , V[:,0], V[:,1], color =['b'], scale =50)
plt . quiver (*origin , V2[0,:], V2[1,:], color =['r'], scale =50)
plt . show ()
Output:
Shear Transformation
import numpy as np
import matplotlib . pyplot as plt
V = np. array ([[2,3]])
origin = np. array ([[0, 0, 0],[0, 0, 0]]) # origin point
A=np. matrix ([[1,2],[0,1]])
V1=np. matrix (V)
V2=A*np. transpose (V1)
V2=np. array (V2)
print (" Image of given vectors is:", V2)
plt . quiver (*origin , V[:,0], V[:,1], color =['b'], scale =20)
plt . quiver (*origin , V2[0,:], V2[1,:], color =['r'], scale =20)
plt . show ()
Output:
Composition
Find the image of vector (10, 0) when it is rotated by π/2 radians then stretched horizontally
2 units.
import numpy as np
import matplotlib . pyplot as plt
V = np. array ([[2,3]])
origin = np. array ([[0, 0, 0],[0, 0, 0]]) # origin point
A=np. matrix ([[0,-1],[1,0]])
B=np. matrix ([[2,0],[0,1]])
V1=np. matrix (V)
V2=A*np. transpose (V1)
V3=B*V2
V2=np. array (V2)
V3=np. array (V3)
print (" Image of given vectors is:", V3)
plt . quiver (*origin , V[:,0], V[:,1], color =['b'], scale =20)
plt . quiver (*origin , V2[0,:], V2[1,:], color =['r'], scale =20)
plt . quiver (*origin , V3[0,:], V3[1,:], color =['g'], scale =20)
plt . title ('Blue = original , Red = Rotated ,Green = Rotated + Streached ')
plt . show ()
Output:
Exercise:
1. Verify the rank nullity theorem for the following linear transformation
a) T: 𝑅 2 → 𝑅 3 defined by T(x, y) = (x + 4y, 2x + 5y, 3x + 6y).
Ans: Rank=2, Nullity=1, RNT verified
b) T: 𝑅 3 → 𝑅 4 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
1. Find the inner product of the vectors (2, 1, 5, 4) and (3, 4, 7, 8).
import numpy as np
# initialize arrays
A = np. array ([2, 1, 5, 4])
B = np. array ([3, 4, 7, 8])
#dot product
output = np. dot(A, B)
print ( output )
Output : 77
import numpy as np
# initialize arrays
A = np. array ([2, 1, 5, 4])
B = np. array ([3, 4, 7, 8])
#dot product
output = np. dot(A, B)
print ('Inner product is :',output )
if output ==0:
print ('given vectors are orthognal ')
else :
print ('given vectors are not orthognal ')
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
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.
Find a root of the equation 3x = cos x+1, near 1, by Newton Raphson method. Perform
5 iterations
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
Ans: 0.853
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.Given f(40)=184, f(50)=204, f(60)=226, f(70)=250, f(80)=276, f(90)=304, find f(38) and f(85)
using Newton’s forward interpolation method.
import numpy as np
# Given data points
x = np.array([40, 50, 60, 70, 80, 90])
y = np.array([184, 204, 226, 250, 276,304])
coefficients = np.polyfit(x, y, deg=len(x) - 1)
def interpolate(x_val):
return np.polyval(coefficients, x_val)
x_val_1 = 38
x_val_2 = 85
f_val_1 = interpolate(x_val_1)
f_val_2 = interpolate(x_val_2)
print("f(38) =", round(f_val_1,4)
print("f(85) =", round(f_val_2,4)
ANS:
f(38) = 180.24
f(85) = 289.75
2. Use Newtons interpolation to obtain the interpolating polynomial and hence cal-
culate y(8) for the following data:
import numpy as np
# Given data points
x = np.array([1, 3, 5, 7, 9])
y = np.array([6, 10, 62, 210,502])
coefficients = np.polyfit(x, y, deg=len(x) - 1)
def interpolate(x_val):
return np.polyval(coefficients, x_val)
x_val_1 = 8
f_val_1 = interpolate(x_val_1)
print("f(8) =", round(f_val_1,4))
7.2 Exercise:
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:3456789
y : 4.8 8.4 14.5 23.6 36.2 52.8 73.9
Ans: 3.1 and 100
LAB 8: Computation of area under the curve using Trapezoidal, Simpson’s 1/3rd
and simpson’s 3/8th rule
8.1 Objectives:
Use python
1. to find area under the curve represented by a given function using Trapezoidal rule.
2. to find area under the curve represented by a given function using Simpson’s 1/3rd rule.
3. to find area under the curve represented by a given function using Simpson’s 3/8th rule.
4. to find the area below the curve when discrete points on the curve are given.
# Trapezoidal Rule
from sympy import *
x=Symbol('x')
g=input('Enter the function \t')
f=lambdify(x,g)
a=float(input('Enter lower limit \t'))
b=float(input('Enter upper limit \t'))
n=int(input('Enter the number of sub intervals'))
h=(b-a)/n
I=f(a)+f(b)
for j in range (1,n):
i=a+j*h
I=I+2*f(i)
I=(h/2)*I
print('Value of the integration corrected to four decimal places is', round(I, 4)))
Output:
Enter the function 1/(1+x**2)
Enter lower limit 0
Enter upper limit 1
Enter the number of sub intervals10
Value of the integration corrected to four decimal places is 0.785
I=f(a)+f(b)
print('Value of the integration corrected to four decimal places is', round(I, 4))
Output:
Enter the function 1/(1+x**2)
Enter lower limit 0
Enter upper limit 1
Enter the number of sub intervals 10
Value of the integration corrected to four decimal places is 0.7854
8.4 Simpson’s 3/8th rule
5 1
Evaluate ∫0 1+𝑥 2
using Simpson’s 3/8th rule, taking 6 sub intervals.
I=f(a)+f(b)
print('Value of the integration corrected to four decimal places is, round(I, 4))
Output:
Enter the function 1/(1+x**2)
Enter lower limit 0
Enter upper limit 1
Enter the number of sub intervals 6
Value of the integration corrected to four decimal places is 0.7854
8.5 Exercise:
1 𝑥2
1. Evaluate the integral ∫0 1+𝑥3 𝑑𝑥 using Simpson’s 1/3rd Rule
Ans: 0.23108
0.6 2
2. Use Simpson’s 3/8th ∫0 𝑒 −𝑥 𝑑𝑥 rule to find by taking seven ordinates.
Ans: 0.5351
𝜋
3. Evaluate using trapezoidal rule ∫0 𝑠𝑖𝑛2 𝑥𝑑𝑥Take n = 6.
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
Estimate the volume of the solid formed using Simpson’s 1/3rd rule.
1
Hint: Required volume is ∫0 𝑦 2 ∗ 𝜋𝑑𝑥 **[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.
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.
𝑑𝑦
1.From Taylor series method find y(0.1) for = 𝑥2 + 𝑦2 at x=0.1,0.2 given
𝑑𝑥
𝑥0 = 0, 𝑦0 = 1 upto third degree.
b) Taylor's series method to solve dy/dx=x+y at x= 1.1, 1.2 given x0=1,y0=0 up to the third degree
terms
ANS :
ANS :
y( 0.2 ) = 0.8
The 1 th improved value of y( 0.2 ) = 0.856
The 2 th improved value of y( 0.2 ) = 0.8467
The 3 th improved value of y( 0.2 ) = 0.8483
y( 0.4 ) = 0.7444
The 1 th improved value of y( 0.4 ) = 0.7809
The 2 th improved value of y( 0.4 ) = 0.7754
The 3 th improved value of y( 0.4 ) = 0.7762
y( 0.6 ) = 0.7357
The 1 th improved value of y( 0.6 ) = 0.7618
The 2 th improved value of y( 0.6 ) = 0.7579
The 3 th improved value of y( 0.6 ) = 0.7585
y( 0.8 ) = 0.7635
The 1 th improved value of y( 0.8 ) = 0.7827
The 2 th improved value of y( 0.8 ) = 0.7797
The 3 th improved value of y( 0.8 ) = 0.7802
y( 1.0 ) = 0.8185
The 1 th improved value of y( 1.0 ) = 0.8323
The 2 th improved value of y( 1.0 ) = 0.83
The 3 th improved value of y( 1.0 ) = 0.8304
9.4 Exercise:
LAB 10: Solution of ODE of first order and first degree 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.
1.Apply the Runge Kutta method to find the solution of dy/dx = 1 + (y/x) at 0.4 by taking
h = 0.2. Given that y(1) = 2.
2. Runge - Kutta fourth order method to solve dy/dx=3*x + y/2at x=0.2(0.2)0.4 given x0=0,y0=1
ANS:
𝑑𝑦
Apply Milne’s predictor and corrector method to solve 𝑑𝑥 = 𝑥 − 𝑦 2 . Given that y(0)=0,
y(0.2)=0.02, y(0.4)=0.0795, y(0.6)=0.1762. compute y(0.8).
ANS:
yp4 = 0.3049139653333334
fp4 = 0.7070274737447028
yc4 = 0.30460143091631353
f4 = 0.7072179682837343
yc4 = 0.30461413055224895
10.4 Exercise: