I Sem Mathematics Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

LAB 1. Use python a. to plot Cartesian curves. b. to plot polar curves. c.

to
plot implicit functions.
In [ ]: #Scatter Plot
import matplotlib.pyplot as plt
x = [1,2,3,4,6,7,8]
y = [2,7,9,1,5,10 ,3]
plt.scatter(x, y)
plt.xlabel('x - axis ')
plt.ylabel('y - axis ')
plt.title('Scatter points ')
plt.show()

In [ ]: #First graph
import matplotlib.pyplot as plt
x = [1,2,3,4,6,7,8]
y = [2,7,9,1,5,10 ,3]
plt.plot(x, y, 'r+--')
plt.xlabel('x - axis ')
plt.ylabel('y - axis ')
plt.title('My first graph !')
plt.show()

In [ ]: #1. Exponential Curves


import numpy as np
import matplotlib.pyplot as plt
x = np.arange (-10 , 10 , 0.001)
y = np.exp(x)
plt.plot(x,y)
plt.title(" Exponential curve ")
plt.grid()
plt.show()

In [ ]: #Sine curve
import numpy as np
import matplotlib.pyplot as plt
x = np. arange(-10 , 10 , 0.001)
y1 = np.sin(x)
plt.plot(x,y1)
plt.title(" sine curve ")
plt.xlabel(" Values of x")
plt.ylabel(" Values of sin (x) ")
plt.grid()
plt.show()

In [ ]: #cosine curve
import numpy as np
import matplotlib.pyplot as plt
x = np. arange(-10 , 10 , 0.001)
y1 = np.cos(x)
plt.plot(x,y1)
plt.title(" cosine curve ")
plt.xlabel(" Values of x")
plt.ylabel(" Values of cosin(x) ")
plt.grid()
plt.show()

In [ ]: #Sine and cosine curve


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

In [ ]: #Simple Graph
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace (0, 2, 100)
plt.plot(x, x, label ='linear ')
plt.plot(x, x ** 2, label ='quadratic ')
plt.plot(x, x ** 3, label ='cubic ')
plt.xlabel('x label ')
plt.ylabel('y label ')
plt.title(" Simple Plot ")
plt.legend()
plt.show()

In [ ]: #2. Implicit Function


#Circle: x^2 + y^2 = 4
from sympy import plot_implicit , symbols , Eq
x, y = symbols ('x y')
p1 = plot_implicit (Eq(x ** 2 + y ** 2, 4) ,(x,-4,4) ,(y,-4,4),title = 'Circle : $x^2+y^2=4$ ') #r = 2

In [ ]: #Strophoid: y^2(a − x) = x^2(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=

In [ ]: #Cissoid: y^2(a − x) = x^3, a > 0


p4= plot_implicit (Eq ((y ** 2)*(3-x),x ** 3) ,(x,-2,5) ,(y,-5,5)) #a = 3

In [ ]: #Lemniscate: a^2y^2 = x^2(a^2 − x^2)


p5= plot_implicit (Eq(4*(y ** 2) ,(x ** 2)*(4-x ** 2)) ,(x,-5,5) ,(y,-5,5)) # a=2

In [ ]: #Folium of De-Cartes: x^3 + y^3 = 3axy


p6= plot_implicit (Eq(x ** 3+y ** 3,3*2*x*y) ,(x,-5,5) ,(y,-5,5)) # a=2

In [ ]: #Polar Curves
import numpy as np
import matplotlib.pyplot as plt
plt.axes(projection = 'polar')
r = 3
rads = np.arange(0, 2 * np.pi, 0.01)

for i in rads :
plt.polar (i, r, 'g')
plt.show ()

In [ ]: #Cardioid: r = 5(1 + cosθ)


from pylab import *
theta = linspace (0,2*np.pi , 1000 )
r1=5+5*cos ( theta )
polar(theta ,r1 ,'r')
show()

In [ ]: #Four leaved Rose: r = 2|cos2x|


from pylab import *
theta = linspace (0,2*pi , 1000 )
r=2*abs(cos(2* theta ))
polar (theta ,r,'r')
show ()

In [ ]: #Cardioids: r = a + acos(θ) and r = a − acos(θ)


import numpy as np
import matplotlib.pyplot as plt
import math
plt.axes ( projection = 'polar')
a=3
rad = np. arange (0, (2 * np.pi), 0.01)
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.')
plt.show ()

In [ ]: #3. Parametric Equations


#Circle: x = acos(θ); y = asin(θ)
import numpy as np
import matplotlib.pyplot as plt
def circle (r):
x = []
y = []
for theta in np. linspace (-2*np.pi , 2*np.pi , 100):
x.append (r*np.cos( theta ))
y.append (r*np.sin( theta ))
plt.plot (x,y)
plt.show ()
circle (5)

In [ ]: #Cycloid: x = a(θ − sinθ); y = a(1 − sinθ)


import numpy as np
import matplotlib.pyplot as plt
def cycloid (r):
x = []
y = []
for theta in np. linspace (-2*np.pi , 2*np.pi , 100):
x.append (r*( theta - np.sin( theta )))
y.append (r*(1 - np.cos( theta )))
plt. plot (x,y)
plt. show ()
cycloid (2)

LAB 2: Finding angle between two polar curves, curvature and radius of
curvature.
In [ ]: 1. Find the angle between the curves r = 4(1 + cos t) and r = 5(1 − cos t).
from sympy import *
r,t = symbols ('r,t')
r1 = 4*(1+cos (t));
r2 = 5*(1-cos (t));
dr1 = diff (r1 ,t)
dr2 = diff (r2 ,t)
t1 = r1/dr1
t2 = r2/dr2
q = solve (r1-r2 ,t)
w1 = t1.subs ({t: float (q[1])})
w2 = t2.subs ({t: float (q[1])})
y1 = atan(w1)
y2 = atan(w2)
w = abs(y1-y2)
print ('Angle between curves in radians is %0.3f '%(w))

In [ ]: from sympy import *


r,t = symbols ('r,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)
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))

In [ ]: #2. Radius of curvature


#Find the radius of curvature, r = 4(1 + cos t) at t=π/2.
from sympy import *
t = Symbol ('t')
r = Symbol ('r')
r = 4*(1+cos(t))
r1 = Derivative (r,t). doit ()
r2 = Derivative (r1 ,t). doit ()
rho = (r ** 2+r1 ** 2) ** (1.5)/(r ** 2+2*r1 ** 2-r*r2);
rho1 = rho . subs (t,pi/2) # substitute t in rho
print ('The radius of curvature is %3.4f units '% rho1 )

In [ ]: #Find the angle between the curves r = 4 cos t and r = 5 sin t.


from sympy import *
t,r,a,n= symbols ('t r a n')
r=a*sin(n*t)
r1 = Derivative (r,t). doit ()
r2 = Derivative (r1 ,t). doit ()
rho = (r ** 2+r1 ** 2) ** 1.5/(r ** 2+2*r1 ** 2-r*r2);
rho1 = rho.subs (t,pi/2)
rho1 = rho1.subs (n,1)
print ("The radius of curvature is")
display( simplify ( rho1 ))

In [ ]: #Parametric Curves
#Find radius of curvature of x = acos(t), y = asin(t).
from sympy import *
from sympy .abc import rho , x,y,r,K,t,a,b,c, alpha
y=( sqrt (x)-4) ** 2
y=a*sin(t)
x=a*cos(t)
dydx = simplify ( Derivative (y,t). doit ())/ simplify ( Derivative (x,t). doit ())
rho = simplify ((1+ dydx ** 2) ** 1.5/( Derivative (dydx ,t). doit ()/( Derivative (x,
t). doit ())))
print ('Radius of curvature is ')
display ( ratsimp (rho ))
t1=pi/2
r1=5
rho1 = rho . subs (t,t1);
rho2 = rho1 . subs (a,r1);
print ('\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 ))

In [ ]: #Find the radius of curvature of y = (asin(t))3/2 ; x = (acos(t))3/2.


from sympy import *
from sympy .abc import rho , x,y,r,K,t,a,b,c, alpha
y=(a*sin(t)) ** (3/2)
x=(a*cos(t)) ** (3/2)
dydx = simplify ( Derivative (y,t). doit ())/ simplify ( Derivative (x,t). doit ())
rho = simplify ((1+ dydx ** 2) ** 1.5/( Derivative (dydx ,t). doit ()/( Derivative (x,
t). doit ())))
print ('Radius of curvature is ')
display ( ratsimp (rho ))
t1=pi/4
r1=1;
rho1 = rho . subs (t,t1);
rho2 = rho1 . subs (a,r1);
display ('Radius of curvature at r=1 and t=pi/4 is ',simplify ( rho2 ));
curvature =1/ rho2 ;
print ('\n\n Curvature at (1,pi/4) is ',float ( curvature ))

LAB 3: Finding partial derivatives and Jacobian of functions of several


variables.
In [ ]: #Prove that mixed partial derivatives , uxy = uyx for u = exp(x)(xcos(y) −ysin(y)).
from sympy import *
x,y = symbols ('x y')
u=exp(x)*(x*cos(y)-y*sin(y))
dux = diff (u,x)
duy = diff (u,y)
duxy = diff (dux ,y)
duyx = diff (duy ,x)
if duxy == duyx :
print ('Mixed partial derivatives are equal ')
else :
print ('Mixed partial derivatives are not equal ')

In [ ]: #Prove that if u = ex(x cos(y) − y sin(y)) then uxx + uyy = 0.


from sympy import *
x,y = symbols ('x y')
u = exp(x)*(x*cos(y)-y*sin(y))
display (u)
dux = diff (u,x)
duy = diff (u,y)
uxx = diff (dux ,x)
uyy = diff (duy ,y)
w = uxx+uyy
w1 = simplify (w)
print('Ans :',float (w1))

In [ ]: #JACOBIANS
#If u = xy/z, v = yz/x,w = zx/y then prove that J = 4.
from sympy import *
x,y,z= symbols ('x,y,z')
u = x*y/z
v = y*z/x
w = z*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]]);
print ("The Jacobian matrix is \n")
display (J)
Jac =det (J). doit ()
print('\n\n J = ', Jac )

In [ ]: #If u = x+3y2 −z3, v = 4x2yz, w = 2z2 −xy then prove that at (1,−1, 0), J = 20.
from sympy import *
x,y,z= symbols ('x,y,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]]);
print ("The Jacobian matrix is ")
display (J)
Jac = Determinant (J). doit ()
print ('\n\n J = \n')
display (Jac )
J1=J. subs ([(x, 1), (y, -1), (z, 0)])
print ('\n\n J at (1,-1,0):\n')
Jac1 = Determinant (J1). doit ()
display ( Jac1 )

In [ ]: #X = ρ ∗ cos(ϕ) ∗ sin(θ), Y = ρ ∗ cos(ϕ) ∗ cos(θ), Z = ρ ∗ sin(ϕ) then find ∂(X,Y,Z) ∂(ρ,ϕ,θ).


from sympy import *
from sympy .abc import rho , phi , theta
X = rho*cos(phi)*sin( theta );
Y = rho*cos(phi)*cos( theta );
Z = rho*sin(phi);
dx = Derivative (X,rho ). doit ()
dy = Derivative (Y,rho ). doit ()
dz = Derivative (Z,rho ). doit ()
dx1 = Derivative (X,phi ). doit ();
dy1 = Derivative (Y,phi ). doit ();
dz1 = Derivative (Z,phi ). doit ()
dx2 = Derivative (X, theta ). doit ()
dy2 = Derivative (Y, theta ). doit ();
dz2 = Derivative (Z, theta ). doit ();
J= Matrix ([[dx ,dy ,dz],[dx1 ,dy1 ,dz1],[dx2 ,dy2 ,dz2]]);
print ('The Jacobian matrix is ')
display (J)
print ('\n\n J = \n')
display(simplify(Determinant (J).doit()))

LAB 4: Applications of Maxima and Minima of functions of two variables,


Taylor series expansion and L’Hospital’s Rule
In [ ]: #MAXIMA & MINIMA
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
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 ')
q1 = s1.subs ({y: criticalpoints1 ,x: criticalpoints2 }). evalf ()
q2 = s2.subs ({y: criticalpoints1 ,x: criticalpoints2 }). evalf ()
q3 = s3. subs ({y: criticalpoints1 ,x: criticalpoints2 }). evalf ()
delta = s1*s2-s3 ** 2
print(delta , q1)
if(delta >0 and s1<0):
print(" f takes maximum ")
elif( delta >0 and s1>0):
print(" f takes minimum ")
if(delta <0):
print ("The point is a saddle point ")
if ( delta ==0):
print (" further tests required ")

In [ ]: #TAYLOR SERIES PROBLEM


#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)))
def f(x):
return np.sin (1*x)
x = np. linspace (-10 , 10)
plt.plot (x, yat (x), color ='red')
plt.plot (x, f(x), color ='green')
plt.ylim ([-3, 3])
plt.grid ()
plt.show ()

In [ ]: #MACLAURIN SERIES
#Find the Maclaurin series expansion of sin(x)+cos(x) upto 3rd degree term. Calculate sin(10) + cos(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)
plt . plot (x, yat (x), color ='red')
plt . plot (x, f(x), color ='green')
plt . ylim ([-3, 3])
plt . grid ()
plt . show ()

In [ ]: #l'HOSPITAL RULE
#limx→0 sin(x)/x
from sympy import Limit , Symbol ,exp ,sin
x= Symbol ('x')
l= Limit (( sin(x))/x,x,0).doit()
print (l)

In [ ]: #Evaluate lim x→1 ((5x4−4x2−1)/(10−x−9x3)


from sympy import *
x= Symbol ('x')
l= Limit ((5*x ** 4-4*x ** 2-1)/(10-x-9*x ** 3),x,1).doit()
print (l)

In [ ]: #Prove that limx→∞(1 + 1/x)^x = e


from sympy import *
from math import inf
x = Symbol('x')
l = Limit ((1+1/x) ** x,x,inf).doit()
display (l)

LAB 5: Solution of First order differential equation and ploting the


solution curves
In [ ]: #Solve : dP(t)/dt = r
from sympy import *
init_printing()
t,r = symbols('t,r')
P = Function('P')(t)
C1 = Symbol('C1')
print("\n Differential Equation ")
DE1 = Derivative (P, t, 1)-r
display (DE1 )
print ("\n General Solution ")
GS1 = dsolve(DE1)
display(GS1)
print ("\n Particular Solution ")
PS1 =GS1.subs({C1:2})
display (PS1)

In [ ]: #Solve: dy/dx + tanx − y3secx = 0.


from sympy import *
x,y = symbols('x,y')
y = Function("y")(x)
y1 = Derivative(y,x)
z1 = dsolve(Eq(y1+y*tan (x)-y ** 3*sec (x),0),y)
display(z1)

In [ ]: #Solve: x3 dy/dx − x2y + y4cosx = 0.


from sympy import *
x,y = symbols('x,y')
y = Function("y")(x)
y1 = Derivative(y,x)
z1 = dsolve(Eq(x ** 3*y1-x ** 2*y+y ** 4*cos(x),0),y)
display(z1)

In [ ]: #SOLUTION CURVES USING IVP[INITIAL VALUE PROBLEM]


#Solve dy/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
def model (y,t):
k=0.3
return -k*y
y0=5
t = np.linspace (0,20)
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()

In [ ]: #Simulate τ dy/dt = −y + Kpu; 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 )
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()

In [ ]: #APPLICATION PROBLEM
'''A culture initially has P0 number of bacteria. At t = 1 hour the number of bacteria is measured to be 3
#2P0. 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) = 3/2p0.
#The solution is : y = P0e0.405465108108164t, y0 = 20.'''
from pylab import *
t= arange (0,10 ,0.5)
P0 = 20
y = 20*exp(0.405465108108164 *t)
plot(t,y)
xlabel('Time')
ylabel('no of bacteria')
title('Law of Natural Growth')
show()

In [ ]: #NEWTONS LAW OF COOLING


'''The temperature of a body drops from 100 C to 75 C in 10 minutes where the
surrounding air is at the temperature 20 C . What will be the temperature of the
body after half an hour? Plot the graph of cooling.'''
import numpy as np
from sympy import *
from matplotlib import pyplot as plt
t2 = 20 # surrounding temp
t1 = 100 # inital temp
t = 10
T = 75
k1 = (1/t)*log (( t1-t2)/(T-t2))
print ('k= ',k1)
k = Symbol ('k')
t = Symbol ('t')
T = Function ('T')(t)
T = t2+(t1-t2)*exp(-k*t)
print ('T=',T)
T = T.subs (k,k1)
T = lambdify (t,T)
t = np.linspace (0, 70)
plt.plot (t, T(t), color ='red')
plt.grid ()
plt.show ()
print('When time t=30 minute T is ,',T(30),'o C')

COMPUTER SCIENCE AND ENGINEERING

LAB 6: Finding GCD using Euclid’s algorithm.


In [ ]: #EUCLIDEAN ALGORITHM
#Find the GCD of (614,124).
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(614 ,124 )

In [ ]: #RELATIVE PRIME
#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 )

In [ ]: #DIVIDES
#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 )

In [ ]: #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
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));

