Week 3 - Solving second order ODEs
Aim :- To Write a program in Python that will simulate the pendulum motion and solving the following ode which represents the equation of motion of a simple pendulum with damping.
Theory :- In Engineering, ODE is used to describe the transient behavior of a system. A simple example is a pendulum.
The way the pendulum moves depends on the Newtons second law. When this law is written down, we get a second order Ordinary Differential Equation that describes the position of the "ball" w.r.t time. Similarly, there are hundreds of ODEs that describe key phenomena.
From the above equation,
g = gravity in m/s2,
L = length of the pendulum in m,
m = mass of the ball in kg,
b=damping coefficient.
Using the given values
L=1 metre,
m=1 kg,
b=0.05.
g=9.81 m/s2.
The Main
#importing required modules
import math
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
#function
def model(theta,t,b,g,m,l):
theta1=theta[0]
theta2=theta[1]
dtheta1_dt=theta2
dtheta2_dt=-(b/m)*theta2-(g/1)*math.sin(theta1)
dtheta_dt=[dtheta1_dt,dtheta2_dt]
return dtheta_dt
#inputs required
b=0.05
g=9.81
l=1
m=1
theta_0=[0,3]
t=np.linspace(0,20,200)
#solving ode
theta=odeint(model,theta_0,t,args = (b,g,l,m))
#plotting result
plt.figure()
plt.plot(t,theta[:,0],'g',label=r'Angular displacement')
plt.plot(t,theta[:,1],'b',label=r'Angular velocity')
plt.xlabel('plot')
plt.ylabel('Time')
plt.legend(loc='best')
plt.show()
#Animation step
ct=1
x0=5
y0=5
for i in range(len(t)):
x1=x0+1*math.sin(theta[i,0])
y1=y0-1*math.cos(theta[i,0])
filename='pendulum'+str(ct)+'.png'
plt.figure()
plt.plot([4,6],[5,5],'k-')
plt.plot([x0,x1],[y0,y1])
plt.plot(x1,y1,marker='o',markersize='10')
plt.axis([3.5,6.5,3,6])
plt.savefig(filename)
ct=ct+1
Explanation
we had imported the plot using the 'import'
for creating the animation we use for loop.theta_0 rages from 0-3m/s2 and images were saved.
Errors Faced
There were error faced while running
which we resolved later
and then we run simulation.
output
Run