Skip to content

Documentation / @interstellar-tools/equations

@interstellar-tools/equations ​

Curated, tested orbital mechanics and dynamics formulas: Newtonian gravity, vis-viva, Kepler’s third law, Kepler’s equation solvers, anomaly conversions, Hohmann transfers, rocket equation, J2 perturbations and more. SI units in, SI units out, with clear errors for invalid input.

Documentation ​

The full documentation lives at phun-ky.net/interstellar-tools:

Installation ​

  • Node.js version 22.12.0 or higher
  • ES modules; require() needs Node 22.12 or later
npm
shell
npm i --save @interstellar-tools/equations

WARNING

These equations have not YET been battle-tested or tested to real world mechanics, YMMV!

Here you will find a set of function that can assist you when calculating orbits, angles, solve for kelper or find true anomalies.

Interfaces ​

InterfaceDescription
CwTwoImpulseTransferInterface-
EstimateLifetimeOptionsInterfaceOptions for estimateLifetime.
LambertSolutionInterface-
LaunchAzimuthsInterface-
Rk45IntegrateOptionsInterfaceOptions for rk45Integrate.
SolveLambertOptionsInterface-

Type Aliases ​

Type AliasDescription
HohmannTransferReturnType-

Functions ​

FunctionDescription
keplerPropagate-
planetographicLatitudeOblateCompute planetographic latitude (oblate spheroid) from body-fixed Cartesian coordinates.

Angles ​

FunctionDescription
computeAngleAdvances a body along its orbit by one time step and returns its new true anomaly (ν).
wrapAngleWrap an angle (in radians) to a single-turn range and snap values extremely close to ±τ (±2π) back to 0 to curb floating-point drift.

Anomalies ​

FunctionDescription
advanceMeanAnomalyAdvances an orbit by a time step and returns its new mean anomaly (M).
asymptoteTrueAnomalyCompute the true anomaly of a hyperbola's asymptotes: the limit a body on a hyperbola approaches but never reaches.
eccentricToTrueAnomalyConverts Eccentric Anomaly (E) to True Anomaly (V) for an orbit.
hyperbolicToTrueAnomalyConvert a hyperbolic anomaly F to the true anomaly on a hyperbola.
meanAnomalyAtThe mean anomaly (M) of an orbit at a given date.
trueAnomalyAtThe true anomaly (ν) of an orbit at a given date: where the body is.
trueToHyperbolicAnomalyConvert a true anomaly on a hyperbola to the hyperbolic anomaly F.
trueToMeanAnomalyConverts true anomaly (ν) to mean anomaly (M) using Kepler's equation.

Atmosphere ​

FunctionDescription
nrlmsise00The NRLMSISE-00 model of Earth's atmosphere: the density, temperature and make-up of the air at any height from the ground to the exosphere, at a place and a moment, for given solar and geomagnetic activity. It's the standard model for satellite drag.

Cartography ​

NameDescription
BodyOrientationInterfaceA body's orientation at a moment, as bodyOrientation gives it.
PlanetocentricPointInterfaceA point on a body, in planetocentric coordinates, as subsolarPoint gives it.
SunInSkyInterfaceWhere the Sun is in a place's sky, as sunInSky gives it.
axialTiltThe axial tilt of a body, its obliquity: the angle between its spin axis and its orbit's pole, from its IAU rotation model and its orbit.
bodyFixedFromInertialDcmIAUBuild the IAU-style inertial → body-fixed direction cosine matrix (DCM).
bodyFixedToGeodeticConvert a body-fixed Cartesian position (ECEF for Earth) to geodetic coordinates: latitude, longitude and height.
bodyOrientationThe orientation of a body at a moment, from its IAU rotation model, as rotation.iau in @interstellar-tools/constants gives it: where its pole points, how far it has turned, and the rotation into its body-fixed frame.
centralAngleCompute the central angle between two points on a sphere from their latitudes and longitudes, with the haversine formula.
centralAngleFromVectorsCompute the central angle between two position vectors, without trigonometry on latitude and longitude.
earthRotationAngleCompute the Earth rotation angle (ERA): how far Earth has turned about its axis at a moment, measured from the Celestial Intermediate Origin. It's the IAU 2000 measure of Earth's rotation, linear in UT1.
eccentricitySquaredOblateSpheroidCompute first eccentricity squared (e2) for an oblate spheroid.
flatteningOblateSpheroidCompute flattening (f) of an oblate spheroid.
geodeticToBodyFixedConvert geodetic coordinates (latitude, longitude, height) to a body-fixed Cartesian position, ECEF for Earth.
greatCircleDistanceCompute the great-circle distance between two points on a sphere: the shortest path along its surface.
greenwichMeanSiderealTimeCompute Greenwich mean sidereal time (GMST) with the IAU 1982 model: the angle from the mean equinox of date to the Greenwich meridian, as the 1982 standard defines it.
heightAboveEllipsoidCompute a point's height above a body's reference ellipsoid: the exact height along the ellipsoid's normal, the height maps and GPS receivers give.
heightAboveSphereCompute a point's height above a spherical body: its distance from the centre less the radius.
horizonDistanceCompute the straight-line distance to the horizon for an observer at a height above a sphere.
horizonSurfaceDistanceCompute the distance along the surface to the horizon for an observer at a height above a sphere.
isOnTriaxialEllipsoidSurfaceTest whether a 3D point lies on the surface of a triaxial ellipsoid (within a tolerance).
localSiderealTimeCompute local mean sidereal time: Greenwich mean sidereal time turned by a longitude, the angle from the mean equinox to the local meridian.
meridionalRadiusOfCurvatureCompute the meridional radius of curvature M of an oblate spheroid at a geodetic latitude.
moonPositionCompute the Moon's position seen from Earth's centre at a moment: right ascension, declination and distance, from the short series of Montenbruck and Gill, the largest terms of the lunar theory.
planetocentricLatitudeCompute planetocentric latitude (φc) from body-fixed Cartesian coordinates.
primeVerticalRadiusOfCurvatureCompute the prime vertical radius of curvature N of an oblate spheroid at a geodetic latitude.
sphericalPolygonAreaCompute the area of a polygon on a sphere, such as an instrument footprint or a region on a planet, from its corner points.
subsolarPointThe subsolar point: where on a body the Sun is overhead, from its IAU rotation model and the direction from the body to the Sun.
sunInSkyWhere the Sun is in a place's sky: its elevation, its azimuth and the local solar time, from where on the body it is overhead, the subsolarPoint.
sunPositionCompute the Sun's position seen from Earth's centre at a moment: right ascension, declination and distance, with the low-precision formulas of the Astronomical Almanac.

Entry ​

FunctionDescription
ballisticCoefficientCompute the ballistic coefficient of an entry vehicle: how much mass it has per unit of drag.
ballisticEntrySpeedCompute the speed of a ballistic entry at an altitude, with the Allen–Eggers solution.
ballisticPeakDecelerationCompute the peak deceleration of a ballistic entry, with the Allen–Eggers solution.
ballisticPeakDecelerationAltitudeCompute the altitude of peak deceleration in a ballistic entry, with the Allen–Eggers solution.
stagnationHeatFluxCompute the convective heat flux at the stagnation point of an entry vehicle, with the Sutton–Graves relation.
terminalVelocityCompute the terminal speed of a falling body: where drag balances its weight.

Galactic ​

NameDescription
GalacticDirectionAndDistanceInterfaceA direction and distance from the Sun, as galactocentricToGalactic gives them.
GalactocentricPositionOptionsInterfaceOptions for galactocentricPosition.
GalactocentricToGalacticOptionsInterfaceOptions for galactocentricToGalactic.
GalactocentricVelocityOptionsInterfaceOptions for galactocentricVelocity.
GalaxyDiskAxisOptionsInterfaceOptions for galaxyDiskAxis.
equatorialToGalacticThe galactic coordinates of a direction on the sky: from right ascension and declination in the ICRS (J2000), as catalogues give them, to galactic longitude l and latitude b.
galacticToEquatorialThe right ascension and declination of a galactic direction: from galactic longitude l and latitude b to the ICRS (J2000), the inverse of equatorialToGalactic, with the transpose of the Hipparcos matrix AG.
galacticToSupergalacticThe supergalactic coordinates of a galactic direction: the frame of the Local Supercluster, where the nearby galaxies and clusters gather in a plane.
galactocentricPositionThe position around the Milky Way's centre of something seen from the Sun: turns a direction in galactic coordinates and a distance, as GALAXIES in @interstellar-tools/constants gives them, into x, y, z in the 'galactocentric' frame.
galactocentricToGalacticThe direction and distance from the Sun of a galactocentric position: the inverse of galactocentricPosition. It untilts the plane by θ=arcsin⁡(z⊙/R0), moves the origin back to the Sun, and reads off the galactic longitude, latitude and distance:
galactocentricVelocityThe velocity around the Milky Way's centre of something seen from the Sun, in km/s, in the 'galactocentric' frame: from its direction, distance and motion, as GALAXIES in @interstellar-tools/constants gives them.
galaxyDiskAxisThe spin axis of a galaxy's disk, in the 'galactocentric' frame's axes: the unit vector its disk turns around, counter-clockwise seen from its tip. Draw the disk at right angles to it.
supergalacticToGalacticThe galactic coordinates of a supergalactic direction: the inverse of galacticToSupergalactic.

Gravity ​

FunctionDescription
accelerationOn1By2Gravitational acceleration of body 1 due to body 2 (vector, m/s²).
forceOn1By2Gravitational force vector on body 1 due to body 2 (newtons, N).
gravitationalForceCompute the Newtonian gravitational force on body 1 due to body 2.
gravitationalParameterTwo-body gravitational parameter (μ).
thirdBodyAccelerationThe tidal pull of a third body, such as the Moon or the Sun, on a satellite: how much more, or less, it pulls the satellite than the planet the satellite orbits. Only that difference changes the orbit, as both fall toward the third body together.
zonalHarmonicsAccelerationThe pull of a planet's flattening and pear shape on a satellite: the acceleration from its zonal harmonics, J2 and up, on top of the central −μr/r3.

Helpers ​

NameDescription
QuantityTypeAny unit-carrying quantity from @interstellar-tools/types' quantities, as convertQuantity takes it.
METERS_PERMeters-per-unit lookup for all canonical DistanceUnitType symbols.
NORMALIZE_DISTANCE_UNITLookup table that normalizes distance unit aliases (and the canonical symbols themselves) to a single, canonical DistanceUnitType.
applyMatrix3Apply a 3×3 matrix to a 3D vector (matrix–vector multiplication).
convertDistanceUnitConvert a distance between any two DistanceUnitType units.
convertQuantityConvert a quantity to another unit of the same kind: a mass from kg to Jupiter masses, a pressure from bar to Pa, a parallax from mas to arcsec.
crossCompute the cross product of two 3D vectors.
det3Compute the determinant of a 3×3 matrix (row-major).
dotCompute the dot product of two 3D vectors.
matMul3Multiply two 3×3 matrices (row-major).
normCompute the Euclidean norm (length / magnitude) of a 3D vector.
norm2piNormalize an angle to the range [0, 2π).
normalizeDistanceUnitNormalize a distance unit string into a canonical DistanceUnitType.
radBrand a numeric value as Radians.
rk45IntegrateIntegrate a system of ODEs from t0 to t1 with adaptive steps: the Dormand–Prince method, RK45, which takes long steps where the solution is smooth and short ones where it changes fast, to keep each step's error within a tolerance.
rk4IntegrateIntegrate a system of ODEs from t0 to t1 in fixed fourth-order Runge–Kutta steps.
rk4StepTake one fourth-order Runge–Kutta step of a system of ODEs, y˙=f(t,y).
rot1Construct a right-handed rotation matrix about the x-axis (often written R₁).
rot3Construct a right-handed rotation matrix about the z-axis (often written R₃).
scaleScale a 3D vector by a scalar.
stumpffCCompute the Stumpff function C(z), used by the universal-variable formulation of the two-body problem.
stumpffSCompute the Stumpff function S(z), used by the universal-variable formulation of the two-body problem.
subSubtract two 3D vectors (a - b).
toRadConvert degrees → radians.
transpose3Transpose a 3×3 matrix (row-major).

Kepler ​

FunctionDescription
residualCompute the Kepler equation residual for an elliptical orbit:

Kepler Solvers ​

FunctionDescription
solveKeplerSolves Kepler's Equation for the Eccentric Anomaly (E) using an adaptive approach:
solveKeplerBisectionSolve Kepler's equation for the eccentric anomaly (E) via bisection (elliptic case: (0≤e<1)).
solveKeplerHighEccentricitySolves Kepler's Equation for the Eccentric Anomaly (E) in highly eccentric orbits (e>0.9) using an iterative numerical approach.
solveKeplerHyperbolicSolve Kepler's equation for a hyperbola: find the hyperbolic anomaly F from the hyperbolic mean anomaly Mh.
solveKeplerNewtonRaphsonSolves Kepler's Equation for the Eccentric Anomaly (E) using the Newton-Raphson method with Householder acceleration for fast convergence.

Manoeuvres ​

FunctionDescription
burnTimeCompute the burn time needed for a given delta-v, at constant thrust and mass flow.
combineBurnsDeltaVCombine non-collinear burns (vector law / law of cosines for velocities).
cwTwoImpulseTransferCompute the two burns of a Clohessy–Wiltshire rendezvous: from a relative state to a target state in a given time.
gravityAssistTurningAngleCompute gravity-assist turning angle (flyby deflection) for a hyperbolic encounter.
gravityLossCompute the gravity loss of a burn from samples of gravity and flight-path angle.
hohmannSemiMajorAxisConvenience: compute only the semi-major axis (at) (m) of the Hohmann transfer.
hohmannTransferHohmann transfer (coplanar, circular (r1→r2)).
hohmannTransferTimeConvenience: compute only the transfer time (tt) (s).
initialMassForDeltaVCompute the mass needed at ignition to give a final mass a delta-v: the rocket equation solved for m0.
massFlowRateCompute the mass flow rate of a rocket engine from its thrust and specific impulse.
oberthEnergyGainOberth effect (specific energy gain near periapsis).
phasingWaitTimeCompute how long to wait for a phase angle: when a target, leading a chaser on another circular orbit, will be at the angle a manoeuvre needs.
planeChangeDeltaVInclination (plane) change Δv at speed (v).
rocketDeltaVFromIspCompute ideal delta-v from the Tsiolkovsky rocket equation using specific impulse.
rocketDeltaVFromVeCompute ideal delta-v from the Tsiolkovsky rocket equation using effective exhaust velocity.
rocketThrustCompute the thrust of a rocket engine from its exhaust, including the pressure term.
solveLambertSolve Lambert's problem: find the orbit that goes from one position to another in a given time.
thrustToWeightCompute the thrust-to-weight ratio of a vehicle in a gravity field.

Orbits ​

