Challenge

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:

  1. To solve second order ODEs
  2. To plot graphs and create animation of the simple pendulum

Solution Procedure:

  1. Set input parameters like mass length etc.
  1. L=1 metre,
  2. m=1 kg,
  3. b=0.05.
  4. g=9.81 m/s2.
  1. Set initial conditions:

Simulate the motion between 0-20 sec, for angular displacement=0,angular velocity=3 rad/sec at time t=0.

  1. Plot the graphs.
  2. 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:

  1. Importing all required modules.
  1. Set input parameters like mass length etc.
  2. Set initial conditions ie angle, time points.
  3. Use ode solver from scipy module.
  4. Calculating angle of displacement and velocities.
  1. Plotting the graphs and saving all graphs.
  2. 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:

https://www.youtube.com/watch?v=n28DCC50FSk

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.