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:
- Getting started: installation, unit conventions and recommended practices
- API reference for
@interstellar-tools/equations: every export, with formulas, parameters and examples
Installation
- Node.js version 22.12.0 or higher
- ES modules;
require()needs Node 22.12 or later
shell
npm i --save @interstellar-tools/equationsWARNING
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
| Interface | Description |
|---|---|
| CwTwoImpulseTransferInterface | - |
| EstimateLifetimeOptionsInterface | Options for estimateLifetime. |
| LambertSolutionInterface | - |
| LaunchAzimuthsInterface | - |
| Rk45IntegrateOptionsInterface | Options for rk45Integrate. |
| SolveLambertOptionsInterface | - |
Type Aliases
| Type Alias | Description |
|---|---|
| HohmannTransferReturnType | - |
Functions
| Function | Description |
|---|---|
| keplerPropagate | - |
| planetographicLatitudeOblate | Compute planetographic latitude (oblate spheroid) from body-fixed Cartesian coordinates. |
Angles
| Function | Description |
|---|---|
| computeAngle | Advances a body along its orbit by one time step and returns its new true anomaly ( |
| wrapAngle | Wrap 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
| Function | Description |
|---|---|
| advanceMeanAnomaly | Advances an orbit by a time step and returns its new mean anomaly ( |
| asymptoteTrueAnomaly | Compute the true anomaly of a hyperbola's asymptotes: the limit a body on a hyperbola approaches but never reaches. |
| eccentricToTrueAnomaly | Converts Eccentric Anomaly ( |
| hyperbolicToTrueAnomaly | Convert a hyperbolic anomaly |
| meanAnomalyAt | The mean anomaly ( |
| trueAnomalyAt | The true anomaly ( |
| trueToHyperbolicAnomaly | Convert a true anomaly on a hyperbola to the hyperbolic anomaly |
| trueToMeanAnomaly | Converts true anomaly ( |
Atmosphere
| Function | Description |
|---|---|
| nrlmsise00 | The 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
| Name | Description |
|---|---|
| BodyOrientationInterface | A body's orientation at a moment, as bodyOrientation gives it. |
| PlanetocentricPointInterface | A point on a body, in planetocentric coordinates, as subsolarPoint gives it. |
| SunInSkyInterface | Where the Sun is in a place's sky, as sunInSky gives it. |
| axialTilt | The 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. |
| bodyFixedFromInertialDcmIAU | Build the IAU-style inertial → body-fixed direction cosine matrix (DCM). |
| bodyFixedToGeodetic | Convert a body-fixed Cartesian position (ECEF for Earth) to geodetic coordinates: latitude, longitude and height. |
| bodyOrientation | The 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. |
| centralAngle | Compute the central angle between two points on a sphere from their latitudes and longitudes, with the haversine formula. |
| centralAngleFromVectors | Compute the central angle between two position vectors, without trigonometry on latitude and longitude. |
| earthRotationAngle | Compute 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. |
| eccentricitySquaredOblateSpheroid | Compute first eccentricity squared ( |
| flatteningOblateSpheroid | Compute flattening ( |
| geodeticToBodyFixed | Convert geodetic coordinates (latitude, longitude, height) to a body-fixed Cartesian position, ECEF for Earth. |
| greatCircleDistance | Compute the great-circle distance between two points on a sphere: the shortest path along its surface. |
| greenwichMeanSiderealTime | Compute 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. |
| heightAboveEllipsoid | Compute 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. |
| heightAboveSphere | Compute a point's height above a spherical body: its distance from the centre less the radius. |
| horizonDistance | Compute the straight-line distance to the horizon for an observer at a height above a sphere. |
| horizonSurfaceDistance | Compute the distance along the surface to the horizon for an observer at a height above a sphere. |
| isOnTriaxialEllipsoidSurface | Test whether a 3D point lies on the surface of a triaxial ellipsoid (within a tolerance). |
| localSiderealTime | Compute local mean sidereal time: Greenwich mean sidereal time turned by a longitude, the angle from the mean equinox to the local meridian. |
| meridionalRadiusOfCurvature | Compute the meridional radius of curvature |
| moonPosition | Compute 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. |
| planetocentricLatitude | Compute planetocentric latitude ( |
| primeVerticalRadiusOfCurvature | Compute the prime vertical radius of curvature |
| sphericalPolygonArea | Compute the area of a polygon on a sphere, such as an instrument footprint or a region on a planet, from its corner points. |
| subsolarPoint | The subsolar point: where on a body the Sun is overhead, from its IAU rotation model and the direction from the body to the Sun. |
| sunInSky | Where 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. |
| sunPosition | Compute 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
| Function | Description |
|---|---|
| ballisticCoefficient | Compute the ballistic coefficient of an entry vehicle: how much mass it has per unit of drag. |
| ballisticEntrySpeed | Compute the speed of a ballistic entry at an altitude, with the Allen–Eggers solution. |
| ballisticPeakDeceleration | Compute the peak deceleration of a ballistic entry, with the Allen–Eggers solution. |
| ballisticPeakDecelerationAltitude | Compute the altitude of peak deceleration in a ballistic entry, with the Allen–Eggers solution. |
| stagnationHeatFlux | Compute the convective heat flux at the stagnation point of an entry vehicle, with the Sutton–Graves relation. |
| terminalVelocity | Compute the terminal speed of a falling body: where drag balances its weight. |
Galactic
| Name | Description |
|---|---|
| GalacticDirectionAndDistanceInterface | A direction and distance from the Sun, as galactocentricToGalactic gives them. |
| GalactocentricPositionOptionsInterface | Options for galactocentricPosition. |
| GalactocentricToGalacticOptionsInterface | Options for galactocentricToGalactic. |
| GalactocentricVelocityOptionsInterface | Options for galactocentricVelocity. |
| GalaxyDiskAxisOptionsInterface | Options for galaxyDiskAxis. |
| equatorialToGalactic | The 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. |
| galacticToEquatorial | The 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 |
| galacticToSupergalactic | The supergalactic coordinates of a galactic direction: the frame of the Local Supercluster, where the nearby galaxies and clusters gather in a plane. |
| galactocentricPosition | The 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 'galactocentric' frame. |
| galactocentricToGalactic | The direction and distance from the Sun of a galactocentric position: the inverse of galactocentricPosition. It untilts the plane by |
| galactocentricVelocity | The 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. |
| galaxyDiskAxis | The 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. |
| supergalacticToGalactic | The galactic coordinates of a supergalactic direction: the inverse of galacticToSupergalactic. |
Gravity
| Function | Description |
|---|---|
| accelerationOn1By2 | Gravitational acceleration of body 1 due to body 2 (vector, m/s²). |
| forceOn1By2 | Gravitational force vector on body 1 due to body 2 (newtons, N). |
| gravitationalForce | Compute the Newtonian gravitational force on body 1 due to body 2. |
| gravitationalParameter | Two-body gravitational parameter ( |
| thirdBodyAcceleration | The 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. |
| zonalHarmonicsAcceleration | The pull of a planet's flattening and pear shape on a satellite: the acceleration from its zonal harmonics, |
Helpers
| Name | Description |
|---|---|
| QuantityType | Any unit-carrying quantity from @interstellar-tools/types' quantities, as convertQuantity takes it. |
| METERS_PER | Meters-per-unit lookup for all canonical DistanceUnitType symbols. |
| NORMALIZE_DISTANCE_UNIT | Lookup table that normalizes distance unit aliases (and the canonical symbols themselves) to a single, canonical DistanceUnitType. |
| applyMatrix3 | Apply a 3×3 matrix to a 3D vector (matrix–vector multiplication). |
| convertDistanceUnit | Convert a distance between any two DistanceUnitType units. |
| convertQuantity | Convert 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. |
| cross | Compute the cross product of two 3D vectors. |
| det3 | Compute the determinant of a 3×3 matrix (row-major). |
| dot | Compute the dot product of two 3D vectors. |
| matMul3 | Multiply two 3×3 matrices (row-major). |
| norm | Compute the Euclidean norm (length / magnitude) of a 3D vector. |
| norm2pi | Normalize an angle to the range [0, 2π). |
| normalizeDistanceUnit | Normalize a distance unit string into a canonical DistanceUnitType. |
| rad | Brand a numeric value as Radians. |
| rk45Integrate | Integrate 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. |
| rk4Integrate | Integrate a system of ODEs from t0 to t1 in fixed fourth-order Runge–Kutta steps. |
| rk4Step | Take one fourth-order Runge–Kutta step of a system of ODEs, |
| rot1 | Construct a right-handed rotation matrix about the x-axis (often written R₁). |
| rot3 | Construct a right-handed rotation matrix about the z-axis (often written R₃). |
| scale | Scale a 3D vector by a scalar. |
| stumpffC | Compute the Stumpff function |
| stumpffS | Compute the Stumpff function |
| sub | Subtract two 3D vectors (a - b). |
| toRad | Convert degrees → radians. |
| transpose3 | Transpose a 3×3 matrix (row-major). |
Kepler
| Function | Description |
|---|---|
| residual | Compute the Kepler equation residual for an elliptical orbit: |
Kepler Solvers
| Function | Description |
|---|---|
| solveKepler | Solves Kepler's Equation for the Eccentric Anomaly ( |
| solveKeplerBisection | Solve Kepler's equation for the eccentric anomaly ( |
| solveKeplerHighEccentricity | Solves Kepler's Equation for the Eccentric Anomaly ( |
| solveKeplerHyperbolic | Solve Kepler's equation for a hyperbola: find the hyperbolic anomaly |
| solveKeplerNewtonRaphson | Solves Kepler's Equation for the Eccentric Anomaly ( |
Manoeuvres
| Function | Description |
|---|---|
| burnTime | Compute the burn time needed for a given delta-v, at constant thrust and mass flow. |
| combineBurnsDeltaV | Combine non-collinear burns (vector law / law of cosines for velocities). |
| cwTwoImpulseTransfer | Compute the two burns of a Clohessy–Wiltshire rendezvous: from a relative state to a target state in a given time. |
| gravityAssistTurningAngle | Compute gravity-assist turning angle (flyby deflection) for a hyperbolic encounter. |
| gravityLoss | Compute the gravity loss of a burn from samples of gravity and flight-path angle. |
| hohmannSemiMajorAxis | Convenience: compute only the semi-major axis ( |
| hohmannTransfer | Hohmann transfer (coplanar, circular ( |
| hohmannTransferTime | Convenience: compute only the transfer time ( |
| initialMassForDeltaV | Compute the mass needed at ignition to give a final mass a delta-v: the rocket equation solved for |
| massFlowRate | Compute the mass flow rate of a rocket engine from its thrust and specific impulse. |
| oberthEnergyGain | Oberth effect (specific energy gain near periapsis). |
| phasingWaitTime | Compute 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. |
| planeChangeDeltaV | Inclination (plane) change Δv at speed ( |
| rocketDeltaVFromIsp | Compute ideal delta-v from the Tsiolkovsky rocket equation using specific impulse. |
| rocketDeltaVFromVe | Compute ideal delta-v from the Tsiolkovsky rocket equation using effective exhaust velocity. |
| rocketThrust | Compute the thrust of a rocket engine from its exhaust, including the pressure term. |
| solveLambert | Solve Lambert's problem: find the orbit that goes from one position to another in a given time. |
| thrustToWeight | Compute the thrust-to-weight ratio of a vehicle in a gravity field. |
Orbits
| Name | Description |
|---|---|
| CwStateTransitionInterface | The Clohessy–Wiltshire state transition matrix |
| StateAtOptionsInterface | Options for stateAt. |
| atmosphericDragAcceleration | Compute atmospheric drag acceleration magnitude. |
| characteristicEnergyC3 | Compute characteristic energy (C3) from hyperbolic excess speed. |
| circularSpeed | Circular speed ( |
| cwHillDerivatives | Compute the time-derivative of a Clohessy–Wiltshire / Hill relative-motion state (right-hand side for ODE integration). |
| cwPropagate | Propagate a Clohessy–Wiltshire / Hill relative state in closed form. |
| cwStateTransition | Compute the Clohessy–Wiltshire state transition matrix: the closed-form solution of the CW / Hill equations. |
| decayRate | How much a near-circular orbit sinks in one revolution under atmospheric drag: the change in its semi-major axis per orbit. |
| elementsToState | Convert the six classical orbital elements to a state vector (position and velocity). |
| escapeSpeed | Escape speed ( |
| estimateLifetime | Estimate 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. |
| exponentialAtmosphereDensity | The density of Earth's atmosphere at a height, from the exponential model: within each band of heights, the density falls by a factor of |
| flightPathAngleFromTrueAnomaly | Flight-path angle ( |
| frozenOrbitEccentricity | The 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. |
| hillSphereRadius | Compute 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. |
| hyperbolicEccentricity | Compute the eccentricity of a hyperbola from the excess speed and the periapsis distance. |
| hyperbolicPeriapsisSpeed | Compute hyperbolic periapsis speed for a flyby/escape hyperbola. |
| hyperbolicSemiMajorAxis | Compute the semi-major axis of a hyperbola from the hyperbolic excess speed. |
| hyperbolicTimeOfFlight | Compute the time of flight between two points on a hyperbola, given by their true anomalies. |
| inclinationFromLaunchAzimuth | Compute the inclination of the orbit reached by launching from a latitude on an azimuth. |
| j2ArgumentOfPerigeeRate | Compute argument of perigee rotation (J2 secular drift of ω) for an orbit about an oblate body. |
| j2NodalPrecessionRate | Compute J2 nodal precession (RAAN drift) for an orbit about an oblate body. |
| keplerPeriod | Kepler's 3rd law - orbital period ( |
| launchAzimuthForInclination | Compute the inertial launch azimuths that reach an inclination from a latitude. |
| meanMotion | Compute mean motion for a (near-)circular reference orbit. |
| orbitFrameToIcrf | The 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. |
| periApoapsisRadii | Peri/apoapsis radii from semi-major axis ( |
| repeatGroundTrack | The 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. |
| rotatingLaunchAzimuth | Compute the azimuth over the ground for an inertial launch azimuth, on a rotating body. |
| solarDayLength | Compute the length of a solar day, sunrise to sunrise, from a body's rotation and its orbit. |
| solarRadiationPressureAcceleration | The 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. |
| specificAngularMomentum | Specific angular momentum ( |
| specificAngularMomentumFromElements | Specific angular momentum ( |
| specificMechanicalEnergy | Specific mechanical energy ( |
| sphereOfInfluenceRadius | Compute sphere of influence radius (patched conics approximation). |
| stateAt | The 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. |
| stateToElements | Convert a state vector (position and velocity) to the six classical orbital elements. |
| sunSynchronousInclination | The 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. |
| surfaceRotationSpeed | Compute the eastward speed of a point on a rotating body's surface, at a latitude. |
| synodicPeriod | Compute the synodic period of two bodies on circular orbits: the time between two alignments. |
| visVivaSpeed | Vis-viva (orbital speed) - compute speed magnitude ( |
Three-body
| Function | Description |
|---|---|
| areTrojanPointsStable | Whether 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. |
| cr3bpDerivatives | Compute the time derivative of a state in the circular restricted three-body problem (right-hand side for ODE integration). |
| cr3bpMassRatio | Compute the mass ratio |
| cr3bpUnits | Compute the units of the normalised CR3BP frame for a pair of bodies. |
| jacobiConstant | Compute the Jacobi constant of a state in the circular restricted three-body problem. |
| lagrangePoints | The 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. |