Compass math - heading from phone sensors, magnetic declination, and the sun's position
compassnavigationdeclinationsun-positionastronomyanglessensorsrotation-matrix
The math behind a phone compass: turning a rotation matrix into "which way am I facing", averaging
and comparing angles correctly across north, correcting magnetic north to true north, and computing
where the sun is in the sky from time and location. All of it is small, pure functions that can be
unit-tested without a device. Worked out for Justin's Android compass app (~/dev/compass,
Model.kt).
Angles on a circle
- Normalize with a double modulo so negatives work:
((d % 360) + 360) % 360. - Signed shortest turn from
atob:d = norm(b - a), thend - 360ifd > 180. Positive means turn right (clockwise). Use it for "Turn right 33°" and for animating a dial: keep an unwrapped running angle and adddiff(current, target)each frame, so the card never spins the long way round past north. - Averaging angles: never average degrees directly (the mean of 359° and 1° is 180°). Average the
unit vectors (
sin,cos) and takeatan2of the result. A low-pass filter for headings keeps two smoothed components:s += α (sin θ − s),c += α (cos θ − c), heading =atan2(s, c). - 16-point compass names: each point covers 22.5°, centered on its direction, so the index is
floor((norm(d) + 11.25) / 22.5) mod 16into N, NNE, NE, ENE, E, ... NNW.
Heading from the rotation matrix
Android's SensorManager.getRotationMatrix (or getRotationMatrixFromVector for the fused,
gyro-steadied rotation-vector sensor) gives a 3×3 matrix R that maps device coordinates to world
coordinates East, North, Up. Column j of R is device axis j written in world coordinates;
the last row is the world "up" written in device coordinates.
- Flat on a table, you face where the phone's top edge points: device +Y. Held upright, you face
where the back camera looks: device −Z. The common recipe (getOrientation azimuth) uses only Y
and flips or goes wild near 45° of tilt.
- Use the horizontal part of (Y − Z): east = R[0][1] − R[0][2], north = R[1][1] − R[1][2],
heading = atan2(east, north). This is correct flat, correct upright, and blends smoothly in
between. When the horizontal part is tiny (the phone points straight up or down) no direction is
defined: hold the last heading instead of showing noise.
- Tilt for a bubble level comes from the last row: asin(R[2][0]) is the side-to-side tilt and
asin(R[2][1]) the front-to-back tilt (clamp to −1..1 before asin).
- Prefer the rotation-vector sensor; fall back to accelerometer + magnetometer with a simple
low-pass on both. Read the magnetometer anyway for its accuracy status (prompt a figure-8
calibration when low) and its field strength: Earth's field is roughly 25 to 65 µT at the
surface, so a reading outside about 20 to 75 µT means nearby metal or magnets are distorting it.
Magnetic declination (true north)
A magnetometer finds magnetic north, which differs from true (geographic) north by the magnetic declination at that place and date. Convention: declination is positive east, meaning magnetic north lies east of true north. Then
true heading = magnetic heading + declination
Declination changes with location and slowly over years; the standard source is the World Magnetic
Model (WMM, updated every five years), which Android ships as android.hardware.GeomagneticField
(latitude, longitude, altitude, time → declination in degrees). In Oklahoma City it is about 3° E
(2.9° E measured in 2026). When no location is available, show magnetic north and say so. Anything
drawn on the dial in true bearings (like the sun) must be shifted by −declination when the dial is
showing magnetic north.
Where is the sun?
NOAA's low-precision solar formulas are accurate to well under a degree for 1950 to 2050, enough for
a compass. With n = days since J2000.0 (unix_ms / 86 400 000 + 2440587.5 − 2451545.0):
1. Mean longitude L = 280.460° + 0.9856474° n, mean anomaly g = 357.528° + 0.9856003° n.
2. Ecliptic longitude λ = L + 1.915° sin g + 0.020° sin 2g; obliquity ε = 23.439° − 0.0000004° n.
3. Right ascension α = atan2(cos ε sin λ, cos λ), declination δ = asin(sin ε sin λ).
4. Greenwich mean sidereal time in hours GMST = 18.697374558 + 24.06570982441908 n (mod 24); local
hour angle H = 15° GMST + longitude − α (longitude east positive).
5. In local East/North/Up: E = −cos δ sin H, N = sin δ cos φ − cos δ cos H sin φ,
U = sin δ sin φ + cos δ cos H cos φ (φ = latitude). Azimuth = atan2(E, N) (clockwise from true
north), elevation = asin(U).
Good unit tests: at solar noon on the June solstice in Oklahoma City the sun is due south at about
78° elevation (90° − 35.5° + 23.4°), and at summer sunset it sets well north of west.
Coordinates for display
Decimal degrees to five places is about one meter. For degrees-minutes-seconds, round the total
number of seconds first and then split it into degrees, minutes and seconds; rounding the seconds
last can print 59′60″.
See also
- Sonifying the planets' orbits ("Music of the Spheres")
- A keyless maps app on Android (MapLibre + OpenStreetMap services)