Project

Solving the 2nd order ODE and plotting the motion of the simple pendulum

OBJECTIVE:-

To build up a code in PYTHON that stimulates the transient behavior of a simple pendulum and an animation video of the motion of it.

The given ODE describes the simple pendulum phenomenon:-

`d^2/dt^2(theta)+(b/m)*(d/dt(theta))+(g/l)*sin(theta)=0`

In 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.

Given parameters:-

L=1 metre,

m=1 kg,

b=0.05.

g=9.81 m/s2.

`d^2/dt^2(theta)+(b/m)*(d/dt(theta))+g/lsin(theta)=0`

`if theta=theta_1`

`d/dt(theta)=d/dt(theta_1)=theta_2``d^2/dt^2(theta)=d/dt(d/dt(theta_1))=d/dt(theta_2)`

then,

`d/dt(theta_2)=(-b/m)*(theta_2)-(g/l)*sin(theta1)`

Following is the code for the simple pendulum:-

\'\'\'
CODE TO SOLVE ODE REPRESENTING EQUATION OF MOTION OF A PENDULUM
\'\'\'

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt 
import math

#function that returns dz/dt
def model (theta,t,b,g,l,m):
	theta1=theta[0]
	theta2=theta[1]
	dtheta1_dt=theta2
	dtheta2_dt=-(b/m)*theta2 - (g/l)*math.sin(theta1)
	dtheta_dt=[dtheta1_dt,dtheta2_dt]
	return dtheta_dt

#inputs given
b=0.05
g=9.81
l=1
m=1 

#initial condition
theta_0=[0,3]

#time_points
t=np.linspace(0,20,200)

theta=odeint(model,theta_0,t,args=(b,g,l,m))

#PLOTTING THE GRAPH
plt.plot(t,theta[:,0],\'-\',label=\'displacement\')
plt.plot(t,theta[:,1],\'--\',label=\'velocity\')
plt.legend()
plt.xlabel(\'time\')
plt.ylabel(\'displacement velocity\')
plt.show()

y=theta[:,0]
ct=1

#FOR SAVING THE ANIMATION VIDEO AND PLOTS
for ang	in y:
	x1=0;y1=0
	x2=1*math.sin(ang)
	y2=1*math.cos(ang)
	file=\'test%05d.png\'%ct
	plt.figure()
	plt.plot([-1.5,1.5],[0,0],linewidth=8)
	plt.plot([x1,x2],[y1,y2],linewidth=3)
	plt.plot(x2,y2,\'o\',markersize=15)
	plt.xlim([-1.5,1.5])
	plt.ylim([-1.5,1.5])
	plt.savefig(file)
	ct=ct+1

I have used the odeint function to solve the first 2 ODE and find out the results using the function then plot the results. Then, for an animation of the motion of the simple pendulum, I have separated the displacement value and store the theta value in a separate variable and then the various position of the simple pendulum is saved and plotted.

OUTPUTS:-

\"\"

Youtube link FOR ANIMATION VIDEO:-

https://www.youtube.com/watch?v=KiBPr7h7TXc&feature=youtu.be

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.