In [ ]: '''USING SYMPY SYMBOLIC LIBRARY FUNCTION'''


from sympy import gcd
gcd (1235 , 2315 )

In [ ]: from sympy import igcd


igcd (3228 ,93)

LAB 7: Solving linear congruence of the form ax ≡ b( mod m).


In [ ]: #Show that the linear congruence 6x ≡ 5( mod 15) has no solution.
from sympy import *
from math import*
a = int( input ('enter integer a '))
b = int( input ('enter integer b '))
m = int( input ('enter integer m '))
d = gcd(a,m)
if (b%d!=0):
print ('the congruence has no integer solution ')
else :
for i in range (1,m-1):
x = (m/a)*i+(b/a)
if(x // 1==x):
print ('the solution of the congruence is ', x)
break

In [ ]: #Find the solution of the congruence 5x ≡ 3(mod 13).


from sympy import *
a = int( input ('enter integer a: '))
b = int( input ('enter integer b: '))
m = int( input ('enter integer m: '))
d=gcd(a,m)
if (b%d!=0):
print ('the congruence has no integer solution ')
else:
for i in range (1,m-1):
x=(m/a)*i+(b/a)
if(x // 1==x):
print('the solution of the congruence is ', x)
break

In [ ]: #Find the inverse of 5 mod 13.


from sympy import gcd
a = int( input ('enter integer a '))
b = int( input ('enter integer b '))
m = int( input ('enter integer m '))
d=gcd(a,m)
if (b%d!=0):
print ('the congruence has no integer solution ');
else:
for i in range (1,m-1):
x=(m/a)*i+(b/a)
if(x // 1==x):
print ('the solution of the congruence is ', x)
break

ELECTRONICS AND COMMUNICATION ENGINEERING

LAB 6: Program to compute area, volume and center of gravity


In [ ]: #DOUBLE AND TRIPLE INTEGRATION
#Evaluate the integral ∫_0^1∫_0^x(x^2+y^2)dydx
from sympy import *
x,y,z = symbols('x y z')
w1 = integrate (x ** 2+y ** 2 ,(y,0,x) ,(x,0,1))
print(w1)

In [ ]: #Evaluate the integral ∫_0^3∫_0^3-x∫_0^3-x-y(xyz)dzdydx


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)

In [ ]: #Evaluate the integral ∫_0^3∫_0^3-x∫_0^3-x-y(xyz)dzdydx


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

In [ ]: #Prove that ∫∫(x^2+y^2)dydx = ∫∫(x^2+y^2)dxdy


from sympy import *
x= Symbol ('x')
y= Symbol ('y')
z= Symbol ('z')
w3= integrate (x ** 2+y ** 2,y,x)
display(w3)
w4 = integrate (x ** 2+y ** 2,x,y)
display(w4)

In [ ]: '''AREA AND VOLUME'''


from sympy import *
x = Symbol ('x')
y = Symbol ('y')
a = 4
b = 6
w3 = 4* integrate (1 ,(y,0 ,(b/a)* sqrt (a ** 2-x ** 2)) ,(x,0,a))
display(w3)

In [ ]: #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')
w3 = 2* integrate (r ,(r,0,a*(1+cos (t))) ,(t,0,pi))
display(w3)

In [ ]: #Find the volume of the tetrahedron bounded by the planes x=0,y=0 and z=0, x/a+y/b+z/c = 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))
display(w2)

In [ ]: '''CENTER OF GRAVITY'''
#Find the center of gravity of cardioid . Plot the graph of cardioid and mark the center of gravity.
import numpy as np
import matplotlib . pyplot as plt
import math
from sympy import *
r = Symbol ('r')
t = Symbol ('t')
a = Symbol ('a')
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))
I = I1/I2
print (I)
I = I.subs (a,5)
plt.axes ( projection = 'polar')
a = 5
rad = np.arange (0, (2 * np.pi), 0.01)
for i in rad :
r = a + (a*np.cos(i))
plt.polar (i,r,'g.')
plt.polar (0,I,'r.')
plt.show ()

LAB 7: Evaluation of improper integrals, Beta and Gamma functions


In [ ]: from sympy import *
x= symbols ('x')
w1= integrate (exp (-x) ,(x,0, float ('inf ')))
display(simplify (w1))

In [ ]: #Evaluate Γ(5) by using definition


from sympy import *
x = symbols ('x')
w1 = integrate (exp (-x)*x ** 4 ,(x,0, float ('inf ')))
display(simplify (w1))

In [ ]: from sympy import *


t,s= symbols ('t,s')
w1= integrate (exp (-s*t)*cos (4*t) ,(t,0,oo))
display(simplify (w1))

In [ ]: #Find Beta(3,5), Gamma(5)


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)

In [ ]: #Calculate Beta(5/2,7/2) and Gamma(5/2).


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)

In [ ]: #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 ')

MECHANICAL AND OTHER ENGINEERING STREAMS

LAB 6: Solution of second order ordinary differential equation and


plotting the solution curve
In [ ]: #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 Particular Solution :\n")
display(PS)
In [ ]: #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()

In [ ]: #Plot the solution curves of y′′ + 2y′ + 2y = cos(2x), y(0) = 0, y′(0) = 0


import numpy as np
from scipy . integrate import odeint
import matplotlib . pyplot as plt
def dU_dx (U, x):
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)
ys = Us[:,0]
ys1 = Us[:,1]
plt.xlabel("x")
plt.ylabel("y")
plt.title(" Solution curves ")
plt.plot(xs ,ys , label ='y');
plt.plot(xs ,ys1 , label ='z');
plt.legend()
plt.show()

In [ ]: #Solve: 3d2x/dt2 + 2dx/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()

LAB 7: Solution of differential equation of oscillations of a spring with


various load
In [ ]: #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]
print(ys)
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 [ ]: #Solve 9d2x/dt2 + 2dx/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]
plt.plot (xs ,ys ,'r-')
plt.xlabel('Time ')
plt.ylabel('Amplitude ')
plt.title('Solution of free and damped case ')
plt.grid(True)
plt.show()

LAB 8: Numerical solution of system of equations, test for consistency


and graphical representation of the solution.
In [ ]: '''HOMOGENOUS EQUATIONS'''
#Solution for the system of linear equations
#Check whether the following system of homogenous linear equation has non-trivial solution.
#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)")

In [ ]: #Check whether the following system of homogenous linear equation has non-trivial solution.
#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)")

In [ ]: '''NON HOMOGENOUS EQUATIONS'''


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

In [ ]: #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 ")

In [ ]: '''ALTERNATE METHOD: USING SYMPY MODULE'''


import sympy as sp
x, y, z = sp.symbols('x y z')
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. solve_linear_system (AB ,x,y,z))
else:
print ("The system of equations is inconsistent ")

In [ ]: #GRAPHICAL REPRESENTATION OF A SOLUTION


#Obain the solution of 3x + 5y = 1; x + y = 1 graphically.
from sympy import *
import numpy as np
import matplotlib . pyplot as plt
x,y= symbols ('x,y')
sol = solve ([3*x+5*y-1,x+y-1],[x,y])
p=sol[x]
q=sol[y]
print ('Point of intersection is A (', p ,',', q, ')\n')
x = np.arange (-10 , 10 , 0.001)
y1 = (1-3*x)/5
y2 = 1-x
plt.plot (x,y1 ,x,y2)
plt.plot (p,q, marker = 'o')
plt.annotate ('A', xy=(p,q), xytext =(p+0.5, q))
plt.xlim (-5,7)
plt.ylim (-7,7)
plt.axhline (y=0)
plt.axvline (x=0)
plt.title ("$3x+5y=1; x+y=1$")
plt.xlabel (" Values of x")
plt.ylabel (" Values of y ")
plt.legend (['$3x+5y=1$ ', '$x+y=1$ '])
plt.grid ()
plt.show ()

In [ ]: #Obtain the solution of 2x + y = 7; 3x − y = 3 graphically.


