1 II-II Mech R20 Python Programming Lab
1 II-II Mech R20 Python Programming Lab
Course Objective: To understand the PYTHON environment and make numerical computations and
analysis.
Course Outcomes:
At the end of the course, student will be able to
CO1 Solve the different methods for linear, non-linear and differential equations
CO2 Learn the PYTHON Programming language
CO3 Familiar with the strings and matrices in PYTHON
CO4 Write the Program scripts and functions in PYTHON to solve the methods
CONTENTS
Write Programs in PYTHON Programming for the following:
1.To find the roots of non-linear equation using Bisection method
2.To find the roots of non-linear equation using Newton Raphson’s method.
3.Curve fitting by least – square approximations
4.To solve the system of linear equations using Gauss - elimination method
5.To solve the system of linear equations using Gauss - Siedal method
6.To solve the system of linear equations using Gauss - Jordan method
7.To integrate numerically using Trapezoidal rule
8.To integrate numerically using Simpsons rule
9.To find the largest eigen value of a matrix by Power – method
10. To find numerical solution of ordinary differential equations by Euler’s method
11. To find numerical solution of ordinary differential equations by Runge-Kutta method
12. To find numerical solution of ordinary differential equations by Milne’s method
13. To find the numerical solution of Laplace equation
14. To find the numerical solution of Wave equation
15. To find the solution of a tri-diagonal matrix using Thomas algorithm
16. To fit a straight using least square technique
Software Details
Note:
Comment must be written with pencil
The comments starts with #
Ex: # Pseudocode For Bisection Method
2 II-II Mech R20 Python Programming Lab
Program:
import sys
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2-4
def bisection(a,b,tol):
i=1
while abs(b-a)>tol:
c= (a+b)/2
print("iterations of i = ",i,"x = ",c,"f(x) = ",f(c))
if f(c)==0:
print("root is found at",c)
return c
elif f(c)<0:
a=c
else:
b=c
i= i+1
return c
if f(a)*f(b)>0:
print("No roots existed in the equation")
sys.exit()
else:
s = bisection(a, b, tol)
x= np.linspace(a,b,100)
plt.plot(x,f(x))
plt.xlabel("x axis")
plt.ylabel("f(x)")
plt.title("Bisection
Graph") plt.grid()
plt.plot(s,0,marker='o',color='red')
plt.show()
Output:
Enter the input a:-2
Enter the input b:4
Enter the tolerance:1e-100
iterations of i = 1 x = 1.0 f(x) = -3.0
iterations of i = 2 x = 2.5 f(x) = 2.25
iterations of i = 3 x = 1.75 f(x) = -0.9375
iterations of i = 4 x = 2.125 f(x) = 0.515625
iterations of i = 5 x = 1.9375 f(x) = -0.24609375
iterations of i = 6 x = 2.03125 f(x) = 0.1259765625 iterations
of i = 7 x = 1.984375 f(x) = -0.062255859375
iterations of i = 8 x = 2.0078125 f(x) = 0.03131103515625
iterations of i = 9 x = 1.99609375 f(x) = -0.0156097412109375
iterations of i = 10 x = 2.001953125 f(x) = 0.007816314697265625
iterations of i = 11 x = 1.9990234375 f(x) = -0.0039052963256835938
iterations of i = 12 x = 2.00048828125 f(x) = 0.0019533634185791016
iterations of i = 13 x = 1.999755859375 f(x) = -0.0009765028953552246
iterations of i = 14 x = 2.0001220703125 f(x) = 0.0004882961511611938
iterations of i = 15 x = 1.99993896484375 f(x) = -0.00024413689970970154
iterations of i = 16 x = 2.000030517578125 f(x) = 0.00012207124382257462
iterations of i = 17 x = 1.9999847412109375 f(x) = -6.1034923419356346e-05
iterations of i = 18 x = 2.0000076293945312 f(x) = 3.0517636332660913e-05
iterations of i = 19 x = 1.9999961853027344 f(x) = -1.5258774510584772e-05
iterations of i = 20 x = 2.000001907348633 f(x) = 7.629398169228807e-06
iterations of i = 21 x = 1.9999990463256836 f(x) = -3.8146963561302982e-06
iterations of i = 22 x = 2.000000476837158 f(x) = 1.9073488601861754e-06
iterations of i = 23 x = 1.999999761581421 f(x) = -9.536742595628311e-07
iterations of i = 24 x = 2.0000001192092896 f(x) = 4.768371724139797e-07
4 II-II Mech R20 Python Programming Lab
Graph:
6 II-II Mech R20 Python Programming Lab
Program:
import sys
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
x=sp.Symbol('x')
f= input("Enter equation:")
f_print =f
f = sp.sympify(f) # Converting string to sympy Expresion
f_prime= f.diff(x) # creating differential equation from original equation
f_prime= sp.lambdify(x,f_prime) # Converting differential equation to function
f = sp.lambdify(x,f) # Converting differential equation to function
x_n = x- (f(x)/f_prime(x))
print("iteration i:",i,"x= ",x_n,"f(x)=",f(x))
m=str(x_n)
"""
print(m)
print(" ")
print(m[0:n+2])
"""
if m[0:n+2]==g[0:n+2]:
condition =False
else:
condition=True
x=x_n
i=i+1
x=str(x)
s= x[0:n+2]
print("The Root of equation f(x) ={} is {}".format(f_print,x))
x= np.linspace(-5,5,100)
plt.plot(x,f(x))
plt.xlabel("x axis")
plt.ylabel("f(x)")
plt.title("Newton Rapson Method")
plt.grid()
s=float(s)
plt.plot(s,0,marker='o',color='red')
plt.show()
Output:
Enter equation:x**3-8
Graph:
9 II-II Mech R20 Python Programming Lab
plt.plot(x,y,'o',markersize=5)
plt.plot(x,b*np.exp(alpha[0]*x),'r')
plt.xlabel("X axis")
plt.ylabel("y=b*e^a*x")
plt.title("Non-Linear Curve Fitting by least square Approximation")
plt.grid()
plt.show()
Output:
The coefficient of a = 0.2657667044851251 and b= 0.13658721956743416
10 II-II Mech R20 Python Programming Lab
Graph:
11 II-II Mech R20 Python Programming Lab
A= np.array(
[
[4.0,-2.0,1.0],
[-2.0,4.0,-2.0],
[1.0,-2.0,4.0]
])
B= np.array(
[11.0,-16.0,17.0]
)
n = len(A)
x = np.zeros((n,n+1))
print("\nX matrix with zeros filling is:\n",x)
#Eliminating Matrix
for i in range(n):
if x[i][i]==0:
print("divdide error")
break
for j in range(n):
if i!=j:
r = x[j][i]/x[i][i]
for k in range(n+1):
12 II-II Mech R20 Python Programming Lab
# Substituting values
for i in range(n):
B[i] = x[i][n]/x[i][i]
Output:
The matrix A :
[[ 4. -2. 1.]
[-2. 4. -2.]
[ 1. -2. 4.]]
The matrix B :
[ 11. -16. 17.]
After Iteration i = 0
[[ 4. -2. 1. 11. ]
[ 0. 3. -1.5 -10.5]
[ 1. -2. 4. 17. ]]
After Iteration i = 0
[[ 4. -2. 1. 11. ]
[ 0. 3. -1.5 -10.5 ]
[ 0. -1.5 3.75 14.25]]
After Iteration i = 1
[[ 4. 0. 0. 4. ]
[ 0. 3. -1.5 -10.5 ]
13 II-II Mech R20 Python Programming Lab
After Iteration i = 1
[[ 4. 0. 0. 4. ]
[ 0. 3. -1.5 -10.5]
[ 0. 0. 3. 9. ]]
After Iteration i = 2
[[ 4. 0. 0. 4. ]
[ 0. 3. -1.5 -10.5]
[ 0. 0. 3. 9. ]]
After Iteration i = 2
[[ 4. 0. 0. 4.]
[ 0. 3. 0. -6.]
[ 0. 0. 3. 9.]]
x1= 1.0
x2= -2.0
x3= 3.0
14 II-II Mech R20 Python Programming Lab
condition =True
while condition:
x1 = f1(x0,y0,z0)
y1 = f2(x1,y0,z0)
z1 = f3(x1,y1,z0)
#checking the tolerance of e1 ,e2 and e3
e1= abs(x0-x1)
e2= abs(y0-y1)
e3= abs(z0-z1)
iteration = iteration+1
#Reassigning the x1, y1,z1 to x0,y0 and z0
x0=x1
y0=y1
z0=z1
print(f"The value of x,y and z are {x1}, {y1}, {z1} of {iteration} iteration")
Output:
The value of x,y and z are 1.0000000000000002, 2.0, 1.0 of 33 iteration
15 II-II Mech R20 Python Programming Lab
# defined matrix
sd = [
[1, 1, 2, 9],
[2, 4, -3, 1],
[3, 6, -5, 0]
]
for i in range(len(sd)):
getone(i)
for j in range(len(sd)):
if i != j:
getzero(j, i)
16 II-II Mech R20 Python Programming Lab
for i in range(len(sd)):
x[i] = sd[i][n]/sd[i][i]
Output:
The original Matrix:
1 1 2 9
2 4 -3 1
3 6 -5 0
x= 1.0
y= 2.0
z= 3.0
17 II-II Mech R20 Python Programming Lab
import numpy as np
f= lambda x: x*np.sin(x) #defining Equation in numpy
a=0.0
b=np.pi/2
n=10 #the number of intervals
h=(b-a)/n
s= 0.5*(f(a)+f(b))
for i in
range(1,n): s=
s+f(a+i*h)
sol = h*s
print("Integral of equation f(x) = x*sin(x) from 0 to pi/2 is" , sol)
Output:
Integral of equation f(x) = x*sin(x) from 0 to pi/2 is 1.0020587067645337
18 II-II Mech R20 Python Programming Lab
#Formula
ℎ
ƒ= [{ ƒ(𝑥𝑎) + ƒ(𝑥𝑏) } + ∑i=1,3,5..
𝑛−1
4ƒ 𝑛−2
3 (𝑥i) + ∑ 2ƒ(𝑥i)]
i=2,4,6..
import numpy as np
# Defining Equation
def f(x):
return x*np.sin(x)
def simpson(a,b):
s=0
t=0
for i in range(1,n):
if i%2==1:
x = a+i*h
s = s+f(x)
else:
x = a+i*h
t = t+f(x)
Integral = (f(a)+f(b)+4*s+2*t)*h/3
print("The Integral is %.9f" %Integral)
Output:
Enter the first point:0
Number of Panels:100
The Integral is 0.999927230
19 II-II Mech R20 Python Programming Lab
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([[0, 2,5],
[2, 3,6],
[5, 3,6]
])
n= int(input("Enter the no of iterations:"))
for i in range(n):
x = np.dot(a, x)
lambda_1, x = normalize(x)
print("iteration i= ",i,"eigen value=",lambda_1,"Eigen Vector = ",x)
print('Eigenvalue:', lambda_1)
print('Eigenvector:', x)
Output:
Enter the no of iterations:15
iteration i= 0 eigen value= 14 Eigen Vector = [0.5 0.78571429 1. ]
iteration i= 1 eigen value= 10.857142857142858 Eigen Vector = [0.60526316 0.86184211
1. ]
iteration i= 2 eigen value= 11.611842105263158 Eigen Vector = [0.57903683 0.84362606
1. ]
iteration i= 3 eigen value= 11.426062322946176 Eigen Vector = [0.58526305 0.84796946
1. ]
iteration i= 4 eigen value= 11.470223632667228 Eigen Vector = [0.58376708 0.84692634
1. ]
iteration i= 5 eigen value= 11.45961438699637 Eigen Vector = [0.58412547 0.84717625 1.
]
iteration i= 6 eigen value= 11.462156118178477 Eigen Vector = [0.58403955 0.84711634
1. ]
iteration i= 7 eigen value= 11.461546760353588 Eigen Vector = [0.58406015 0.8471307 1.
]
iteration i= 8 eigen value= 11.461692824210132 Eigen Vector = [0.58405521 0.84712726
1. ]
iteration i= 9 eigen value= 11.461657811107015 Eigen Vector = [0.58405639 0.84712808
1. ]
20 II-II Mech R20 Python Programming Lab
Program:
# function to be solved
def f(x,y):
return x+y
# Euler method
def euler(x0,y0,xn,n):
# Calculating step size
h = (xn-x0)/n
print('\n-----------SOLUTION----------')
print(' ')
print('x0\t\ty0\t\tslope\t\tyn')
print(' ')
for i in range(n):
slope = f(x0, y0)
yn = y0 + h *
slope
print('%.4f\t%.4f\t%0.4f\t%.4f'% (x0,y0,slope,yn) )
print(' ')
y0 = yn
x0 = x0+h
# Inputs
print('Enter initial conditions:')
x0 = float(input('x0 = '))
y0 = float(input('y0 = '))
Output:
x0 = 0
y0 = 1
Enter calculation point:
xn = 1
Enter number of steps:
Number of steps = 20
-----------SOLUTION-----------
x0 y0 slope yn
At x=1.0000, y=3.3066
24 II-II Mech R20 Python Programming Lab
# RK-4 method
def rk4(x0,y0,xn,n):
print('\n--------SOLUTION--------')
print(' ')
print('x0\t\t\t\ty0\t\t\tyn')
print(' ')
for i in range(n):
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))) k =
(k1+2*k2+2*k3+k4)/6 yn =
y0 + k
print('%.4f\t\t%.4f\t\t%.4f'% (x0,y0,yn) )
print(' ')
y0 = yn
x0 = x0+h
print('\nAt x=%.4f, y=%.4f' %(xn,yn))
# Inputs
print('Enter initial conditions:')
x0 = float(input('x0 = '))
y0 = float(input('y0 = '))
Output:
Enter initial conditions:
x0 = 0
y0 = 1
xn = 6
Number of steps = 15
SOLUTION
x0 y0 yn
At x=6.0000, y=799.1167
27 II-II Mech R20 Python Programming Lab
x0 = 0
y0 = 2
xf = 1
n = 11
deltax = (xf-x0)/(n-1)
x = np.linspace(x0,xf,n)
def f(x,y):
return y-x
y = np.zeros([n])
y[0] = y0
py = np.zeros([n])
for i in range(0,4):
py[i] = None
for i in range(1,4):
k1 = deltax*f(x[i-1],y0)
k2 =
deltax*f(x[i-1]+deltax/2,y0+k1/2) k3
= deltax*f(x[i-1]+deltax/2,y0+k2/2)
k4 = deltax*f(x[i-1]+deltax,y0+k3)
y[i] = y0 + (k1 + 2*k2 + 2*k3 + k4)/6
y0 = y[i]
for i in range(4,n):
py[i] = 4*deltax/3*(2*f(x[i-1],y[i-1]) - f(x[i-2],y[i-2]) + 2*f(x[i-3],y[i-3]) ) + y[i-4]
y[i] = deltax/3*( f(x[i],py[i]) + 4*f(x[i-1],y[i-1]) + f(x[i-2],y[i-2]) ) + y[i-2]
plt.plot(x,y,'o')
plt.xlabel("Value of x")
plt.ylabel("Value of y")
plt.title("Approximation Solution with Milne's Method")
plt.show()
28 II-II Mech R20 Python Programming Lab
Output:
x_n py_n y_n
0.0 nan 2.000000
0.1 nan 2.205171
0.2 nan 2.421403
0.3 nan 2.649858
0.4 2.891821 2.891824
0.5 3.148717 3.148721
0.6 3.422114 3.422119
0.7 3.713747 3.713752
0.8 4.025535 4.025541
0.9 4.359596 4.359603
1.0 4.718274 4.718282
Graph:
29 II-II Mech R20 Python Programming Lab