Advertisement
ChrisRodman55

Chris's Python Script (Simulation of Double Pendulum)

Mar 28th, 2020
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. from numpy import sin, cos
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import scipy.integrate as integrate
  5. import matplotlib.animation as animation
  6.  
  7. G = 9.8  # acceleration due to gravity, in m/s^2
  8. L1 = 1.0  # length of pendulum 1 in m
  9. L2 = 1.0  # length of pendulum 2 in m
  10. M1 = 1.0  # mass of pendulum 1 in kg
  11. M2 = 1.0  # mass of pendulum 2 in kg
  12.  
  13. def derivs(state, t): # dynamics of system
  14.     dydx = np.zeros_like(state)
  15.     dydx[0] = state[1]
  16.     del_ = state[2] - state[0]
  17.     den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)
  18.     dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) +                  M2*G*sin(state[2])*cos(del_) +
  19.               M2*L2*state[3]*state[3]*sin(del_) - (M1 +  M2)*G*sin(state[0]))/den1
  20.     dydx[2] = state[3]
  21.     den2 = (L2/L1)*den1
  22.     dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_) + (M1 + M2)*G*sin(state[0])*cos(del_) -
  23.                (M1 + M2)*L1*state[1]*state[1]*sin(del_) - (M1 + M2)*G*sin(state[2]))/den2
  24.  
  25.     return dydx
  26.  
  27. dt = 0.05
  28. t = np.arange(0.0, 20, dt)
  29.  
  30. th1 = 90.0
  31. w1 = 0.0
  32. th2 = 0.0
  33. w2 = 0.0
  34.  
  35. state = np.radians([th1, w1, th2, w2]) # initial state
  36. y = integrate.odeint(derivs, state, t) # integrate  ODE using scipy.integrate.
  37.  
  38. x1 = L1*sin(y[:, 0])
  39. y1 = -L1*cos(y[:, 0])
  40.  
  41. x2 = L2*sin(y[:, 2]) + x1
  42. y2 = -L2*cos(y[:, 2]) + y1
  43.  
  44. fig = plt.figure()
  45. ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))
  46. ax.grid()
  47.  
  48. line, = ax.plot([], [], 'o-', lw=2)
  49. time_template = 'time = %.1fs'
  50. time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
  51.  
  52. def init():
  53.     line.set_data([], [])
  54.     time_text.set_text('')
  55.  
  56.     return line, time_text
  57.  
  58. def animate(i):
  59.     thisx = [0, x1[i], x2[i]]  # x codrin of point making pendulum  
  60.     thisy = [0, y1[i], y2[i]]  # y cord of point
  61.     line.set_data(thisx, thisy)
  62.     time_text.set_text(time_template % (i*dt))
  63.  
  64.     return line, time_text
  65.  
  66. ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),interval=25, blit=True, init_func=init)
  67.  
  68. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement