Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. from numpy import sqrt, array, cos, sin, pi, arange, array
  2. from pylab import plot, show, legend, xlabel, ylabel
  3. %matplotlib inline
  4.  
  5. G = 6.674e-11
  6. M = 5.972e24
  7. m = 7.348e22 # mass of the moon
  8.  
  9. def alpha(r):
  10.     radiusMagnitude = sqrt(x**2 + y**2)
  11.     return -G * M * r / (radiusMagnitude**3)
  12.  
  13. # This program solves dr/dt = f(r,t)
  14. def f(r,t):
  15.    
  16.     # unpack variables
  17.     x = r[0]
  18.     y = r[1]
  19.     vx = r[2]
  20.     vy = r[3]
  21.    
  22.     radiusMagnitude = sqrt(x**2 + y**2)
  23.    
  24.     fx = vx
  25.     fy = vy
  26.     fvx = -G * M * x / (radiusMagnitude**3)
  27.     fvy = -G * M * y / (radiusMagnitude**3)
  28.    
  29.     return array([fx, fy, fvx, fvy], float)
  30.  
  31. # initial conditions
  32. t0 = 0.0                          # initial time
  33. tf = 6.998e6 # 81 days
  34. h = 1 # time step of one hour
  35. tpoints = arange(t0, tf, h) # array of time values
  36.  
  37. x = -3.626e8                          # initial x in meters
  38. y = 0                          # intiial y
  39. vx = 0                # initial vx
  40. vy = 1.077e3       # initial vy m/s
  41. r = array([x, y, vx, vy], float) # initial r vector
  42. xpointsV = []
  43. ypointsV = []
  44. vxpointsV = []
  45. vypointsV = []
  46. PElist = [] # potential energy
  47. KElist = [] # kinetic energy
  48. TElist = [] # total energy
  49.  
  50. vxmid = vx + alpha(x) * 0.5 * h
  51. vymid = vy + alpha(y) * 0.5 * h
  52.  
  53. for t in tpoints:
  54.    
  55.     #verlet method
  56.     xpointsV.append(x)
  57.     ypointsV.append(y)
  58.     vxpointsV.append(vx)
  59.     vypointsV.append(vy)
  60.    
  61.     potential = -G * M * m / (sqrt(x**2 + y**2))
  62.     kinetic = .5 * m * (vx**2 + vy**2)
  63.     total = potential + kinetic
  64.     PElist.append(potential)
  65.     KElist.append(kinetic)
  66.     TElist.append(total)
  67.    
  68.     x += vxmid * h
  69.     y += vymid * h
  70.     vx = vxmid + alpha(x) * 0.5 * h
  71.     vy = vymid + alpha(y) * 0.5 * h
  72.     vxmid += alpha(x) * h
  73.     vymid += alpha(y) * h
  74.    
  75. plot (tpoints, PElist, "r-", label="potential")
  76. plot (tpoints, KElist, "g-", label="kinetic")
  77. plot (tpoints, TElist, "b-", label="total")
  78. xlabel("time")
  79. ylabel("energy (J)")
  80. show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement