Advertisement
Ebo1984

gravity sim

Dec 16th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import matplotlib.animation as anim
  3. import numpy as np
  4. from numpy.random import normal as nr
  5. import math
  6.  
  7. class Planet(object):
  8.     def __init__(self,x,y,vx,vy,m):
  9.         self.x = x
  10.         self.y = y
  11.         self.vx = vx
  12.         self.vy = vy
  13.         self.m = m
  14.  
  15. fig, ax = plt.subplots()
  16. plist = []
  17. planets, = ax.plot([], [], 'o', ms=10, alpha=0.75)
  18.  
  19. au = 1.5e11
  20.  
  21. earth_x = 1 * au
  22. earth_y = 0.
  23. earth_vx = 0.
  24. earth_vy = 29783.
  25. earth_m = 5.74e24
  26. sun_m = 2.0e30
  27.  
  28.  
  29.  
  30.  
  31. plist.append(Planet(earth_x,earth_y,earth_vx,earth_vy,earth_m))
  32. plist.append(Planet(0.,0.,0.,0.,sun_m))
  33.  
  34. def force(x1,y1,x2,y2,m1,m2):
  35.     g = 6.67e-11
  36.  
  37.     dx = x2 - x1
  38.     dy = y2 - y1
  39.  
  40.     dd = dx**2 + dy**2
  41.     dist = np.sqrt(dd)
  42.    
  43.     f = g * m1 * m2 * (1./dist**2)
  44.    
  45.     a = math.atan2(dy, dx)
  46.    
  47.     fx = f * np.cos(a)
  48.     fy = f * np.sin(a)
  49.  
  50.     return fx, fy
  51.  
  52. def move(x,y,vx,vy,fx,fy,m):
  53.  
  54.     dt = 3600.
  55.  
  56.     vx += (fx/m)  
  57.     vy += (fy/m)
  58.     x += (vx * dt)
  59.     y += (vy * dt)
  60.  
  61.     return x, y, vx, vy
  62.  
  63. def init():
  64.  
  65.     planets.set_data([],[])
  66.  
  67.     ax.set_xlim(-1e12,1e12)
  68.     ax.set_ylim(-1e12,1e12)
  69.  
  70.     return planets,
  71.  
  72. def animate(i):
  73.     xdata, ydata = [],[]
  74.  
  75.     for p in plist:
  76.         t_fx = t_fy = 0.0
  77.  
  78.         for o in plist:
  79.  
  80.             if o != p:
  81.                 fx, fy = force(p.x,p.y,o.x,o.y,p.m,o.m)
  82.  
  83.                 t_fx += fx
  84.                 t_fy += fy
  85.                
  86.         p.x, p.y, p.vx, p.vy = move(p.x,p.y,p.vx,p.vy,t_fx,t_fy,p.m)
  87.        
  88.         xdata.append(p.x)
  89.         ydata.append(p.y)
  90.  
  91.     planets.set_data(xdata,ydata)
  92.  
  93.     return planets,
  94.  
  95. animation = anim.FuncAnimation(fig,animate,init_func=init, frames=10000, interval=1, blit=True)
  96. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement