---
title: "Project: an orbit simulator"
heading: Fly a satellite in Python and check Kepler's laws
eyebrow: B1 · Lesson 54 · Project
xp: 80
---

::: hook
Kepler found his three laws of planetary motion by poring over decades of observations; Newton showed they follow from one inverse-square force. In this project you'll get there a third way: write a simulator that steps a satellite forward under gravity alone, and then measure what it does. You'll check that it conserves energy and angular momentum, measure its period from the simulated path, and compare with the formula that mission planners use to put satellites where they belong.
:::

::: play
- A satellite starts 7000 km from Earth's center (about 630 km up) moving sideways at $v_0$. The curve is its orbit, with Earth drawn to scale.
- At about 7.55 km/s the orbit is a circle. Faster, it stretches into an ellipse with Earth at one focus; the far point climbs quickly.
- Near 10.7 km/s the ellipse opens into an escape path. The readouts give the orbit's size and period.
:::
:::

```sim plot
view: complex
axes: x (km), y (km)
range: 24000
slider: v0 = 7.55..10.5 step 0.05 = 8 km/s
curve: 6371*exp(j*u) | over: u = 0..2*pi | color: ch3 | label: Earth
curve: (1/(2/7000 - v0^2/398600.4))*(1 - (1 - 7000*(2/7000 - v0^2/398600.4))^2)/(1 + (1 - 7000*(2/7000 - v0^2/398600.4))*cos(u))*exp(j*u) | over: u = 0..2*pi | label: orbit
readout: semi-major axis, km = 1/(2/7000 - v0^2/398600.4) | digits: 5
readout: highest altitude, km = 2/(2/7000 - v0^2/398600.4) - 7000 - 6371 | digits: 5
readout: period, min = 2*pi*sqrt((1/(2/7000 - v0^2/398600.4))^3/398600.4)/60 | digits: 4
```

::: predict
## A satellite at 7000 km from Earth's center moves at 8.0 km/s, a little faster than circular speed. Compared with the circular orbit's 97 minutes, its period is:

- [ ] The same, since it starts at the same radius
- [ ] Shorter, because it's moving faster
- [x] Longer: about 118 minutes
- [ ] Infinite: it escapes

::: reveal
Longer, about 118 minutes. The extra speed lifts the far side of the orbit to about 9000 km from Earth's center, so the semi-major axis grows from 7000 km to 7990 km, and by Kepler's third law the period grows as $a^{3/2}$. Moving faster at the start makes the trip longer, because the orbit gets bigger.
:::
:::

::: nameit
## Kepler's laws, from Newton

1. Orbits are **ellipses** with the planet's center at one focus (or, above escape speed, open curves).
2. The line from the planet to the satellite sweeps **equal areas in equal times**: the satellite's angular momentum $\mathbf r \times m\mathbf v$ is conserved, because gravity pulls along $\mathbf r$ and exerts no torque.
3. **$T^2 \propto a^3$**: $T = 2\pi\sqrt{\frac{a^3}{GM}}$, where $a$, the semi-major axis, is half the longest diameter of the ellipse.

## Energy and the vis-viva equation

The orbit's total energy per unit mass depends only on its size:

$$\frac{v^2}{2} - \frac{GM}{r} = -\frac{GM}{2a} \qquad\Longleftrightarrow\qquad v^2 = GM\left(\frac{2}{r} - \frac{1}{a}\right)$$

So a launch speed $v_0$ at radius $r_0$ fixes $a$, and with it the period. Launched sideways at the closest point (perigee), the farthest point (apogee) is at $2a - r_0$. For Earth, $GM = 398\,600$ km³/s².

## The simulation

The state is position $\mathbf r$ and velocity $\mathbf v$; the acceleration is $-GM\frac{\mathbf r}{|\mathbf r|^3}$. RK4 (lesson 52) with a 10 s step over a 100-minute orbit holds the energy constant to about one part in $10^{10}$. Conserved quantities are the best test of an orbit code: any bug or too-large step shows up as energy drifting.
:::

::: example
## A satellite at 7000 km from Earth's center moves sideways at 8.0 km/s. Find the semi-major axis, the apogee altitude and the period.

::: solution
1. **Semi-major axis, from vis-viva.**
   $$\begin{aligned} \frac{1}{a} &= \frac{2}{7000} - \frac{8.0^2}{398\,600} \\ &= 1.2515 \times 10^{-4}\ \text{/km} \end{aligned}$$
   so $a = 7990$ km.
2. **Apogee.** The apogee radius is
   $$2a - 7000 = 8981\ \text{km}$$
   which is 2610 km above the surface.
3. **Period.**
   $$\begin{aligned} T &= 2\pi\sqrt{\frac{7990^3}{398\,600}} \\ &= 7108\ \text{s} \end{aligned}$$
   which is 118.5 min.
4. **Check with the simulation.** A simulation with 10 s steps measures 7108.07 s, matching to 0.01 s.

**Answer:** $a = 7990$ km, the apogee is 2610 km up, and the period is 7108 s (118.5 min).
:::
:::

::: example
## What speed puts a satellite at 7000 km into a circular orbit, and what speed lets it escape?

::: solution
1. **Circular speed.**
   $$\begin{aligned} v_c &= \sqrt{\frac{398\,600}{7000}} \\ &= 7.55\ \text{km/s} \end{aligned}$$
   with a period of 5829 s (97.1 min).
2. **Escape speed.**
   $$\begin{aligned} v_\text{esc} &= \sqrt2 \times 7.55 \\ &= 10.67\ \text{km/s} \end{aligned}$$
3. **In between.** Between them the orbits are ellipses, growing without limit as the speed nears escape.

**Answer:** 7.55 km/s gives a circular orbit, and 10.67 km/s lets the satellite escape.
:::
:::

::: check
kind: python

## Step 1. Write `gravity(r)` returning the acceleration $-GM\mathbf r/|\mathbf r|^3$ for a position `r` (a NumPy array, in km), with `GM = 398600.4` km³/s².

```python starter
import numpy as np
GM = 398600.4

def gravity(r):
    return np.zeros(2)

print(gravity(np.array([7000.0, 0.0])))
```

```python solution
import numpy as np
GM = 398600.4

def gravity(r):
    return -GM * r / np.linalg.norm(r) ** 3

print(gravity(np.array([7000.0, 0.0])))
```

```python tests
import numpy as np
a = gravity(np.array([7000.0, 0.0]))
assert np.allclose(a, [-GM / 7000**2, 0]), f"At (7000, 0) km the acceleration should point to Earth with size GM/r²; got {a}."
a = gravity(np.array([3000.0, 4000.0]))
assert np.allclose(np.linalg.norm(a), GM / 5000**2) and a[0] < 0 and a[1] < 0, "The pull should point toward the origin and fall as 1/r²."
```

::: right
Right. At 7000 km that's 8.1 m/s², about 83% of surface gravity.
:::
:::

::: check
kind: python

## Step 2. Write `orbit(r0, v0, dt, n)` that steps `n` times with RK4 and returns two `(n + 1) × 2` arrays, the positions and velocities, starting with the initial state. `gravity` is included.

```python starter
import numpy as np
GM = 398600.4

def gravity(r):
    return -GM * r / np.linalg.norm(r) ** 3

def orbit(r0, v0, dt, n):
    return np.zeros((n + 1, 2)), np.zeros((n + 1, 2))

rs, vs = orbit([7000, 0], [0, 7.546], 10, 600)
print(np.linalg.norm(rs[-1]))
```

```python solution
import numpy as np
GM = 398600.4

def gravity(r):
    return -GM * r / np.linalg.norm(r) ** 3

def orbit(r0, v0, dt, n):
    rs = np.zeros((n + 1, 2)); vs = np.zeros((n + 1, 2))
    r = np.array(r0, float); v = np.array(v0, float)
    rs[0], vs[0] = r, v
    for i in range(n):
        k1v = gravity(r); k1r = v
        k2v = gravity(r + dt / 2 * k1r); k2r = v + dt / 2 * k1v
        k3v = gravity(r + dt / 2 * k2r); k3r = v + dt / 2 * k2v
        k4v = gravity(r + dt * k3r); k4r = v + dt * k3v
        r = r + dt / 6 * (k1r + 2 * k2r + 2 * k3r + k4r)
        v = v + dt / 6 * (k1v + 2 * k2v + 2 * k3v + k4v)
        rs[i + 1], vs[i + 1] = r, v
    return rs, vs

rs, vs = orbit([7000, 0], [0, 7.546], 10, 600)
print(np.linalg.norm(rs[-1]))
```

```python tests
import numpy as np
v = np.sqrt(GM / 7000)
rs, vs = orbit([7000, 0], [0, v], 10, 600)
assert rs.shape == (601, 2) and vs.shape == (601, 2), "Return n + 1 rows, starting with the initial state."
rad = np.linalg.norm(rs, axis=1)
assert np.max(np.abs(rad - 7000)) < 1e-3, f"A circular orbit should stay at 7000 km; it ranged over {rad.min():.4f} to {rad.max():.4f}."
rs, vs = orbit([7000, 0], [0, 8.0], 10, 800)
E = 0.5 * np.sum(vs**2, axis=1) - GM / np.linalg.norm(rs, axis=1)
assert np.ptp(E) / abs(E[0]) < 1e-8, f"Energy should be conserved to better than 1e-8; it drifted by {np.ptp(E) / abs(E[0]):.2e}."
L = rs[:, 0] * vs[:, 1] - rs[:, 1] * vs[:, 0]
assert np.ptp(L) / L[0] < 1e-8, "Angular momentum should be conserved too."
```

::: right
Right. Energy and angular momentum hold to about one part in $10^{10}$: Kepler's second law, checked numerically.
:::
:::

::: check
kind: python

## Step 3. Write `period(rs, dt)` that finds the times when the orbit crosses the positive $x$ axis going upward ($y$ changes from negative to non-negative while $x > 0$), interpolating within the step, and returns the time between the first two crossings. `orbit` is included.

```python starter
import numpy as np
GM = 398600.4

def gravity(r):
    return -GM * r / np.linalg.norm(r) ** 3

def orbit(r0, v0, dt, n):
    rs = np.zeros((n + 1, 2)); vs = np.zeros((n + 1, 2))
    r = np.array(r0, float); v = np.array(v0, float); rs[0], vs[0] = r, v
    for i in range(n):
        k1v = gravity(r); k1r = v
        k2v = gravity(r + dt / 2 * k1r); k2r = v + dt / 2 * k1v
        k3v = gravity(r + dt / 2 * k2r); k3r = v + dt / 2 * k2v
        k4v = gravity(r + dt * k3r); k4r = v + dt * k3v
        r = r + dt / 6 * (k1r + 2 * k2r + 2 * k3r + k4r)
        v = v + dt / 6 * (k1v + 2 * k2v + 2 * k3v + k4v)
        rs[i + 1], vs[i + 1] = r, v
    return rs, vs

def period(rs, dt):
    return 0.0

rs, vs = orbit([7000, 0], [0, 8.0], 10, 1600)
print(period(rs, 10))
```

