Solving second order ODEs
Solving second order ODEs
Aim:
To solve second order ODEs of the transient behaviour of a system (pendulum) and to plot the graph and create animation of simple pendulum.
Objectives:
- To solve second order ODEs
- To plot graphs and create animation of the simple pendulum
Solution Procedure:
- Set input parameters like mass length etc.
- L=1 metre,
- m=1 kg,
- b=0.05.
- g=9.81 m/s2.
- Set initial conditions:
Simulate the motion between 0-20 sec, for angular displacement=0,angular velocity=3 rad/sec at time t=0.
- Plot the graphs.
- Create the animations using image magick.
Code:
#Solving second order ODEs
# By Abhishek Savakar
from matplotlib.pyplot import *
from math import *
from numpy import *
from scipy.integrate import *
def mode1(theta, t, b, g, l, m):
theta1 = theta[0]
theta2 = theta[1]
dtheta1_dt = theta2
dtheta2_dt = -(b / m) * theta2 - (g / l) * sin(theta1)
dtheta_dt = [dtheta1_dt, dtheta2_dt]
return dtheta_dt
# damping coeffcient, lenght of string and mass of the bob
b = 0.05
g = 9.81
l = 1
m = 1
# initial condition
theta_0 = [0, pi / 2]
# time points
t = linspace(0, 20 , 200)
# Solve ODE
theta = odeint(mode1, theta_0, t, args=(b, g, l, m))
# plot results
figure()
plot(t, theta[:, 0], 'b-', Label=r'$\frac{d\theta_1}{dt}=\theta2$')
plot(t, theta[:, 1], 'r--', Label=r'$\frac{d\theta_2}{dt}=\frac{b}{m}\theta_2-\frac{g}{1}sin\theta_1$')
xlabel('Time')
ylabel('Plot')
legend(loc='best')
show()
val = theta[:, 0]
ct = 1
x0 = 0
y0 = 0
# creating animation
for i in range(0, len(val)):
figure()
x1 = sin(val[i])
y1 = -cos(val[i])
plot(x1, y1, 'o', markersize=25)
plot([-0.5, 0.5], [0, 0], 'g', linewidth=4)
plot([x0, x1], [y0, y1], 'r')
xlim([-2, 2])
ylim([-2, 2])
filename = str(ct) + '.png'
savefig(filename)
ct = ct + 1
Code Explanation:
- Importing all required modules.
- Set input parameters like mass length etc.
- Set initial conditions ie angle, time points.
- Use ode solver from scipy module.
- Calculating angle of displacement and velocities.
- Plotting the graphs and saving all graphs.
- Creating simulation of simple pendulum using image magick.
Results:
Successfully plotted time vs plot graph and created animation of the simple pendulum.
YouTube link for animation: