I Sem Mathematics Lab
I Sem Mathematics Lab
I Sem Mathematics Lab
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 [ ]: #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 [ ]: #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 [ ]: #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 ()
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 [ ]: #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 [ ]: #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 [ ]: #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 [ ]: #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 [ ]: #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 [ ]: #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 ()
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()
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()
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 [ ]: #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 [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)
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)