0 Members and 2 Guests are viewing this topic.
#!/usr/bin/env python'''Two body simulation.'''from __future__ import divisionimport mathimport matplotlib.pyplot as pypimport numpy as np# Gravitational constant (N*m^2*kg^-2)G = 6.674e-11# A giga year in seconds.gyrts = math.pi * 1e7 * 1e9def Fgrav(M, m, r): ''' Gravitational force of two bodies attracting each other. ''' return -G * M * m / r**2 # Solar mass (kg)M = 1.989e30# Earth mass (kg)m = 5.9721e24# Initial conditions.# Position (m).x, y = 150e9, 0X, Y = 0, 0# Velocity (m/s).vx, vy = 0, 30e3Vx, Vy = 0, 0time = 5*math.pi*1e7t = 0dt = 1000xarr, yarr, rarr, tarr = [], [], [], []while t < time: # Update the positions. x += vx * dt y += vy * dt # Calculate the separation vector. dx = x - X dy = y - Y r2 = dx*dx + dy*dy + 1e-4 r = np.sqrt(r2) #print 'dx, dy: ', dx, dy # Calculate components of the gravitational force. fgrav_x = Fgrav(M, m, r) * dx / r fgrav_y = Fgrav(M, m, r) * dy / r #print 'Fgrav: ', fgrav_x, fgrav_y # Update the velocities. vx += (fgrav_x / m) * dt vy += (fgrav_y / m) * dt Vx += (fgrav_x / M) * dt Vy += (fgrav_y / M) * dt #print 'vx, vy: ', vx, vy X += Vx * dt Y += Vy * dt # Store all data. xarr.append(dx); yarr.append(dy); rarr.append(r) tarr.append(t) t += dt fig, (ax1, ax2) = pyp.subplots(2, 'nom')ax1.plot(xarr, yarr)ax1.set_xlabel('$x$ (m)'); ax1.set_ylabel('$y$ (m)')ax2.plot(tarr, rarr)ax2.set_xlabel('$t$ (s)'); ax2.set_ylabel('$r$ (m)')fig.tight_layout()pyp.show()