How can I setup the three body problem in python? How to I define the function to solve the ODEs?
The three equations are
x'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * x
,
y'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * y
, and
z'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * z
.
Written as 6 first order we have
x' = x2
,
y' = y2
,
z' = z2
,
x2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * x
,
y2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * y
, and
z2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * z
I also want to add in the path Plot o Earth's orbit and Mars which we can assume to be circular.
Earth is 149.6 * 10 ** 6
km from the sun and Mars 227.9 * 10 ** 6
km.
#!/usr/bin/env python
# This program solves the 3 Body Problem numerically and plots the trajectories
import pylab
import numpy as np
import scipy.integrate as integrate
import matplotlib.pyplot as plt
from numpy import linspace
mu = 132712000000 #gravitational parameter
r0 = [-149.6 * 10 ** 6, 0.0, 0.0]
v0 = [29.0, -5.0, 0.0]
dt = np.linspace(0.0, 86400 * 700, 5000) # time is seconds
As you've shown, you can write this as a system of six first-order ode's:
You can save this as a vector:
and thus create a function that returns its derivative:
Given an initial state
u0 = (x0, y0, z0, x20, y20, z20)
, and a variable for the timest
, this can be fed intoscipy.integrate.odeint
as such:where
u
will be the list as above. Or you can unpacku
from the start, and ignore the values forx2
,y2
, andz2
(you must transpose the output first with.T
)