0% found this document useful (0 votes)
87 views32 pages

m2 Math Lab

Uploaded by

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

m2 Math Lab

Uploaded by

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

In [1]: """"

1.Lab-Finding gradient, divergent, curl and their geometrical interpretation


1.To find curl of F⃗ = xy2i + 2x2yz j − 3yz2k """

from sympy.physics.vector import *
from sympy import var

var('x,y,z')
v=ReferenceFrame('v')
F=v[0]*v[1]**2*v.x+2*v[0]**2*v[1]*v[2]*v.y-3*v[1]*v[2]**2*v.z
G=curl(F,v)
F=F.subs([(v[0],x),(v[1],y),(v[2],z)])
print("Given vector point function is ")
display(F)

G=G.subs([(v[0],x),(v[1],y),(v[2],z)])
print("curl of F=")
display(G)

Given vector point function is

𝑥𝑦2 𝐯𝐱̂ + 2𝑥2 𝑦𝑧𝐯𝐲̂ − 3𝑦𝑧2 𝐯𝐳̂


curl of F=

(−2𝑥2 𝑦 − 3𝑧2 )𝐯𝐱̂ + (4𝑥𝑦𝑧 − 2𝑥𝑦)𝐯𝐳̂


In [3]: """ 2. To find divergence of F⃗ = x2yzˆi + y2zxˆj + z2xyk """

from sympy.vector import*
from sympy import symbols

N=CoordSys3D('N')
x,y,z=symbols('x,y,z')
A=N.x**2*N.y*N.z*N.i+N.y**2*N.z*N.x*N.j+N.z**2*N.x*N.y*N.k

delop=Del()
curlA=delop.cross(A)
display(curlA)

print(f"\n Curl of {A} is \n")
display(curl(A))

∂ 𝐱𝐍 𝐲𝐍 𝐳𝐍 2 − ∂ 𝐱𝐍 𝐲𝐍 2 𝐳𝐍 𝐢𝐍̂ + − ∂ 𝐱𝐍 𝐲𝐍 𝐳𝐍 2 + ∂ 𝐱𝐍 2 𝐲𝐍 𝐳𝐍 𝐣𝐍̂ + ∂ 𝐱𝐍 𝐲𝐍 2 𝐳𝐍 − ∂ 𝐱𝐍 2 𝐲𝐍 𝐳𝐍 𝐤𝐍̂


( ∂𝐲𝐍 ∂𝐳𝐍 ) ( ∂𝐱𝐍 ∂𝐳𝐍 ) ( ∂𝐱𝐍 ∂𝐲𝐍 )
Curl of N.x**2*N.y*N.z*N.i + N.x*N.y**2*N.z*N.j + N.x*N.y*N.z**2*N.k is

(−𝐱𝐍 𝐲𝐍 2 + 𝐱𝐍 𝐳𝐍 2 ) 𝐢𝐍̂ + (𝐱𝐍 2 𝐲𝐍 − 𝐲𝐍 𝐳𝐍 2 ) 𝐣𝐍̂ + (−𝐱𝐍 2 𝐳𝐍 + 𝐲𝐍 2 𝐳𝐍 ) 𝐤𝐍̂


In [4]: """
Lab 2. Solution of second order ordinary differential equation and plotting the solution curve
1.Solve: y′′ − 5y′ + 6y = cos(4x)
"""

from sympy import *

x=Symbol('x')
y=Function("y")(x)
C1,C2=symbols('C1,C2')

y1=Derivative(y,x)
y2=Derivative(y1,x)

print("Differential Equation :\n")
diff1=Eq(y2-5*y1+6*y-cos(4*x),0)

display(diff1)

print("\n\n General solution :\n")
z=dsolve(diff1)

display(z)

PS=z.subs({C1:1,C2:2})
print("\n\n Paricular Solution: \n")
display(PS)

Differential Equation :

6𝑦(𝑥) − cos(4𝑥) − 5 𝑑𝑥𝑑 𝑦(𝑥) + 𝑑𝑥𝑑 2 𝑦(𝑥) = 0


2

General solution :

𝑦(𝑥) = 𝐶1 𝑒2𝑥 + 𝐶2 𝑒3𝑥 − sin(4𝑥)


25 − cos(4𝑥)
50
Paricular Solution:

𝑦(𝑥) = 2𝑒3𝑥 + 𝑒2𝑥 − sin(4𝑥)


25 − cos(4𝑥)
50
In [5]: """
2.Solve: 3 d2x \dt2+ 2 dx\dt − 2x = cos(2x) with x(0) = 0; x′(0) = 0 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],-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]

plt.plot(xs,ys,'r-')

plt.xlabel('t values')
plt.ylabel('x values')

plt.title('Solution curve')
plt.show()
In [7]: """
Lab 3. Solution of differential equation of oscillations of a spring with various load
1.Solve d2x\dt2 + 64x = 0, x(0) = 1/4 , 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]
plt.plot(xs,ys,'r-')

plt.xlabel('Time')
plt.ylabel('Amplitude')

plt.title('Solution of free and undamed case')
plt.grid(True)
plt.show()
In [8]: """
2.Solve 9 d2x\dt2 + 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)
ys=us[:,0]
plt.plot(xs,ys,'r-')

plt.xlabel('Time')
plt.ylabel('Amplitude')

plt.title('Solution of free and damped case')
plt.grid(True)
plt.show()
In [10]: """
Lab 4. Computation of basis and dimension for a vector space and graphical representation of linear trans-formation.
Verify the rank-nullity theorem for the linear transformation T : R3 -R3 defined by
1.T (x, y, z) = (x + 4y + 7z, 2x + 5y + 8z, 3x + 6y + 9z).
"""

import numpy as np
from scipy.linalg import null_space

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

rank=np.linalg.matrix_rank(A)
print("Rank of the matrix",rank)

ns=null_space(A)
print("Null space of the matrix",ns)

nullity=ns.shape[1]
print("Null space of the matrix",nullity)

if rank + nullity == A.shape[1]:
print("Rank-nullity theorem holds")
else:
print("Rabk-nullity theorem does not hold.")

Rank of the matrix 2


Null space of the matrix [[ 0.40824829]
[-0.81649658]
[ 0.40824829]]
Null space of the matrix 1
Rank-nullity theorem holds
In [11]: """
2.Find the dimension of subspace spanned by the vectors (1, 2, 3), (2, 3, 1) and (3, 1, 2).
"""

import numpy as np

V=np.array([
[1,2,3],
[2,3,1],
[3,1,2]])
basis=np.linalg.matrix_rank(V)
dimension=V.shape[0]
print("Dimension of row space",basis)
print("Dimension of column space",basis)

Dimension of row space 3


Dimension of column space 3

In [12]: """
Lab 5. Computing the inner product and orthogonality
1.Find the inner product of the vectors (2, 1, 5, 4) and (3, 4, 7, 8)
"""
import numpy as np

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

output=np.dot(A,B)
print(output)

77
In [13]: """
2. Verify whether the following vectors (2, 1, 5, 4) and (3, 4, 7, 8) are orthogonal.
"""
import numpy as np

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

output=np.dot(A,B)
print('Inner product is:',output)
if output==0:
print("given vector are orthogonal")
else:
print("given vectors are not orthogonal")

Inner product is: 77


given vectors are not orthogonal
In [14]: """
Lab 6. *Solution of algebraic and transcendental equation by Regula-Falsi and Newton Raphson method
1. Obtain a root of the equation x3− 2x − 5 = 0 between 2 and 3 by regula-falsi method. Perform 5 iterations.
"""
from sympy import *
x=Symbol('x')
g=input('Entrer the function')
f=lambdify(x,g)
a=float(input('Enter a values:'))
b=float(input('Enter b values:'))
N=int(input('Enter number of iteraions :'))

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)));

Entrer the functionx**3-2*x-5


Enter a values:2
Enter b values:3
Enter number of iteraions :5
Itration 1 the root 2.059 function value -0.391

Itration 2 the root 2.081 function value -0.147

Itration 3 the root 2.090 function value -0.055

Itration 4 the root 2.093 function value -0.020

Itration 5 the root 2.094 function value -0.007


In [15]: """
2. Find a root of the equation 3x = cos x+ 1, near 1, by Newton Raphson method. Perform 5 iterations
"""

from sympy import *
x=Symbol('x')
g=input('enter the function')
f=lambdify(x,g)
dg=diff(g);
df=lambdify(x,dg)
x0=float(input('Enter the inital approximation'));
n=int(input('Enter the number of iteration '));
for i in range(1,n+1):
x1=(x0-(f(x0)/df(x0)))
print('Iteration %d \t the root %0.3f \t function value %0.3f \n'%(i,x1,f(x1)));
x0=x1

enter the function3*x-cos(x)-1


Enter the inital approximation1
Enter the number of iteration 5
Iteration 1 the root 0.620 function value 0.046

Iteration 2 the root 0.607 function value 0.000

Iteration 3 the root 0.607 function value 0.000

Iteration 4 the root 0.607 function value 0.000

Iteration 5 the root 0.607 function value -0.000


In [25]: """
Lab 7. Interpolation /Extrapolation using Newton’s forward and backward difference formula
1.Use Newton’s forward interpolation to obtain the interpolating polynomial and hence calculate y(2) for the following
x: 1 3 5 7 9
y: 6 10 62 210 502
"""

from sympy import *
import numpy as np

n = int(input('Enter number of data points: '))
x= np.zeros((n))
y = np.zeros((n,n))

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(1,n):
for j in range(0,n-i):
y[j][i] = y[j+1][i-1] - y[j][i-1]

print("\nFORWARD DIFFERENCE TABLE\n");

for i in range(0,n):
print('%0.2f' %(x[i]), end='')
for j in range(0,n-1):
print('\t\t%0.2f' %(y[i][j]), end='')
print()
t=symbols('t')
f=[]

p=(t-x[0])/(x[1]-x[0])
f.append(p)
for i in range(1,n-1):
f.append(f[i-1]*(p-i)/(i+1))
poly=y[0][0]
for i in range(n-1):
poly=poly+y[0][i+1]*f[i]
simp_poly=simplify(poly)
print('\n THE INTERPOLATING POLYNOMIAL IS \n');
pprint(simp_poly)
inter=input('Do you want to interpolate at a point (y/n)? ')
if inter=='y':
a= float(input('enter the point '))
interpol=lambdify(t, simp_poly)
result=interpol (a)
print('\nThe value of the function at',a, 'is\n', result);

Enter number of data points: 5


Enter data for x and y:
x[0]=1
y[0]=6
x[1]=3
y[1]=10
x[2]=5
y[2]=62
x[3]=7
y[3]=210
x[4]=9
y[4]=502

FORWARD DIFFERENCE TABLE

1.00 6.00 4.00 48.00 48.00


3.00 10.00 52.00 96.00 48.00
5.00 62.00 148.00 144.00 0.00
7.00 210.00 292.00 0.00 0.00
9.00 502.00 0.00 0.00 0.00

THE INTERPOLATING POLYNOMIAL IS

3 2
1.0⋅t - 3.0⋅t + 1.0⋅t + 7.0
Do you want to interpolate at a point (y/n)? y
enter the point 2

The value of the function at 2.0 is


5.0
In [29]: """
2.Use Newton’s backward interpolation to obtain the interpolating polynomial and hence calculate y(8) for the followin
x: 1 3 5 7 9
y: 6 10 62 210 502
"""

from sympy import *
import numpy as np
import sys

print("This will use Newton's backward interpolation formula")

n = int(input('Enter number of data points: '))
x= np.zeros((n))
y = np.zeros((n,n))

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(1,n):
for j in range(n-1,i-2,-1):
y[j][i] = y[j][i-1] - y[j-1][i-1]

print("\nBACKWARD DIFFERENCE TABLE\n");

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()

t=symbols('t')
f=[]

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))
poly=y[n-1][0]
print(poly)
for i in range(n-1):
poly=poly+y[n-1][i+1]*f[i]

simp_poly=simplify(poly)
print('\n THE INTERPOLATING POLYNOMIAL IS \n');
pprint(simp_poly)
inter=input('Do you want to interpolate at a point (y/n)? ')
if inter=='y':
a= float(input('enter the point '))
interpol=lambdify(t, simp_poly)
result=interpol (a)
print('\nThe value of the function at',a, 'is\n', result);
This will use Newton's backward interpolation formula
Enter number of data points: 5
Enter data for x and y:
x[0]=1
y[0]=6
x[1]=3
y[1]=10
x[2]=5
y[2]=62
x[3]=7
y[3]=210
x[4]=9
y[4]=502

BACKWARD DIFFERENCE TABLE

1.00 6.00
3.00 10.00 4.00
5.00 62.00 52.00 48.00
7.00 210.00 148.00 96.00 48.00
9.00 502.00 292.00 144.00 48.00 0.00
502.0

THE INTERPOLATING POLYNOMIAL IS

3 2
1.0⋅t - 3.0⋅t + 1.0⋅t + 7.0
Do you want to interpolate at a point (y/n)? y
enter the point 8

The value of the function at 8.0 is


335.0
In [1]: """
Lab 8. Computation of area under the curve using Trapezoidal, Simpson’s 1 \3 rd and Simpsons 3\ 8 th rule
1.Evaluate by Simpson’s 1 \3 rd rule
2.Evaluate by Simpsons 3\ 8 th rule
"""

def my_func(x):
return 1/(1+x**2)

def simpson13(x0,xn,n):
h=(xn-x0)/n
integration = (my_func(x0)+ my_func(xn))
k = x0
for i in range(1,n):
if i%2 == 0:
integration = integration + 4 * my_func(k)
else:
integration = integration + 2 * my_func(k)
k +=h
integration = integration * h * (1/3)
return integration

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: "))

result=simpson13(lower_limit,upper_limit,sub_interval)
print("Integration result by simpson's 1/3 method is: %0.6f" %(result))

Enter lower limit of integration:0


Enter upper limit of integration:5
Enter number of sub intervals: 100
Integration result by simpson's 1/3 method is: 1.404120
In [3]: """
2.Evaluate by Simpsons 3\ 8 th rule
"""

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

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

a=0
b=6
n=6

result=simpsons_3_8_rule(f,a,b,n)
print('%3.5f'%result)

1.27631
In [6]: """
Lab 9. Solution of ODE of first order and first degree by Taylor’s series and Modified Euler’s metho
1. Solve: dy/ dx − 2y = 3ex with y(0) = 0 using Taylor series method at x = 0.1(0.1)0.3.
"""

from numpy import array, zeros, exp

def taylor(deriv,x,y,xStop,h):
X=[]
Y=[]
X.append(x)
Y.append(y)
while x<xStop:
D=deriv(x,y)
H=1.0
for j in range(3):
H=H*h/(j+1)
y=y+D[j]*H
x=x+h
X.append(x)
Y.append(y)

return array(X),array(Y)

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

x=0.0
xStop=0.3
y=array([[0.0]])
h=0.1
X,Y=taylor(deriv,x,y,xStop,h)
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],

The required values are :at x=0.00, y=0.00000, x=0.10, y=0.34850, x=0.20, y=0.81079, x=0.30, y=1.41590

C:\Users\NAveED aK\AppData\Local\Temp\ipykernel_5672\1574999152.py:27: DeprecationWarning: setting an array element w


ith a sequence. This was supported in some cases where the elements are arrays with a single element. For example `n
p.array([1, np.array([2])], dtype=int)`. In the future this will raise the same ValueError as `np.array([1, [2]], dty
pe=int)`.
D[0]=[2*y[0]+3*exp(x)]
C:\Users\NAveED aK\AppData\Local\Temp\ipykernel_5672\1574999152.py:28: DeprecationWarning: setting an array element w
ith a sequence. This was supported in some cases where the elements are arrays with a single element. For example `n
p.array([1, np.array([2])], dtype=int)`. In the future this will raise the same ValueError as `np.array([1, [2]], dty
pe=int)`.
D[1]=[4*y[0]+9*exp(x)]
C:\Users\NAveED aK\AppData\Local\Temp\ipykernel_5672\1574999152.py:29: DeprecationWarning: setting an array element w
ith a sequence. This was supported in some cases where the elements are arrays with a single element. For example `n
p.array([1, np.array([2])], dtype=int)`. In the future this will raise the same ValueError as `np.array([1, [2]], dty
pe=int)`.
D[2]=[8*y[0]+21*exp(x)]
C:\Users\NAveED aK\AppData\Local\Temp\ipykernel_5672\1574999152.py:30: DeprecationWarning: setting an array element w
ith a sequence. This was supported in some cases where the elements are arrays with a single element. For example `n
p.array([1, np.array([2])], dtype=int)`. In the future this will raise the same ValueError as `np.array([1, [2]], dty
pe=int)`.
D[3]=[16*y[0]+45*exp(x)]
In [2]: """
2. Solve: y ′ = e-x with y(0) = −1 using Euler’s method at x = 0.2(0.2)0.6.
"""

import numpy as np
import matplotlib.pyplot as plt

f=lambda x:np.exp(-x)
h=0.2
y0=-1
n=3

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

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

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

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
print("\n\n")


plt.plot(x,y,'bo--',label='Approximate')
plt.plot(x,-np.exp(-x),'g*-',label='Exact')
plt.title("Approximate and Exact Solution")
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid()
plt.legend(loc='best')
plt.show()

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
In [16]: """
Lab 10. Solution of ODE of first order and first degree by Runge-Kutta 4th order method and Milne’s predictor and corr
1. Apply the Runge Kutta method to find the solution of dy/dx = 1 + (y/x) at y(2) taking h = 0.2. Given that y(1) = 2.
"""

from sympy import *
import numpy as np
def Rungekutta(g,x0,h,y0,xn):
x,y=symbols('x,y')
f=lambdify([x,y],g)
xt=x0+h
Y=[y0]
while xt<=xn:
k1=h*f(x0,y0)
k2=h*f(x0+h/2,y0+k1/2)
k3=h*f(x0+h/2,y0+k2/2)
k4=h*f(x0+h, y0+k3)
y1=y0+(1/6)*(k1+2*k2+2*k3+k4)
Y.append(y1)
# print('y(%3.3f'%xt,') is %3.3f'%y1)
x0=xt
y0=y1
xt=xt+h
return np.round(Y,2)
Rungekutta('1+(y/x)',1,0.2,2,2)

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


In [25]: """
2. Apply Milne’s predictor and corrector method to solve dy/dx = x 2+ (y/2) at y(1.4). Given that y(1)=2, y(1.1)=2.215
"""

x0=1
y0=2
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('predicated 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)

predicated value of y4 is 3.079


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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy