Week 3 - Solving second order ODEs
WEEK -3
PENDULUM -Solving second order ODEs
This is the following code for the given question :
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
# Now we will first assign the inputs of the given damping eqaution
b = .2
g = 9.81
l = 1
m = 1
# Now the initial condition has 2 values in which first one relates to displacment and second relates to velocity
# Also there are only 2values due to fact that equation has 2 degree
initial_cond = [0,3]
# time array with 100 steps
t = np.linspace(0,20,100)
# the differential equation has been splitted into 2 first order equation and after it the solution has been taken into matrix
def motion( theta ,t, b ,g ,l ,m ) :
dtheta1_dt = theta[1] # this theta[1] shows that the output vector(theta) has 2 values out of which first value is assigned to the input variable
dtheta2_dt = (-b/m)*theta[1]- (g/l)*math.sin(theta[0])
dtheta_dt = [dtheta1_dt , dtheta2_dt]
return dtheta_dt
# Now this variable theta has 2 output values stored in it after passing the following parameters because the eqaution has also 2 degree
theta = odeint(motion, initial_cond , t , args = (b ,g ,l , m ))
# extracting the coloumn first from the array theta
x = theta[:,0]
ct = 1
# the for loop has been created because to show that the pendulum has run for 20 sec for differnt values of theta .
for i in x:
x0 = 0
y0 = 0
x1 = (x0 + l*math.sin(i))
y1 = -(y0 + l*math.cos(i))
# plot function
plt.figure()
plt.plot([-2 ,2] , [0,0] , color = "yellow" , linewidth = 3)
plt.plot(x0,y0 , 'o' ,marker = 'o', markersize = 5 , color = "blue" )
plt.plot([ x0,x1] , [y0, y1] , linewidth = 3 , color = "red" )
plt.plot( x1 ,y1 , 'o' ,marker = 'o', markersize = 30 , color = "purple")
filename = 'test%05d.png' % ct # name for saving the filename to create image one by one
plt.savefig(filename)
ct =ct +1
screenshots :
This is a folder in which each image of pendulum is saved .


https://drive.google.com/file/d/1jtM6g4K5RQZmRmSVv2dcjvTHf0WevoU_/view?usp=sharing
This is the link for gif animation .
https://drive.google.com/drive/folders/1F_DX3Rh9S0TxxcE_hueyOScia_jkOTq2?usp=sharing
This is the folder in which all the images are saved .