from sympy import *
import numpy as np
import matplotlib . pyplot as plt
x,y= symbols ('x,y')
sol = solve ([2*x+y-7,3*x-y-3],[x,y])
p = sol[x]
q = sol[y]
print('Point of intersection is A (', p ,',', q, ')\n' )
x = np.arange (-10 , 10 , 0.001)
y1 = 7-2*x
y2 = 3*x-3
plt.plot (x,y1 ,'r')
plt.plot (x,y2 ,'g')
plt.plot (p,q, marker = 'o')
plt.annotate ('A', xy=(p,q), xytext =(p+0.5, q))
plt.xlim (-5,7)
plt.ylim (-7,7)
plt.axhline (y=0)
plt.axvline (x=0)
plt.title ("$2x+y=7; 3x -y=3$")
plt.xlabel (" Values of x")
plt.ylabel (" Values of y ")
plt.legend (['$2x+y=7$ ', '$3x -y-3$ '])
plt.grid ()
plt.show ()

LAB 9: Solution of system of linear equations by Gauss-Seidel method.


In [ ]: #Solve the system of equations using Gauss-Seidel method: 20x+y−2z = 17; 3x+20y−z =−18; 2x − 3y + 20z = 25.
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
x0 = 0
y0 = 0
z0 = 0
count = 1
e = float ( input ('Enter tolerable error : '))
print ('\n Count \tx\ty\tz\n')
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
condition = e1>e and e2>e and e3>e
print ('\n Solution : x= %0.3f , y= %0.3f and z = %0.3f\n'% (x1 ,y1 ,z1))

In [ ]: #Solve x+2y−z = 3; 3x−y+2z = 1; 2x−2y+6z = 2 by Gauss-Seidel Iteration method.


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
x0 ,y0 ,z0 = 0,0,0
e = float ( input ('Enter tolerable error : '))
print ('\n Iteration \t x\t y\t z\n')
for i in range (0,25):
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' %(i, x1 ,y1 ,z1))
e1 = abs(x0-x1);
e2 = abs(y0-y1);
e3 = abs(z0-z1);
x0 = x1
y0 = y1
z0 = z1
if e1>e and e2>e and e3>e:
continue
else:
break
print('\n Solution : x = %0.3f , y = %0.3f and z = %0.3f\n'% (x1 ,y1 ,z1))

In [ ]: from numpy import *


def seidel (a, x ,b):
n = len(a)
for j in range (0, n):
d = b[j]
for i in range (0, n):
if(j != i):
d=d-a[j][i] * x[i]
x[j] = d / a[j][j]
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)

In [25]: #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
def seidel (a, x ,b):
n = len(a)
for j in range (0, n):
d = b[j]
for i in range (0, n):
if(j != i):
d=d-a[j][i] * x[i]
x[j] = d/a[j][j]
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]])
for i in range (0,len (a)):
asum =0
for j in range (0,len(a)):
if (i!=j):
asum = asum + abs(a[i][j])
if(asum <=a[i][i]):
continue
else:
sys.exit ("The system is not diagonally dominant ")
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. ]
[0. ]
[1.1]]

In [ ]: #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)
return x
''' ___MAIN___ '''
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)

LAB 10: Compute eigenvalues and corresponding eigenvectors. Find


dominant and corresponding eigenvector by Rayliegh power method.
In [ ]: #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)
w,v = np.linalg.eig (I)
print ("\n Eigen values : \n", w)
print ("\n Eigen vectors : \n", v)
print (" Eigen value :\n ", w[0])
print ("\n Corresponding Eigen vector :", v[:,0])

In [ ]: #Obtain the eigen values and eigen vectors for the given matrix.
'''A =
1 −3 3
3 −5 3
6 −6 4'''
import numpy as np
I = np.array ([[1,-3,3],[3,-5,3],[6,-6,4]])
print ("\n Given matrix : \n", I)
w,v = np.linalg.eig (I)
print ("\n Eigen values : \n", w)
print ("\n Eigen vectors : \n", v)

In [ ]: '''RAYLEIGH POWER'''
#Compute the numerically largest eigenvalue of P =
'''6 −2 2
−2 3 −1
2 −1 3
by power method.'''
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 ([[6,-2,2 ],
[-2,3,-1],[2,-1,3]])
for i in range (10):
x = np.dot(a, x)
lambda_1 , x = normalize (x)
print ('Eigenvalue :', lambda_1 )
print (' Eigenvector :', x)

In [ ]: #Compute the numerically largest eigenvalue of P =


'''1 1 3
1 5 1
3 1 1
by power method.'''
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)
print ('Eigenvalue :', lambda_1 )
print (' Eigenvector :', x)

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