Orbital Mechanics in Julia: Solving Kepler's Equation
Recovering the true anomaly from an orbit, in a few lines of Julia.
Given where a body is, I wanted to know where it is in its orbit. The first version of this post did that: it took the semi-major axis a, the eccentricity e and the radial distance r, and returned the true anomaly. I titled it “Solving Kepler’s Equation”. It does not solve Kepler’s equation, and I want to fix that here. This post keeps the original function, says what it solves, and then adds the solver the title promised.
I picked Julia because the syntax reads like the equations and the speed is close to C. Here is the plan. First the radial inversion I wrote, with its limits. Then Kepler’s equation and a Newton solver for it. Then checks you can do by hand, so you can trust both.
Two problems that share a name
The two problems start from different knowns and end at the same angle.
The radial inversion starts from a distance. If you know r, a and e, the orbit equation fixes the eccentric anomaly up to a sign. The sign says whether the body is moving away from periapsis or toward it.
Kepler’s equation starts from a time. The mean anomaly M grows linearly with time, and M = E − e sin E links it to the eccentric anomaly E. You cannot rearrange that into a formula for E. You have to iterate. That is the part people mean by “solving Kepler’s equation”.
The radial inversion, as I first wrote it
function radial_kepler(r, a, e; direction=1)
e >= 1 && error("Only elliptical orbits (e < 1) supported")
cosE = clamp((a - r) / (a * e), -1.0, 1.0)
E = acos(cosE)
f = 2 * atan(sqrt((1 + e) / (1 - e)) * tan(E / 2))
return direction * f
end
a, e, r = 1.0, 0.1, 0.9 # r = a(1 - e): perihelion
println("True anomaly (deg): ", rad2deg(radial_kepler(r, a, e)))Here is what it does. The orbit equation gives r = a(1 − e cos E), so cos E = (a − r) / (a e). The clamp keeps rounding error from pushing the cosine outside [−1, 1]. The acos returns E between 0 and π. The half-angle formula turns E into f. The direction argument is +1 when the body moves outward from periapsis and −1 when it moves inward, and it flips the sign of f.
At perihelion the true anomaly is zero, which is a useful sanity check. Exact arithmetic gives 0°. Julia prints 1.3348511219001302e-6 instead, because 1.0 − 0.9 is not exactly 0.1 in binary, so cos E comes out a hair under 1 and acos returns a small angle.
The function has one limit I should have stated. At e = 0 the divisor a * e is zero, so for a circular orbit the function divides by zero and returns NaN when r equals a, which I confirmed by running it. That is the right answer, because a circular orbit has no periapsis and the true anomaly is not fixed by r alone.
Kepler’s equation and a Newton solver
Kepler’s equation is:
M = E − e sin E
I solve it for E with Newton’s method. Write g(E) = E − e sin E − M. Its derivative is 1 − e cos E, which is at least 1 − e and so never reaches zero for an ellipse. Each step subtracts g divided by that derivative.
The one thing to decide is the starting guess. For small eccentricity, E = M is close and converges in a few steps. Near e = 0.99 that guess can send the iteration the wrong way, so for e of 0.8 or more I start from E = π. I ran a sweep in Julia over e from 0 to 0.999 in steps of 0.01 and M from 0 to 2π in steps of 0.05. Every case converged within 50 steps, and the largest residual in M = E − e sin E was about 9e-16.
function solve_kepler(M, e; tol=1e-12, maxiter=50)
M = mod(M, 2pi)
E = e < 0.8 ? M : pi
for _ in 1:maxiter
dE = (E - e * sin(E) - M) / (1 - e * cos(E))
E -= dE
abs(dE) < tol && return E
end
error("no convergence")
end
true_anomaly(E, e) = 2atan(sqrt(1 + e) * sin(E / 2), sqrt(1 - e) * cos(E / 2))The first line wraps M into [0, 2π) so a large time does not hurt convergence. The loop returns when a step is smaller than the tolerance. If 50 steps do not reach it, the function raises an error and does not hand back a wrong number.
For the story on starting guesses at high eccentricity, see Improved First Estimates to the Solution of Kepler’s Equation on arXiv.
Checks that hold by algebra
I ran these in Julia and the results match the maths.
With e = 0, the equation reduces to E = M and the true anomaly equals M. At M = 0 the answer is E = 0 and f = 0, which is periapsis. At M = π the answer is E = π and f = π, which is apoapsis, for any e.
A less obvious check ties the two functions together. Take a = 1 and e = 0.5, and put the body at r = 1. The radial inversion gives cos E = (1 − 1) / 0.5 = 0, so E = π/2. The half-angle formula gives tan(f/2) = sqrt(1.5 / 0.5) · tan(π/4) = sqrt(3), so f = 120°.
Check it against the orbit equation. The distance at f = 120° is a(1 − e²) / (1 + e cos f) = 0.75 / (1 + 0.5 · (−0.5)) = 0.75 / 0.75 = 1, which matches r = 1.
Now go the other way through Kepler’s equation. For E = π/2 and e = 0.5, M = π/2 − 0.5 = 1.0708 radians, which is 61.35°. Running solve_kepler(1.070796, 0.5) returns E = 1.570796, and true_anomaly gives 119.99998°, which is 120° to the precision of the rounded M. Two different starting points, one orbit position, one answer.
Which function to call
Use the radial inversion when you have a distance, for example from a measured range. It returns two possible positions, one outbound and one inbound, and direction picks one. Use the Newton solver when you have a time. It returns one position.
If you hold only a time and an orbit, the pipeline is M from the time, E from solve_kepler, f from true_anomaly, and r from the orbit equation. The angles that tilt that orbit into space are in Orbital Mechanics Angles in Julia.
Limits
Both functions handle ellipses only. Parabolic and hyperbolic orbits have their own forms of the equation, and I do not cover them. The Newton solver’s tolerance of 1e-12 is a choice for double precision, and the starting-guess rule is the least tested part.
For the textbook derivations, see Curtis, Orbital Mechanics for Engineering Students, and Vallado, Fundamentals of Astrodynamics and Applications. The Wikipedia article on Kepler’s equation, which the original post links, is a short reference for the notation.