Challenge

Week 3 - Solving second order ODEs

AIM : To write a program that solves the given ODE, i.e the equation of motion of a simple pendulum with damping, and also to simulate the motion of a pendulum.

THEORY :

Shown above is the second order ODE of the motion of a simple pendulum where,

theta = angle the pendulum makes with the vertical at any instant of time

t = time

b = damping constant

m = mass

g = acceleration due to gravity (9.81 m/s^2)

L = length of the pendulum

PROCEDURE :

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

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
b = 0.05
g = 9.81
l = 1
m = 0.1

theta_0 = [0,5]
t = np.linspace(0,10,150)

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

plt.plot(t,theta[:,0])
plt.plot(t,theta[:,1])
plt.show()


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.xlim([3,7])
	plt.ylim([3,6])
	plt.savefig(filename)
	ct=ct+1

Initially the modules required in the program were imported.

Then a function that splits the second order ODE into two first order ODE was defined, whose arguments are all the constants/variables in the actual ODE.

Then the input parameters were declared.

After that, the initial values of theta was given in a list, the first value being for theta1, and second for theta2.

Using the method linspace from the numpy module, 150 instants of time were taken between 0 and 10 seconds.

After that, using the method "odeint" from the scipy module, the ODE was solved with the function that was declared in the beginning of the program.

Then the plots were plotted using the matplotlib module.

After that, using the matplotlib module again, with the help of marker and markersize commands, pictures of different instants in the pendulum's motion were plotted which were stitched together later to complete the animation.

RESULT :

CONCLUSION :

The program for solving the ODE of the motion of a simple pendulum and for simulating an animation of the motion of the pendulum was successfully written.

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.