双摆问题

这个动画说明了双摆问题。

双摆公式从 http://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c 的C代码翻译而来。

  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. G = 9.8 # acceleration due to gravity, in m/s^2
  7. L1 = 1.0 # length of pendulum 1 in m
  8. L2 = 1.0 # length of pendulum 2 in m
  9. M1 = 1.0 # mass of pendulum 1 in kg
  10. M2 = 1.0 # mass of pendulum 2 in kg
  11. def derivs(state, t):
  12. dydx = np.zeros_like(state)
  13. dydx[0] = state[1]
  14. del_ = state[2] - state[0]
  15. den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)
  16. dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) +
  17. M2*G*sin(state[2])*cos(del_) +
  18. M2*L2*state[3]*state[3]*sin(del_) -
  19. (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_) +
  23. (M1 + M2)*G*sin(state[0])*cos(del_) -
  24. (M1 + M2)*L1*state[1]*state[1]*sin(del_) -
  25. (M1 + M2)*G*sin(state[2]))/den2
  26. return dydx
  27. # create a time array from 0..100 sampled at 0.05 second steps
  28. dt = 0.05
  29. t = np.arange(0.0, 20, dt)
  30. # th1 and th2 are the initial angles (degrees)
  31. # w10 and w20 are the initial angular velocities (degrees per second)
  32. th1 = 120.0
  33. w1 = 0.0
  34. th2 = -10.0
  35. w2 = 0.0
  36. # initial state
  37. state = np.radians([th1, w1, th2, w2])
  38. # integrate your ODE using scipy.integrate.
  39. y = integrate.odeint(derivs, state, t)
  40. x1 = L1*sin(y[:, 0])
  41. y1 = -L1*cos(y[:, 0])
  42. x2 = L2*sin(y[:, 2]) + x1
  43. y2 = -L2*cos(y[:, 2]) + y1
  44. fig = plt.figure()
  45. ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))
  46. ax.set_aspect('equal')
  47. ax.grid()
  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. def init():
  52. line.set_data([], [])
  53. time_text.set_text('')
  54. return line, time_text
  55. def animate(i):
  56. thisx = [0, x1[i], x2[i]]
  57. thisy = [0, y1[i], y2[i]]
  58. line.set_data(thisx, thisy)
  59. time_text.set_text(time_template % (i*dt))
  60. return line, time_text
  61. ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),
  62. interval=25, blit=True, init_func=init)
  63. plt.show()

下载这个示例