[关闭]
@wudawufanfan 2017-01-08T11:43:21.000000Z 字数 1798 阅读 517

在此处输入标题

未分类


在此输入正文

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4. import random
  5. fig = plt.figure(figsize=(7,7))
  6. ax1 = fig.add_subplot(1,1,1)
  7. ax2 = fig.add_subplot(2,1,1)
  8. ax3 = fig.add_subplot(3,1,1)
  9. fig.subplots_adjust(hspace=.45)
  10. # Spring data
  11. k = 100
  12. m = 20
  13. w = np.sqrt(k/m)
  14. phi = 2
  15. A = 2
  16. period = 2*np.pi/w
  17. frequency = 1/period
  18. print("Period:",period,"seconds",sep=" ")
  19. print("Frequency:",frequency,"Hz",sep=" ")
  20. print("k: ",k,"N/m",sep=" ")
  21. def fun(t):
  22. global w,phi,A
  23. return A*np.sin(w*t+phi)
  24. def vel(t):
  25. global w,phi,A
  26. return A*w*np.cos(w*t+phi)
  27. def acceleration(t):
  28. global w,phi,A
  29. return -A*w**2*np.sin(w*t+phi)
  30. def position(x):
  31. x1 = x-1
  32. x2 = x+1
  33. y1 = 1
  34. y2 = -1
  35. p1 = [x1,y2]
  36. p2 = [x2,y2]
  37. p3 = [x2,y1]
  38. p4 = [x1,y1]
  39. return [p1,p2,p3,p4]
  40. counter = 0
  41. xt = [0]
  42. yt = [0]
  43. vy = [0]
  44. acy = [0]
  45. def animate(i):
  46. global counter, xt,yt,A,vy,acy
  47. ax3.clear()
  48. plt.subplot(311)
  49. # configure X axes
  50. plt.xlim(-3.5,3.5)
  51. # configure Y axes
  52. plt.ylim(-2,2)
  53. # labels
  54. plt.xlabel("x")
  55. plt.ylabel("y")
  56. plt.title("Motion of an ideal spring")
  57. p1 = [position(fun(counter))[0][0],position(fun(counter))[0][1]]
  58. p2 = [position(fun(counter))[1][0],position(fun(counter))[1][1]]
  59. p3 = [position(fun(counter))[2][0],position(fun(counter))[2][1]]
  60. p4 = [position(fun(counter))[3][0],position(fun(counter))[3][1]]
  61. x = [p1[0],p2[0],p3[0],p4[0],p1[0]]
  62. y = [p1[1],p2[1],p3[1],p4[1],p1[1]]
  63. linex = [-4,p1[0]]
  64. liney = [0,0]
  65. plt.plot(x,y,lw=5,color="blue")
  66. plt.plot(linex,liney,color="red",ls=":",lw=5)
  67. plt.subplot(312)
  68. xt.append(counter)
  69. vy.append(vel(counter))
  70. plt.title("Velocity")
  71. plt.xlim(0,15)
  72. plt.ylim(-A*w-0.5,A*w+0.5)
  73. plt.plot(xt,vy,lw=1,color="green")
  74. plt.plot([0,15],[0,0],lw=0.5,color="black")
  75. plt.subplot(313)
  76. acy.append(acceleration(counter))
  77. plt.title("Acceleration")
  78. plt.xlim(0,15)
  79. plt.ylim(-A*w**2-0.5,A*w**2+0.5)
  80. plt.plot(xt,acy,lw=1,color="green")
  81. plt.plot([0,15],[0,0],lw=0.5,color="black")
  82. counter += 0.1
  83. ani = animation.FuncAnimation(fig,animate,interval=2)
  84. plt.show()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注