```python solution
import numpy as np
GM = 398600.4

def gravity(r):
    return -GM * r / np.linalg.norm(r) ** 3

def orbit(r0, v0, dt, n):
    rs = np.zeros((n + 1, 2)); vs = np.zeros((n + 1, 2))
    r = np.array(r0, float); v = np.array(v0, float); rs[0], vs[0] = r, v
    for i in range(n):
        k1v = gravity(r); k1r = v
        k2v = gravity(r + dt / 2 * k1r); k2r = v + dt / 2 * k1v
        k3v = gravity(r + dt / 2 * k2r); k3r = v + dt / 2 * k2v
        k4v = gravity(r + dt * k3r); k4r = v + dt * k3v
        r = r + dt / 6 * (k1r + 2 * k2r + 2 * k3r + k4r)
        v = v + dt / 6 * (k1v + 2 * k2v + 2 * k3v + k4v)
        rs[i + 1], vs[i + 1] = r, v
    return rs, vs

def period(rs, dt):
    t = []
    for i in range(1, len(rs)):
        if rs[i - 1, 1] < 0 <= rs[i, 1] and rs[i, 0] > 0:
            f = -rs[i - 1, 1] / (rs[i, 1] - rs[i - 1, 1])
            t.append((i - 1 + f) * dt)
    return t[1] - t[0]

rs, vs = orbit([7000, 0], [0, 8.0], 10, 1600)
print(period(rs, 10))
```

```python tests
import numpy as np
rs, vs = orbit([7000, 0], [0, 8.0], 10, 1600)
T = period(rs, 10)
a = 1 / (2 / 7000 - 8.0**2 / GM)
Tk = 2 * np.pi * np.sqrt(a**3 / GM)
assert abs(T - Tk) < 0.5, f"The measured period should match Kepler's 2π√(a³/GM) = {Tk:.2f} s; got {T:.2f} s."
rs, vs = orbit([7000, 0], [0, np.sqrt(GM / 7000)], 10, 1300)
T = period(rs, 10)
assert abs(T - 5828.52) < 0.5, f"The circular orbit's period should be 5828.5 s; got {T:.2f} s."
```

::: right
Right. The simulated satellite keeps Kepler's third law to within hundredths of a second.
:::
:::

::: check
given: v = 8 | 8.5 | 9
answer: 2/(2/7000 - v^2/398600.4) - 7000 - 6371
unit: km
tolerance: 0.5%

## Step 4. A satellite at 7000 km from Earth's center moves sideways at {v} km/s. Using the vis-viva equation, how high above the surface (radius 6371 km) is its apogee?

::: right
Right. $a = \left(\frac{2}{r_0} - \frac{v^2}{GM}\right)^{-1}$, apogee radius $2a - r_0$, minus 6371 km: {answer}.
:::

::: misses
- [2/(2/7000 - v^2/398600.4) - 7000] That's the apogee's distance from Earth's center.
- [1/(2/7000 - v^2/398600.4) - 6371] That's the semi-major axis minus Earth's radius; the apogee is at $2a - r_0$.
- [any] Not yet. Find $a$ from vis-viva, then the apogee radius.
:::
:::

::: explain
## Why is energy conservation a good test of an orbit simulation?

::: model
Gravity is a conservative force, so the true orbit keeps its total energy exactly constant. A numerical method only approximates each step, and its errors usually show up as a slow drift in energy: the orbit spirals in or out. Watching the energy is cheap, needs no exact solution to compare against, and catches most bugs and steps that are too large. A drift of one part in $10^{10}$ over an orbit means the method is tracking the physics closely; a drift of a percent means the results can't be trusted.
:::
:::

::: practice

::: check
given: r = 7000 | 7500 | 42164
answer: sqrt(398600.4/r)
unit: km/s
tolerance: 0.5%

## What is the circular orbital speed {r} km from Earth's center?

::: misses
- [any] $\sqrt{GM/r}$.
:::
:::

::: check
given: a = 8000 | 10000 | 26560
answer: 2*pi*sqrt(a^3/398600.4)/3600
unit: h
tolerance: 0.5%

## An orbit has a semi-major axis of {a} km. What is its period in hours?

::: misses
- [any] $2\pi\sqrt{a^3/GM}$.
:::
:::

::: check
given: r = 7000 | 8000; a = 8000 | 9000
answer: sqrt(398600.4*(2/r - 1/a))
unit: km/s
tolerance: 0.5%

## A satellite on an orbit with semi-major axis {a} km passes {r} km from Earth's center. How fast is it moving?

::: misses
- [any] Vis-viva: $v^2 = GM(2/r - 1/a)$.
:::
:::
:::
