ISE-NEW-Lab Manual Engineering Maths 2 VTU-51-97
ISE-NEW-Lab Manual Engineering Maths 2 VTU-51-97
Lab 7. Interpolation /Extrapolation using Newton’s forward and backward difference for-
y values from Runge -Kutta method: [0. 0.02 0.08 0.18 0.3 ] mula
predicted value of y4 0.3042133333333334 rd
corrected value of y4 , iteration 1 0.3047636165214815 Lab 8. Computation of area under the curve using Trapezoidal, Simpson’s 13 and Simp-
th
sons 38
corrected value of y4 , iteration 2 0.3047412758696499 rule
corrected value of y4 , iteration 3 0.3047421836520892
Lab 9. Solution of ODE of first order and first degree by Taylor’s series and Modified
Euler’s method
10.4 Exercise:
Lab 10. Solution of ODE of first order and first degree by Runge-Kutta 4th order method
1. Find y(0.1) by Runge Kutta method when y ′ = x − y 2 , y(0) = 1.
and Milne’s predictor and corrector method
Ans: y(0.1) = 0.91379
50 51
LAB 1: Programme to compute area, volume and cen- Example 3:
ter of gravity
RR 2
(x + y 2 )dydx =
RR 2
Prove that (x + y 2 )dxdy
from sympy import *
1.1 Objectives: x = Symbol ( 'x ')
y = Symbol ( 'y ')
Use python z = Symbol ( 'z ')
w3 = integrate ( x ** 2 + y ** 2 ,y , x )
1. to evaluate double integration. pprint ( w3 )
w4 = integrate ( x ** 2 + y ** 2 ,x , y )
2. to compute area and volume. pprint ( w4 )
pprint ()
Example 4:
√
Ra (b/a) R a2 −x2
2. integrate:
Find the area of an ellipse by double integration. A=4 dydx
integrate ( function ,( variable , min_limit , max_limit ) ) 0 0
from sympy import *
x = Symbol ( 'x ')
y = Symbol ( 'y ')
1.2 Double and triple integration # a = Symbol ( ' a ')
# b = Symbol ( ' b ')
Example 1:
a=4
R1 Rx b=6
Evaluate the integral (x2 + y 2 )dydx w3 = 4 * integrate (1 ,( y ,0 ,( b / a ) * sqrt ( a ** 2 - x ** 2 ) ) ,(x ,0 , a ) )
0 0 print ( w3 )
from sympy import *
x ,y , z = symbols ( 'x y z ')
w1 = integrate ( x ** 2 + y ** 2 ,( y ,0 , x ) ,(x ,0 , 1 ) ) 24.0*pi
print ( w1 )
RR
1.4 Area of the region R in the polar form is rdrdθ
1/3 R
Example 5:
Example 2:
Find the area of the cardioid r = a(1 + cosθ) by double integration
R 3−x−y
R3 3−x R
Evaluate the integral (xyz)dzdydx from sympy import *
0 0 0 r = Symbol ( 'r ')
from sympy import * t = Symbol ( 't ')
x = Symbol ( 'x ') a = Symbol ( 'a ')
y = Symbol ( 'y ') #a=4
z = Symbol ( 'z ')
w2 = integrate (( x * y * z ) ,(z ,0 , 3 - x - y ) ,(y ,0 , 3 - x ) ,(x ,0 , 3 ) ) w3 = 2 * integrate (r ,( r ,0 , a * ( 1 + cos ( t ) ) ) ,(t ,0 , pi ) )
print ( w2 ) pprint ( w3 )
81/80
52 53
RRR
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, 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
1.7 Exercise:
1.6 Center of Gravity R1 Rx
1. Evaluate (x + y)dydx
Find the center of gravity of cardioid . Plot the graph of cardioid and mark the center 0 0
of gravity. Ans: 0.5
log(2)
R Rx x+log(y)
import numpy as np
(ex+y+z )dzdydx
R
import matplotlib . pyplot as plt 2. Find the
0 0 0
import math
Ans: -0.2627
from sympy import *
r = Symbol ( 'r ')
t = Symbol ( 't ')
3. Find the area of positive quadrant of the circle x2 + y 2 = 16
a = Symbol ( 'a ') Ans: 4π
I1 = integrate ( cos ( t ) * r ** 2 ,( r ,0 , a * ( 1 + cos ( t ) ) ) ,(t , - pi , pi ) )
I2 = integrate (r ,( r ,0 , a * ( 1 + cos ( t ) ) ) ,(t , - pi , pi ) ) 4. Find the volume of the tetrahedron bounded by the planes x=0,y=0 and z=0,
I = I1 / I2
x
2
+ y3 + z4 = 1
print ( I ) Ans: 4
I = I . subs (a , 5 )
plt . axes ( projection = ' polar ')
a=5
rad = np . arange (0 , ( 2 * np . pi ) , 0 . 01 )
5*a/6
54 55
LAB 2: Evaluation of improper integrals, Beta and Example 3:
Gamma functions Evaluate
R∞
e−st cos(4t)dt . That is Laplace transform of cos(4t)
0
2.1 Objectives: from sympy import *
t , s = symbols ( 't , s ')
Use python # for infinity in sympy we use oo
w1 = integrate ( exp ( - s * t ) * cos ( 4 * t ) ,(t ,0 , oo ) )
1. to evaluate improper integrals using Beta function. display ( simplify ( w1 ) )
2. to evaluate improper integrals using Gamma function.
Parameters : Example 4:
x : The number whose gamma value needs to be computed.
Find Beta(3,5), Gamma(5)
2. beta # beta and gamma functions
math . beta (x , y ) from sympy import beta , gamma
m = input ( 'm : ') ;
n = input ( 'n : ') ;
Parameters : m = float ( m ) ;
x ,y: The numbers whose beta value needs to be computed. n = float ( n ) ;
s = beta (m , n ) ;
3. Note: We can evaluate improper integral involving infinity by using inf. t = gamma ( n )
print ( ' gamma ( ' ,n , ') is % 3 . 3f '% t )
print ( ' Beta ( ' ,m ,n , ') is % 3 . 3f '% s )
Example 1:
R∞
Evaluate e−x dx. m :3
0
n :5
from sympy import *
x = symbols ( 'x ') gamma ( 5.0 ) is 24.000
w1 = integrate ( exp ( - x ) ,(x ,0 , float ( ' inf ') ) ) Beta ( 3.0 5.0 ) is 0.010
print ( simplify ( w1 ) )
Example 5:
1
R∞ Calculate Beta(5/2,7/2) and Gamma(5/2).
Gamma function is x(n) = 0
e−x xn−1 dx # beta and gamma functions
# If the number is a fraction give it in decimals . Eg 5 / 2 = 2 . 5
Example 2: from sympy import beta , gamma
m = float ( input ( 'm : ') ) ;
Evaluate Γ(5) by using definition n = float ( input ( 'n : ') ) ;
from sympy import * s = beta (m , n ) ;
x = symbols ( 'x ') t = gamma ( n )
w1 = integrate ( exp ( - x ) * x ** 4 ,( x ,0 , float ( ' inf ') ) ) print ( ' gamma ( ' ,n , ') is % 3 . 3f '% t )
print ( simplify ( w1 ) ) print ( ' Beta ( ' ,m ,n , ') is % 3 . 3f '% s )
24
56 57
m : 2.5 LAB 3: Finding gradient, divergent, curl and their
n :3.5
gamma ( 3.5 ) is 3.323
geometrical interpretation
Beta ( 2.5 3.5 ) is 0.037
1.1 Objectives:
Example 6: Use python
Verify that Beta(m, n) = Gamma(m)Gamma(n)/Gamma(m + n) for m=5 and n=7 1. to find the gradient of a given scalar function.
from sympy import beta , gamma
m=5; 2. to find find divergence and curl of a vector function.
n=7;
m = float ( m ) ;
n = float ( n ) ;
1.2 Method I:
s = beta (m , n ) ; To find gradient of ϕ = x2 y + 2xz − 4.
t = ( gamma ( m ) * gamma ( n ) ) / gamma ( m + n ) ;
print (s , t ) # To find gradient of scalar point function .
if ( abs ( s - t ) < = 0 . 00001 ) : from sympy . vector import *
print ( ' beta and gamma are related ') from sympy import symbols
else : N = CoordSys3D ( 'N ') # Setting the coordinate system
print ( ' given values are wrong ') x ,y , z = symbols ( 'x y z ')
A = N . x ** 2 * N . y + 2 * N . x * N . z - 4 # Variables x ,y , z to be used with coordinate
system N
0.000432900432900433 0.000432900432900433 delop = Del () # Del operator
beta and gamma are related display ( delop ( A ) ) # Del operator applied to A
gradA = gradient ( A ) # Gradient function is used
print ( f " \ n Gradient of { A } is \ n " )
2.2 Exercise: display ( gradA )
R∞
1. Evaluate e−t cos(2t)dt
0
Ans: 1/5
58 59
To find divergence of F⃗ = x2 y î + yz 2 ĵ + x2 z k̂.
To find curl of F⃗ = x2 yz î + y 2 zxĵ + z 2 xy k̂ # To find divergence of F = x ^ 2yi + yz ^ 2j + x ^ 2zk
# To find curl of a vector point function from sympy . physics . vector import *
from sympy . vector import * from sympy import var
from sympy import symbols var ( 'x ,y , z ')
N = CoordSys3D ( 'N ') v = ReferenceFrame ( 'v ')
x ,y , z = symbols ( 'x y z ') F = v [ 0 ] ** 2 * v [ 1 ] * v . x + v [ 1 ] * v [ 2 ] ** 2 * v . y + v [ 0 ] ** 2 * v [ 2 ] * v . 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 G = divergence (F , v )
delop = Del () F = F . subs ( [ ( v [ 0 ] ,x ) ,( v [ 1 ] ,y ) ,( v [ 2 ] ,z ) ] )
curlA = delop . cross ( A ) print ( " Given vector point function is " )
display ( curlA ) display ( F )
60 61
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.4 Exercise: 1. to verify the Rank nullity theorem of given linear transformation
1. If u = x + y + z, v = x2 + y 2 + z 2 , w = yz + zx + xy, find gradu, gradv and gradw. 2. to compute the dimension of vector space
Ans: î + ĵ + k̂, 2(xî + y ĵ + z k̂), (y + z)î + (z + x)ĵ + (z + x)k̂. 3. to represent linear transformations graphically
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̂.
4.2 Rank Nullity Theorem
Verify the rank-nullity theorem for the linear transformation T : R3 → R3 defined by
3. Prove that the vector (yz − x2 )î + (4y − z 2 x)ĵ + (2xz − 4z)k̂ is solenoidal. T (x, y, z) = (x + 4y + 7z, 2x + 5y + 8z, 3x + 6y + 9z).
4. Find the vector normal to the surface xy 3 z 2 = 4 at the point (−1, −1, 2). import numpy as np
from scipy . linalg import null_space
Ans: −4î − 12ĵ + 4k̂.
# Define a linear transformation interms of matrix
⃗ = xî + y ĵ + z k̂, show that (i) ∇ · R
5. If R ⃗ = 3, (ii) ∇ × R
⃗ = 0.
A = np . array ( [ [1 , 2 , 3 ] , [4 , 5 , 6 ] , [7 , 8 , 9 ] ] )
62 63
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).
import numpy as np
Extract the linearly independent rows in given matrix : Basis of Row space Represent the horizontal stretch transformation T : R2 ßR2 geometrically
Find the image of vector (10, 0) when it is stretched horizontally by 2 units.
from numpy import *
import sympy as sp import numpy as np
A = [ [1 , -1 ,1 , 1 ] ,[2 , -5 ,2 , 2 ] ,[3 , -3 ,5 , 3 ] ,[4 , -4 ,4 , 4 ] ] import matplotlib . pyplot as plt
AB = array ( A ) V = np . array ( [ [ 10 , 0 ] ] )
S = shape ( A ) origin = np . array ( [ [0 , 0 , 0 ] ,[0 , 0 , 0 ] ] ) # origin point
n = len ( A ) A = np . matrix ( [ [2 , 0 ] ,[0 , 1 ] ] )
for i in range ( n ) : V1 = np . matrix ( V )
if AB [i , i ] = = 0 : V2 = A * np . transpose ( V1 )
ab = copy ( AB ) V2 = np . array ( V2 )
for k in range ( i +1 , S [ 0 ] ) : plt . quiver ( * origin , V [ : ,0 ] , V [ : ,1 ] , color = [ 'b '] , scale = 50 )
if ab [k , i ] ! = 0 : plt . quiver ( * origin , V2 [0 , : ] , V2 [1 , : ] , color = [ 'r '] , scale = 50 )
ab [i , : ] = AB [k , : ] plt . show ()
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 ]
display ( " REF of given matrix : " , sp . Matrix ( AB ) )
temp = { (0 , 0 , 0 , 0 ) }
result = [ ]
for idx , row in enumerate ( map ( tuple , AB ) ) :
if row not in temp :
result . append ( idx )
print ( " \ n Basis are non - zero rows of A : " )
display ( sp . Matrix ( AB [ result ] ) )
Another example.
from math import pi , sin , cos
64 65
import matplotlib . pyplot as plt 4.4.2 Reflection:
import numpy as np
Represent the reflection transformation T : R2 → R2 geometrically.
coords = np . array ( [ [0 , 0 ] ,[ 0 .5 , 0 . 5 ] ,[ 0 .5 , 1 . 5 ] ,[0 , 1 ] ,[0 , 0 ] ] ) Find the image of vector (10, 0) when it is reflected about y axis.
coords = coords . transpose ()
coords import numpy as np
x = coords [0 , : ] import matplotlib . pyplot as plt
y = coords [1 , : ] V = np . array ( [ [ 10 , 0 ] ] )
origin = np . array ( [ [0 , 0 , 0 ] ,[0 , 0 , 0 ] ] ) # origin point
A = np . array ( [ [2 , 0 ] ,[0 , 1 ] ] ) A = np . matrix ( [ [ -1 , 0 ] ,[0 , 1 ] ] )
A_coords = A@coords V1 = np . matrix ( V )
x_LT1 = A_coords [0 , : ] V2 = A * np . transpose ( V1 )
y_LT1 = A_coords [1 , : ] V2 = np . array ( V2 )
plt . quiver ( * origin , V [ : ,0 ] , V [ : ,1 ] , color = [ 'b '] , scale = 50 )
# Create the figure and axes objects plt . quiver ( * origin , V2 [0 , : ] , V2 [1 , : ] , color = [ 'r '] , scale = 50 )
fig , ax = plt . subplots () plt . show ()
# 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 ')
Another example.
B = np . array ( [ [ -1 , 0 ] ,[0 , 1 ] ] )
B_coords = B@coords
x_LT2 = B_coords [0 , : ]
y_LT2 = B_coords [1 , : ]
# 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 ')
66 67
ax . axhline ( y =0 , color = " k " , ls = " : " )
ax . grid ( True )
ax . axis ( [ -2 ,2 , -1 , 2 ] )
ax . set_aspect ( ' equal ')
ax . set_title ( " Reflection " ) ;
Another example.
theta = pi / 6
R = np . array ( [ [ cos ( theta ) ,- sin ( theta ) ] ,[ sin ( theta ) , cos ( theta ) ] ] )
R_coords = R@coords
x_LT3 = R_coords [0 , : ]
y_LT3 = R_coords [1 , : ]
# 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 ')
68 69
Another example.
S = np . array ( [ [1 , 2 ] ,[0 , 1 ] ] )
S_coords = S@coords
x_LT4 = S_coords [0 , : ]
y_LT4 = S_coords [1 , : ]
70 71
Another example.
4.4.5 Composition C = np . array ( [ [ - cos ( theta ) , sin ( theta ) ] ,[ sin ( theta ) , cos ( theta ) ] ] )
C_coords = C@coords
Represent the composition of two 2D transformations.
x_LT5 = C_coords [0 , : ]
Find the image of vector (10, 0) when it is rotated by π/2 radians then stretched hori-
y_LT5 = C_coords [1 , : ]
zontally 2 units.
import numpy as np
import matplotlib . pyplot as plt # Create the figure and axes objects
V = np . array ( [ [2 , 3 ] ] ) fig , ax = plt . subplots ()
origin = np . array ( [ [0 , 0 , 0 ] ,[0 , 0 , 0 ] ] ) # origin point
A = np . matrix ( [ [0 , - 1 ] ,[1 , 0 ] ] ) # Plot the points . x and y are original vectors , x_LT1 and y_LT1 are
B = np . matrix ( [ [2 , 0 ] ,[0 , 1 ] ] ) images
V1 = np . matrix ( V ) ax . plot (x ,y , ' ro ')
V2 = A * np . transpose ( V1 ) ax . plot ( x_LT5 , y_LT5 , ' bo ')
V3 = B * V2
V2 = np . array ( V2 ) # Connect the points by lines
V3 = np . array ( V3 ) ax . plot (x ,y , 'r ' , ls = " --" )
print ( " Image of given vectors is : " , V3 ) ax . plot ( x_LT5 , y_LT5 , 'b ')
plt . quiver ( * origin , V [ : ,0 ] , V [ : ,1 ] , color = [ 'b '] , scale = 20 )
plt . quiver ( * origin , V2 [0 , : ] , V2 [1 , : ] , color = [ 'r '] , scale = 20 ) # Edit some settings
plt . quiver ( * origin , V3 [0 , : ] , V3 [1 , : ] , color = [ 'g '] , scale = 20 ) ax . axvline ( x =0 , color = " k " , ls = " : " )
plt . title ( ' Blue = original , Red = Rotated , Green = Rotated + Streached ') ax . axhline ( y =0 , color = " k " , ls = " : " )
plt . show () ax . grid ( True )
ax . axis ( [ -2 ,2 , -1 , 2 ] )
ax . set_aspect ( ' equal ')
72 73
LAB 5: Computing the inner product and orthogo-
nality
5.1 Objectives:
Use python
# 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 )
4.5 Exercise:
1. Verify the rank nullity theorem for the following linear transformation 77
74 75
5.4 Exercise: LAB 6: Solution of algebraic and transcendental equa-
1. Find the inner product of (1, 2, 3) and (3, 4, 5). tion by Regula-Falsi and Newton-Raphson method
Ans: 26
6.1 Objectives:
2. Find the inner product of (1, −1, 2, 1) and (4, 2, 1, 0).
Use python
Ans: 4
1. to solve algebraic and transcendental equation by Regula-Falsi method.
3. Check whether the following vectors are orthogonal or not
2. to solve algebraic and transcendental equation by Newton-Raphson method.
a) (1, 1, −1) and (2, 3, 5). Ans: True
b) (1, 0, 2, 0) and (4, 2, −2, 5). Ans: True 6.2 Regula-Falsi method to solve a transcendental equation
c) (1, 2, 3, 4) and (2, 3, 4, 5) . Ans: False
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 sympy import *
x = Symbol ( 'x ')
g = input ( ' Enter the function ') # % x ^3 - 2 *x - 5 ; % function
f = lambdify (x , g )
a = float ( input ( ' Enter a valus : ') ) # 2
b = float ( input ( ' Enter b valus : ') ) # 3
N = int ( input ( ' Enter number of iterations : ') ) # 5
for i in range (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
print ( ' itration % d \ t the root % 0 . 3f \ t function value % 0 . 3f \ n '%
(i ,c , f ( c ) ) ) ;
76 77
df = lambdify (x , dg )
# Regula Falsi method while loop2 x0 = float ( input ( ' Enter the intial approximation ') ) ; # x0 = 1
from sympy import * n = int ( input ( ' Enter the number of iterations ') ) ; #n=5;
x = Symbol ( 'x ') for i in range (1 , n + 1 ) :
g = input ( ' Enter the function ') # % x ^3 - 2 *x - 5 ; % function x1 = ( x0 - ( f ( x0 ) / df ( x0 ) ) )
f = lambdify (x , g ) print ( ' itration % d \ t the root % 0 . 3f \ t function value % 0 . 3f \ n '%
a = float ( input ( ' Enter a valus : ') ) # 2 (i , x1 , f ( x1 ) ) ) ; # print all
b = float ( input ( ' Enter b valus : ') ) # 3 iteration value
N = float ( input ( ' Enter tolarence : ') ) # 0 . 001 x0 = x1
x=a;
c=b;
i=0
while ( 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
print ( ' itration % d \ t the root % 0 . 3f \ t function value % 0 . 3f \ n '%
(i ,c , f ( c ) ) ) ;
print ( ' final value of the root is % 0 . 5f '% c )
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
78 79
LAB 7: Interpolation /Extrapolation using Newton’s simp_poly = simplify ( poly )
print ( '\ nTHE INTERPOLATING POLYNOMIAL IS \ n ') ;
forward and backward difference formula pprint ( simp_poly )
# if you want to interpolate at some point the next session will help
7.1 Objectives: inter = input ( ' Do you want to interpolate at a point ( y / n ) ? ') # y
if inter = = 'y ':
Use python a = float ( input ( ' enter the point ') ) # 2
interpol = lambdify (t , simp_poly )
1. to interpolate using Newton’s Forward interpolation method. result = interpol ( a )
print ( '\ nThe value of the function at ' ,a , ' is \ n ' , result ) ;
2. to interpolate using Newton’s backward interpolation method.
80 81
print ( ' Enter data for x and y : ')
for i in range ( n ) :
x [ i ] = float ( input ( 'x [ '+ str ( i ) + ' ]= ') )
y [ i ] [ 0 ] = float ( input ( 'y [ '+ str ( i ) + ' ]= ') )
for i in range (0 , n ) :
print ( '% 0 . 2f ' % ( x [ i ] ) , end = ' ')
for j in range (0 , i + 1 ) :
print ( '\ t % 0 . 2f ' % ( y [ i ] [ j ] ) , end = ' ')
print ()
p=(t-x[n-1])/(x[1]-x[0])
f . append ( p )
for i in range (1 , n - 1 ) :
f . append ( f [ i - 1 ] * ( p + i ) / ( i + 1 ) ) 7.2 Exercise:
1. Obtain the interpolating polynomial for the following data
poly = y [ n - 1 ] [ 0 ]
print ( poly ) x: 0 1 2 3
for i in range ( n - 1 ) : y: 1 2 1 10
poly = poly + y [ n - 1 ] [ i + 1 ] * f [ i ]
simp_poly = simplify ( poly ) Ans: 2x3 − 7x2 + 6x + 1
print ( '\ nTHE INTERPOLATING POLYNOMIAL IS \ n ') ;
pprint ( simp_poly ) 2. Find the number of men getting wage Rs. 100 from the following table:
# if you want to interpolate at some point the next session will help
wage: 50 150 250 350
inter = input ( ' Do you want to interpolate at a point ( y / n ) ? ')
if inter = = 'y ': No. of men: 9 30 35 42
a = float ( input ( ' enter the point ') ) Ans: 23 men
interpol = lambdify (t , simp_poly )
result = interpol ( a ) 3. Using Newton’s backward interpolation method obtain y(160) for the following data
print ( '\ nThe value of the function at ' ,a , ' is \ n ' , result ) ;
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
82 83
LAB 8: Computation of area under the curve using
1 rd 3 th
Trapezoidal, Simpson’s 3 and Simpsons 8 rule
8.1 Objectives:
Use python 1 rd
8.3 Simpson’s 3 Rule
1. to find area under the curve represented by a given function using Trapezoidal rule. R5 1
rd Evaluate 1+x2
.
2. to find area under the curve represented by a given function using Simpson’s 13 0
rule. # Definition of the function to integrate
def my_func ( x ) :
th return 1 / ( 1 + x ** 2 )
3. to find area under the curve represented by a given function using Simpson’s 38
rule.
# Function to implement the Simpson 's one - third rule
4. to find the area below the curve when discrete points on the curve are given.
def simpson13 ( x0 , xn , n ) :
h = ( xn - x0 ) / n # calculating step size
8.2 Trapezoidal Rule # Finding sum
integration = ( my_func ( x0 ) + my_func ( xn ) )
R5 1
k = x0
Evaluate 1+x2
. for i in range (1 , n ) :
0
if i % 2 = = 0 :
# Definition of the function to integrate integration = integration + 4 * my_func ( k )
def my_func ( x ) : else :
return 1 / ( 1 + x ** 2 ) integration = integration + 2 * my_func ( k )
k += h
# Function to implement trapezoidal method # Finding final integration value
def trapezoidal ( x0 , xn , n ) : integration = integration * h * ( 1 / 3 )
h = ( xn - x0 ) / n # Calculating step return integration
size
# Finding sum # Input section
integration = my_func ( x0 ) + my_func ( xn ) # Adding first and lower_limit = float ( input ( " Enter lower limit of integration : " ) )
last terms upper_limit = float ( input ( " Enter upper limit of integration : " ) )
for i in range (1 , n ) : sub_interval = int ( input ( " Enter number of sub intervals : " ) )
k = x0 + i * h # i - th step value
integration = integration + 2 * my_func ( k ) # Adding areas of the # Call trapezoidal () method and get result
trapezoids result = simpson13 ( lower_limit , upper_limit , sub_interval )
# Proportioning sum of trapezoid areas print ( " Integration result by Simpson 's 1 / 3 method is : % 0 . 6f " % ( result )
integration = integration * h / 2 )
return integration
# Input section
lower_limit = float ( input ( " Enter lower limit of integration : " ) )
upper_limit = float ( input ( " Enter upper limit of integration : " ) )
sub_interval = int ( input ( " Enter number of sub intervals : " ) )
# Call trapezoidal () method and get result 8.4 Simpson’s 3/8th rule
result = trapezoidal ( lower_limit , upper_limit , sub_interval )
R6 1
Evaluate 0 1+x2
dx using Simpson’s 3/8 th rule, taking 6 sub intervals
# Print result
print ( " Integration result by Trapezoidal method is : " , result ) def s impson s_3_8_ rule (f , a , b , n ) :
84 85
h = (b - a) / n 1
Estimate the volume of the solid formed using Simpson’s rd rule. Hint: Required
s = f(a) + f(b) R1 3
for i in range (1 , n , 3 ) : volume is 0 y 2 ∗ πdx. **[Ans: 2.8192]**
s += 3 * f(a + i * h)
for i in range (3 , n -1 , 3 ) : 5. The velocity v(km/min) of a moped which starts from rest, is given at fixed intervals
s += 3 * f(a + i * h) of time t(min) as follows:
for i in range (2 , n -2 , 3 ) :
s += 2 * f(a + i * h) t: 2 4 6 8 10 12 14 16 18 20
return s * 3 * h / 8 v: 10 18 25 29 32 20 11 5 2 0
def f ( x ) : Estimate approximately the distance covered in twenty minutes.
return 1 / ( 1 + x ** 2 ) # function here
Answer for 5.
a = 0 # lower limit We know that ds/dt=v. So to get distance (s) we have to integrate.
b = 6 # upper limit Here h = 2.2, v0 = 0, v1 = 10, v2 = 18, v3 = 25 etc.
n = 6 # number of sub intervals
# we shall use simpson 's 1 / 3 rule directly to estimate
result = sim psons_ 3_8_r ule (f , a , b , n )
print ( '% 3 . 5f '% result ) h=2
y = [0 , 10 ,18 , 25 , 29 , 32 ,20 , 11 ,5 ,2 , 0 ]
result = ( h / 3 ) * (( y [ 0 ] + y [ 10 ] ) + 4 * ( y [ 1 ] + y [ 3 ] + y [ 5 ] + y [ 7 ] + y [ 9 ] ) + 2 * ( y [ 2 ] + y [ 4 ] + y [
1.27631 6]+y[8]))
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 87
LAB 9: Solution of ODE of first order and first degree D[0] = [ 2 * y [ 0 ] + 3 * exp ( x ) ]
D[1] = [ 4 * y [ 0 ] + 9 * exp ( x ) ]
by Taylor’s series and Modified Euler’s method D[2] = [ 8 * y [ 0 ] + 21 * exp ( x ) ]
D[3] = [ 16 * y [ 0 ] + 45 * exp ( x ) ]
9.1 Objectives: return D
3. to trace the solution curves. print ( " The required values 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 ]
9.2 Taylor series method to solve ODE ,X [ 3 ] ,Y [ 3 ] ) )
dy
Solve: dx
− 2y = 3ex with y(0) = 0 using Taylor series method at x = 0.1(0.1)0.3.
The required values are :at x= 0.00, y=0.00000, x=0.10, y=0.34850,
# # module taylor
x = 0.20, y=0.81079,x = 0.30, y=1.41590
'''X , Y = taylor ( deriv ,x ,y , xStop , h ) .
4th - order Taylor series method for solving the initial value problem { y
} ' = { F (x , { y } ) } , where
Solve y ′ + 4y = x2 with initial conditions y(0) = 1 using Taylor series method at x =
{ y } = { y [ 0 ] , y [ 1 ] ,... y [n - 1 ] } . 0.1, 0.2.
x , y = initial conditions from numpy import array
xStop = terminal value of x def taylor ( deriv ,x ,y , xStop , h ) :
h = increment of x X = []
''' Y = []
from numpy import array X . append ( x )
def taylor ( deriv ,x ,y , xStop , h ) : Y . append ( y )
X = [] while x < xStop : # Loop over integration steps
Y = [] D = deriv (x , y ) # Derivatives of y
X . append ( x ) H = 1.0
Y . append ( y ) for j in range ( 3 ) : # Build Taylor series
while x < xStop : # Loop over integration steps H = H*h/(j + 1)
D = deriv (x , y ) # Derivatives of y y = y + D[j]*H # H = h^j/j!
H = 1.0 x = x + h
for j in range ( 3 ) : # Build Taylor series X . append ( x ) # Append results to
H = H*h/(j + 1) Y . append ( y ) # lists X and Y
y = y + D[j]*H # H = h^j/j!
x = x + h return array ( X ) , array ( Y ) # Convert lists into arrays
X . append ( x ) # Append results to
Y . append ( y ) # lists X and Y # deriv = user - supplied function that returns derivatives in the 4 x n
array
return array ( X ) , array ( Y ) # Convert lists into arrays '''
[ y '[ 0 ] y '[ 1 ] y '[ 2 ] ... y '[n - 1 ]
# deriv = user - supplied function that returns derivatives in the 4 x n y "[ 0 ] y "[ 1 ] y "[ 2 ] ... y "[ n - 1 ]
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 deriv (x , y ) :
y '''[ 0 ] y '''[ 1 ] y '''[ 2 ] ... y '''[n - 1 ] D = zeros (( 4 , 1 ) )
y ''' '[ 0 ] y ' '''[ 1 ] y ''' '[ 2 ] ... y ' '''[n - 1 ]] D [ 0 ] = [ x ** 2 - 4 * y [ 0 ] ]
''' D [ 1 ] = [ 2 * x - 4 * x ** 2 + 16 * y [ 0 ] ]
def deriv (x , y ) : D [ 2 ] = [ 2 - 8 * x + 16 * x ** 2 - 64 * y [ 0 ] ]
D = zeros (( 4 , 1 ) ) D [ 3 ] = [ - 8 + 32 * x - 64 * x ** 2 + 256 * y [ 0 ] ]
88 89
return D 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
x = 0.0 # Initial value of x
xStop = 0 . 2 # last value
y = array ( [ 1 . 0 ] ) # Initial values of y
h = 0.1 # Step size
X , Y = taylor ( deriv ,x ,y , xStop , h )
90 91
The required values are at x= 0.00, y=1.00000, x=0.10, y=0.80000,
x=0.20, y=0.64008 def f (x , y ) :
return - 0 . 01 * y # ODE dy / dx = - ky
x0 = 0 . 0
y0 = 100 . 0
h = 25
n = 4
x , y = modified_euler (f , x0 , y0 , h , n )
def modified_euler (f , x0 , y0 , h , n ) :
x = np . zeros ( n + 1 )
y = np . zeros ( n + 1 )
x [ 0 ] = x0
y [ 0 ] = y0
9.5 Exercise:
for i in range ( n ) :
x[i+1] = x[i] + h 1. Find y(0.1) by Taylor Series exapnsion when y ′ = x − y 2 , y(0) = 1.
k1 = h * f ( x [ i ] , y [ i ] )
k2 = h * f ( x [ i + 1 ] , y [ i ] + k1 ) Ans: y(0.1) = 0.9138
y [ i + 1 ] = y [ i ] + 0 . 5 * ( k1 + k2 )
2. Find y(0.2) by Taylor Series exapnsion when y ′ = x2 y − 1, y(0) = 1, h = 0.1.
return x , y Ans: y(0.2) = 0.80227
92 93
3. Evaluate by modified Euler’s method: y ′ = ln(x + y), y(0) = 2 at x = 0(0.2)0.8. LAB 10: Solution of ODE of first order and first de-
Ans: 2.0656, 2.1416, 2.2272, 2.3217 gree by Runge-Kutta 4th order method and Milne’s
4. Solve by modified Euler’s method: y ′ = x + y, y(0) = 1, h = 0.1, x = 0(0.1)0.3. predictor and corrector method
Ans: 1.1105, 1.2432, 1.4004
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.
94 95
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 )
print ( ' predicted value of y4 is % 3 . 3f '% y4p )
y14 = f ( x4 , y4p ) ;
for i in range (1 , 4 ) :
y4 = y2 + ( h / 3 ) * ( y14 + 4 * y13 + y12 ) ;
print ( ' corrected value of y4 after \ t iteration %d is \ t % 3 . 5f \ t '%
(i , y4 ) )
y14 = f ( x4 , y4 ) ;
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 sympy import *
def Milne (g , x0 ,h , y0 , y1 , y2 , y3 ) :
x , y = symbols ( 'x , y ')
f = lambdify ( [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 )
print ( ' predicted value of y4 ' , y4p )
y14 = f ( x4 , y4p )
for i in range (1 , 4 ) :
y4 = y2 + ( h / 3 ) * ( y14 + 4 * y13 + y12 )
print ( ' corrected value of y4 , iteration % d '%i , y4 )
96