Week 3 - Solving second order ODEs
Introduction: this assignment is about making a simulation of a pendulum using various module in python.essentially what we do is use a differential equation to define the motion of a pendulum and then use the equation in finding the position of the pendulum at different point of time and then stitching them together ,to make a video.
Explanation:
we start with importing all the necessary modules to get the job done(numpy,scipy,matplot,math).after the module import ,define a function which describes the differential equation of motion of the pendulum ,for the computation sake we convert the second order ode to 2 first order odes,thus set as return value for the function.then define all the constant which define the properties of the pendulum(length, damping factor, mass, acceleration due to gravity etc).then define a initial condition for the differential eqn and then using the odeint function we integrate the differential equation to find the displacement values at different points of time.
Then using the plot option different positions of the pendulum are plotted int sequence and saved in the current working directory.
#pendulum motion
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
#function definition
def model(theta,t,b,g,l,m):
theta1=theta[0]
theta2=theta[1]
d_theta1=theta2
d_theta2=-(b/m)*theta2-(g/l)*math.sin(theta1)
d_theta_dt=[d_theta1,d_theta2]
return d_theta_dt
#constants
b=0.02
g=9.81
l=1
m=0.1
#initial condition
theta_0=[0,3]
#time_intrvals
t=np.linspace(0,20,100)
#solve ode
theta=odeint(model,theta_0,t,args=(b,g,l,m))
disp=[]
x_1=0
y_1=0
ct=0
for i in theta[:,0]:
disp.append(i)
for i in disp:
x=l*math.cos(i+225)
y=l*math.sin(i+225)
file_name=str(ct)+'.png.'
plt.figure(ct)
plt.plot([x_1,x],[y_1,y],'o-',)
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.savefig(file_name)
ct=ct+1
Conclusion:
the assignment was successfully executed and the link to the video is given below