NameDescription
CwStateTransitionInterfaceThe Clohessy–Wiltshire state transition matrix Φ(t), split into its four 3×3 blocks: r(t)=Φrrr0+Φrvv0 and v(t)=Φvrr0+Φvvv0.
StateAtOptionsInterfaceOptions for stateAt.
atmosphericDragAccelerationCompute atmospheric drag acceleration magnitude.
characteristicEnergyC3Compute characteristic energy (C3) from hyperbolic excess speed.
circularSpeedCircular speed (vc) for a body in a circular orbit at radius (r).
cwHillDerivativesCompute the time-derivative of a Clohessy–Wiltshire / Hill relative-motion state (right-hand side for ODE integration).
cwPropagatePropagate a Clohessy–Wiltshire / Hill relative state in closed form.
cwStateTransitionCompute the Clohessy–Wiltshire state transition matrix: the closed-form solution of the CW / Hill equations.
decayRateHow much a near-circular orbit sinks in one revolution under atmospheric drag: the change in its semi-major axis per orbit.
elementsToStateConvert the six classical orbital elements to a state vector (position and velocity).
escapeSpeedEscape speed (vesc) - minimum speed to escape a central body's gravity from radius (r) (ignoring drag/perturbations).
estimateLifetimeEstimate how long a satellite in a near-circular low orbit stays up: the time for atmospheric drag to bring it down to re-entry. For a student CubeSat, it sets the mission's length, and checks the guideline to deorbit within five years of the mission's end.
exponentialAtmosphereDensityThe density of Earth's atmosphere at a height, from the exponential model: within each band of heights, the density falls by a factor of e every scale height. It's the quick estimate for drag on a satellite.
flightPathAngleFromTrueAnomalyFlight-path angle (γ) from true anomaly (ν) and eccentricity (e).
frozenOrbitEccentricityThe eccentricity of a frozen orbit: the small eccentricity at which the pear shape of the planet, J3, and its bulge, J2, balance, so the perigee stays put at 90° and the orbit's height over each latitude stays the same, orbit after orbit. Earth-observation missions fly them for steady imaging heights.
hillSphereRadiusCompute the Hill sphere radius: how far from a body its own gravity can hold a moon or a spacecraft against the pull of the body it orbits.
hyperbolicEccentricityCompute the eccentricity of a hyperbola from the excess speed and the periapsis distance.
hyperbolicPeriapsisSpeedCompute hyperbolic periapsis speed for a flyby/escape hyperbola.
hyperbolicSemiMajorAxisCompute the semi-major axis of a hyperbola from the hyperbolic excess speed.
hyperbolicTimeOfFlightCompute the time of flight between two points on a hyperbola, given by their true anomalies.
inclinationFromLaunchAzimuthCompute the inclination of the orbit reached by launching from a latitude on an azimuth.
j2ArgumentOfPerigeeRateCompute argument of perigee rotation (J2 secular drift of ω) for an orbit about an oblate body.
j2NodalPrecessionRateCompute J2 nodal precession (RAAN drift) for an orbit about an oblate body.
keplerPeriodKepler's 3rd law - orbital period (T) from semi-major axis (a) and gravitational parameter (μ).
launchAzimuthForInclinationCompute the inertial launch azimuths that reach an inclination from a latitude.
meanMotionCompute mean motion for a (near-)circular reference orbit.
orbitFrameToIcrfThe rotation from an orbit's reference plane to the ICRF, the J2000 equator and equinox: multiply a vector in the plane's coordinates by it to get the vector in the ICRF.
periApoapsisRadiiPeri/apoapsis radii from semi-major axis (a) and eccentricity (e).
repeatGroundTrackThe semi-major axis of a repeat ground track orbit: one whose track over the ground repeats exactly after a whole number of revolutions in a whole number of days, so a satellite revisits the same places on a fixed cycle. Landsat 8 and 9 make 233 revolutions in 16 days.
rotatingLaunchAzimuthCompute the azimuth over the ground for an inertial launch azimuth, on a rotating body.
solarDayLengthCompute the length of a solar day, sunrise to sunrise, from a body's rotation and its orbit.
solarRadiationPressureAccelerationThe push of sunlight on a spacecraft: solar radiation pressure. Light carries momentum, and a spacecraft that absorbs or reflects it is pushed away from the Sun, gently but without pause.
specificAngularMomentumSpecific angular momentum (h) (scalar magnitude).
specificAngularMomentumFromElementsSpecific angular momentum (h) from orbital elements.
specificMechanicalEnergySpecific mechanical energy (ε) of a point mass in a central gravity field.
sphereOfInfluenceRadiusCompute sphere of influence radius (patched conics approximation).
stateAtThe position and velocity of a body on its orbit at a given date, in 3D, from a dataset orbit: its a, e, period, its true anomaly angle at J2000, and its orientation i, om and w in its frame.
stateToElementsConvert a state vector (position and velocity) to the six classical orbital elements.
sunSynchronousInclinationThe sun-synchronous inclination: the inclination at which the planet's equatorial bulge turns an orbit's plane as fast as the planet goes round the Sun, so the satellite crosses the equator at the same local time every day. Most Earth-observation satellites fly one, for the same light on every pass.
surfaceRotationSpeedCompute the eastward speed of a point on a rotating body's surface, at a latitude.
synodicPeriodCompute the synodic period of two bodies on circular orbits: the time between two alignments.
visVivaSpeedVis-viva (orbital speed) - compute speed magnitude (v) from (r), (a), and (μ).

Three-body ​

FunctionDescription
areTrojanPointsStableWhether the Trojan points L4 and L5 of two bodies are stable: whether a small body there, nudged, circles the point rather than drifting off. It's why Jupiter has thousands of Trojan asteroids.
cr3bpDerivativesCompute the time derivative of a state in the circular restricted three-body problem (right-hand side for ODE integration).
cr3bpMassRatioCompute the mass ratio μ of the circular restricted three-body problem.
cr3bpUnitsCompute the units of the normalised CR3BP frame for a pair of bodies.
jacobiConstantCompute the Jacobi constant of a state in the circular restricted three-body problem.
lagrangePointsThe five Lagrange points of two bodies circling each other: where a third, small body can stay put relative to them. JWST, Gaia and SOHO are parked at Sun-Earth L1 and L2, and the Trojan asteroids gather at Sun-Jupiter L4 and L5.