// SPDX-FileCopyrightText: © 2012-2025 Charles Karney // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Geodesics on an ellipsoid of revolution: the shortest path between two //! points on the ellipsoid itself, rather than on a sphere standing in for //! it. //! //! This is Karney's algorithm (J. Geodesy 87, 43-55, 2013, with the addenda //! at https://geographiclib.sourceforge.io/geod-addenda.html), ported from his //! own C implementation, `geodesic.c`, as PROJ carries it. It is accurate to //! about 15 nanometres on the Earth, and unlike Vincenty's it converges for //! every pair of points, nearly antipodal ones included, which is where //! Vincenty's iteration fails. The port keeps the C's structure and names //! -- `sbet1` is the sine of the reduced latitude β₁, `calp2` the cosine of //! the azimuth α₂, and so on -- so that it can be checked line by line //! against the original, and it keeps the original's comments where they //! explain something. It departs from the original in one place, marked //! where it is: geodesic.c v2.2 answers some valid inputs on a prolate //! ellipsoid with a NaN, and this does not. `reference/` checks it against //! the C on every push. It covers the inverse and direct problems: distance //! and azimuths between two points, and the point reached from one along an //! azimuth. The area, reduced-length and geodesic-scale outputs are left //! out, and so is arc mode. //! //! Angles are in degrees and lengths in the units of `a`. const std = @import("std"); const math = std.math; const Geodesic = @This(); /// Equatorial radius. a: f64, /// Flattening, (a - b) / a. Negative for a prolate ellipsoid. f: f64, f1: f64, e2: f64, ep2: f64, n: f64, b: f64, etol2: f64, A3x: [nA3x]f64, C3x: [nC3x]f64, const order = 6; const nA1 = order; const nC1 = order; const nC1p = order; const nA2 = order; const nC2 = order; const nA3 = order; const nA3x = nA3; const nC3 = order; const nC3x = (nC3 * (nC3 - 1)) / 2; const nC = order + 1; // qd = quarter turn / degree, hd = half turn / degree, td = full turn / degree const qd: f64 = 90; const hd: f64 = 2 * qd; const td: f64 = 2 * hd; const digits = math.floatMantissaBits(f64) + 1; const maxit1 = 20; const maxit2 = maxit1 + digits + 10; const epsilon = math.floatEps(f64); const tiny = @sqrt(math.floatMin(f64)); const tol0 = epsilon; // Increase multiplier in defn of tol1 from 100 to 200 to fix inverse case // 52.784459512564 0 -52.784459512563990912 179.634407464943777557 // which otherwise failed for Visual Studio 10 (Release and Debug) const tol1 = 200 * tol0; const tol2 = @sqrt(tol0); // Check on bisection interval const tolb = tol0; const xthresh = 1000 * tol2; const degree = math.pi / hd; const nan = math.nan(f64); /// The geodesics of the ellipsoid with equatorial radius `a` and flattening /// `f`. pub fn init(a: f64, f: f64) Geodesic { var g: Geodesic = .{ .a = a, .f = f, .f1 = 1 - f, .e2 = f * (2 - f), .ep2 = undefined, .n = f / (2 - f), .b = a * (1 - f), .etol2 = undefined, .A3x = undefined, .C3x = undefined, }; g.ep2 = g.e2 / sq(g.f1); // e2 / (1 - e2) // The sig12 threshold for "really short". Using the auxiliary sphere // solution with dnm computed at (bet1 + bet2) / 2, the relative error in // the azimuth consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2. // (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000. For a // given f and sig12, the max error occurs for lines near the pole. If // the old rule for computing dnm = (dn1 + dn2)/2 is used, then the error // increases by a factor of 2.) Setting this equal to epsilon gives sig12 // = etol2. Here 0.1 is a safety factor (error decreased by 100) and // max(0.001, abs(f)) stops etol2 getting too large in the nearly // spherical case. g.etol2 = 0.1 * tol2 / @sqrt(@max(0.001, @abs(f)) * @min(1.0, 1 - f / 2) / 2); g.a3coeff(); g.c3coeff(); return g; } /// The solution of the inverse problem: how far apart two points are, and /// the azimuths of the geodesic joining them. pub const Inverse = struct { /// The distance, in the units of `a`. distance: f64, /// The azimuth at the first point, in degrees clockwise from north, /// (-180, 180]. azimuth1: f64, /// The azimuth at the second point, continuing in the same direction. azimuth2: f64, /// The arc length on the auxiliary sphere, in degrees. arc: f64, }; /// The solution of the direct problem: where a geodesic arrives. pub const Direct = struct { latitude: f64, /// In [-180, 180]. longitude: f64, /// The azimuth on arrival, in degrees clockwise from north. azimuth: f64, }; /// The geodesic from (`lat1`, `lon1`) to (`lat2`, `lon2`). A latitude outside /// [-90, 90] gives NaNs. pub fn inverse(g: *const Geodesic, lat1_in: f64, lon1: f64, lat2_in: f64, lon2: f64) Inverse { var lat1 = lat1_in; var lat2 = lat2_in; var s12x: f64 = 0; var m12x: f64 = 0; var a12: f64 = 0; var sig12: f64 = undefined; var calp1: f64 = 0; var salp1: f64 = 0; var calp2: f64 = 0; var salp2: f64 = 0; // Compute longitude difference (AngDiff does this carefully). Result is // in [-180, 180] but -180 is only for west-going geodesics. 180 is for // east-going and meridional geodesics. var lon12, var lon12s = angDiff(lon1, lon2); // Make longitude difference positive. var lonsign: f64 = if (math.signbit(lon12)) -1 else 1; lon12 *= lonsign; lon12s *= lonsign; const lam12 = lon12 * degree; // Calculate sincos of lon12 + error (this applies AngRound internally). const slam12, const clam12 = sincosde(lon12, lon12s); // the supplementary longitude difference lon12s = (hd - lon12) - lon12s; // If really close to the equator, treat as on equator. lat1 = angRound(latFix(lat1)); lat2 = angRound(latFix(lat2)); // Swap points so that point with higher (abs) latitude is point 1 // If one latitude is a nan, then it becomes lat1. const swapp: f64 = if (@abs(lat1) < @abs(lat2) or lat2 != lat2) -1 else 1; if (swapp < 0) { lonsign *= -1; std.mem.swap(f64, &lat1, &lat2); } // Make lat1 <= -0 const latsign: f64 = if (math.signbit(lat1)) 1 else -1; lat1 *= latsign; lat2 *= latsign; // Now we have // // 0 <= lon12 <= 180 // -90 <= lat1 <= -0 // lat1 <= lat2 <= -lat1 // // longsign, swapp, latsign register the transformation to bring the // coordinates to this canonical form. In all cases, 1 means no change // was made. We make these transformations so that there are few cases // to check, e.g., on verifying quadrants in atan2. In addition, this // enforces some symmetries in the results returned. var sbet1, var cbet1 = sincosd(lat1); sbet1 *= g.f1; // Ensure cbet1 = +epsilon at poles norm2(&sbet1, &cbet1); cbet1 = @max(tiny, cbet1); var sbet2, var cbet2 = sincosd(lat2); sbet2 *= g.f1; // Ensure cbet2 = +epsilon at poles norm2(&sbet2, &cbet2); cbet2 = @max(tiny, cbet2); // If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure of the // |bet1| - |bet2|. Alternatively (cbet1 >= -sbet1), abs(sbet2) + sbet1 // is a better measure. This logic is used in assigning calp2 in // Lambda12. Sometimes these quantities vanish and in that case we force // bet2 = +/- bet1 exactly. An example where is is necessary is the // inverse problem // 48.522876735459 0 -48.52287673545898293 179.599720456223079643 // which failed with Visual Studio 10 (Release and Debug) // // Departing from geodesic.c here, which tests only for equality. Since // |bet2| <= |bet1|, cbet2 >= cbet1 and abs(sbet2) <= -sbet1 -- but the // rounding in sincosd and norm2 can put two latitudes an ulp apart the // wrong way round as well as level, and then Lambda12 takes the square // root of a negative number and the whole solution is NaN. On a prolate // ellipsoid, for a short line between latitudes an ulp apart, geodesic.c // v2.2 does exactly that, for about one such line in nine thousand. The two // latitudes are then equal to within rounding, so they are treated as // equal, which is what the equality test already does. if (cbet1 < -sbet1) { if (cbet2 <= cbet1) { cbet2 = cbet1; sbet2 = math.copysign(sbet1, sbet2); } } else { if (@abs(sbet2) >= -sbet1) { sbet2 = math.copysign(sbet1, sbet2); cbet2 = cbet1; } } const dn1 = @sqrt(1 + g.ep2 * sq(sbet1)); const dn2 = @sqrt(1 + g.ep2 * sq(sbet2)); var meridian = lat1 == -qd or slam12 == 0; if (meridian) { // Endpoints are on a single full meridian, so the geodesic might lie // on a meridian. calp1 = clam12; // Head to the target longitude salp1 = slam12; calp2 = 1; // At the target we're heading north salp2 = 0; // tan(bet) = tan(sig) * cos(alp) const ssig1 = sbet1; const csig1 = calp1 * cbet1; const ssig2 = sbet2; const csig2 = calp2 * cbet2; // sig12 = sig2 - sig1 sig12 = math.atan2(@max(0.0, csig1 * ssig2 - ssig1 * csig2) + 0, csig1 * csig2 + ssig1 * ssig2); const l = g.lengths(g.n, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, true); s12x = l.s12b; m12x = l.m12b; // Add the check for sig12 since zero length geodesics might yield // m12 < 0. Test case was // // echo 20.001 0 20.001 0 | GeodSolve -i if (sig12 < tol2 or m12x >= 0) { // Need at least 2, to handle 90 0 90 180 if (sig12 < 3 * tiny or // Prevent negative s12 or m12 for short lines (sig12 < tol0 and (s12x < 0 or m12x < 0))) { sig12 = 0; m12x = 0; s12x = 0; } m12x *= g.b; s12x *= g.b; a12 = sig12 / degree; } else { // m12 < 0, i.e., prolate and too close to anti-podal meridian = false; } } if (!meridian and sbet1 == 0 and // and sbet2 == 0 // Mimic the way Lambda12 works with calp1 = 0 (g.f <= 0 or lon12s >= g.f * hd)) { // Geodesic runs along equator calp1 = 0; calp2 = 0; salp1 = 1; salp2 = 1; s12x = g.a * lam12; sig12 = lam12 / g.f1; a12 = lon12 / g.f1; } else if (!meridian) { // Now point1 and point2 belong within a hemisphere bounded by a // meridian and geodesic is neither meridional or equatorial. // Figure a starting point for Newton's method const start = g.inverseStart(sbet1, cbet1, dn1, sbet2, cbet2, dn2, lam12, slam12, clam12); sig12 = start.sig12; salp1 = start.salp1; calp1 = start.calp1; if (sig12 >= 0) { // Short lines (InverseStart sets salp2, calp2, dnm) salp2 = start.salp2; calp2 = start.calp2; s12x = sig12 * g.b * start.dnm; a12 = sig12 / degree; } else { // Newton's method. This is a straightforward solution of // f(alp1) = lambda12(alp1) - lam12 = 0 with one wrinkle. f(alp) // has exactly one root in the interval (0, pi) and its derivative // is positive at the root. Thus f(alp) is positive for alp > // alp1 and negative for alp < alp1. During the course of the // iteration, a range (alp1a, alp1b) is maintained which brackets // the root and with each evaluation of f(alp) the range is // shrunk, if possible. Newton's method is restarted whenever the // derivative of f is negative (because the new value of alp1 is // then further from the solution) or if the new estimate of alp1 // lies outside (0,pi); in this case, the new starting guess is // taken to be (alp1a + alp1b) / 2. var lambda: Lambda = undefined; var numit: u32 = 0; // Bracketing range var salp1a: f64 = tiny; var calp1a: f64 = 1; var salp1b: f64 = tiny; var calp1b: f64 = -1; var tripn = false; var tripb = false; while (true) : (numit += 1) { // the WGS84 test set: mean = 1.47, sd = 1.25, max = 16 // WGS84 and random input: mean = 2.85, sd = 0.60 lambda = g.lambda12(sbet1, cbet1, dn1, sbet2, cbet2, dn2, salp1, calp1, slam12, clam12, numit < maxit1); const v = lambda.lam12; const dv = lambda.dlam12; if (tripb or // Reversed test to allow escape with NaNs !(@abs(v) >= @as(f64, if (tripn) 8 else 1) * tol0) or // Enough bisections to get accurate result numit == maxit2) break; // Update bracketing values if (v > 0 and (numit > maxit1 or calp1 / salp1 > calp1b / salp1b)) { salp1b = salp1; calp1b = calp1; } else if (v < 0 and (numit > maxit1 or calp1 / salp1 < calp1a / salp1a)) { salp1a = salp1; calp1a = calp1; } if (numit < maxit1 and dv > 0) { const dalp1 = -v / dv; if (@abs(dalp1) < math.pi) { const sdalp1 = @sin(dalp1); const cdalp1 = @cos(dalp1); const nsalp1 = salp1 * cdalp1 + calp1 * sdalp1; if (nsalp1 > 0) { calp1 = calp1 * cdalp1 - salp1 * sdalp1; salp1 = nsalp1; norm2(&salp1, &calp1); // In some regimes we don't get quadratic // convergence because slope -> 0. So use // convergence conditions based on epsilon // instead of sqrt(epsilon). tripn = @abs(v) <= 16 * tol0; continue; } } } // Either dv was not positive or updated value was outside // legal range. Use the midpoint of the bracket as the next // estimate. This mechanism is not needed for the WGS84 // ellipsoid, but it does catch problems with more eccentric // ellipsoids. Its efficacy is such for the WGS84 test set // with the starting guess set to alp1 = 90deg: // the WGS84 test set: mean = 5.21, sd = 3.93, max = 24 // WGS84 and random input: mean = 4.74, sd = 0.99 salp1 = (salp1a + salp1b) / 2; calp1 = (calp1a + calp1b) / 2; norm2(&salp1, &calp1); tripn = false; tripb = (@abs(salp1a - salp1) + (calp1a - calp1) < tolb or @abs(salp1 - salp1b) + (calp1 - calp1b) < tolb); } salp2 = lambda.salp2; calp2 = lambda.calp2; sig12 = lambda.sig12; const l = g.lengths(lambda.eps, sig12, lambda.ssig1, lambda.csig1, dn1, lambda.ssig2, lambda.csig2, dn2, true); s12x = l.s12b * g.b; a12 = sig12 / degree; } } // Convert calp, salp to azimuth accounting for lonsign, swapp, latsign. if (swapp < 0) { std.mem.swap(f64, &salp1, &salp2); std.mem.swap(f64, &calp1, &calp2); } salp1 *= swapp * lonsign; calp1 *= swapp * latsign; salp2 *= swapp * lonsign; calp2 *= swapp * latsign; return .{ .distance = 0 + s12x, // Convert -0 to 0 .azimuth1 = atan2d(salp1, calp1), .azimuth2 = atan2d(salp2, calp2), .arc = a12, }; } /// Where the geodesic from (`lat1`, `lon1`) on azimuth `azi1` arrives after /// `s12`, which may be negative. pub fn direct(g: *const Geodesic, lat1: f64, lon1: f64, azi1_in: f64, s12: f64) Direct { const azi1 = angNormalize(azi1_in); // Guard against underflow in salp0 const salp1, const calp1 = sincosd(angRound(azi1)); // geod_lineinit_int, for a line that can be followed by distance and // give longitude, latitude and azimuth. var sbet1, var cbet1 = sincosd(angRound(latFix(lat1))); sbet1 *= g.f1; // Ensure cbet1 = +epsilon at poles norm2(&sbet1, &cbet1); cbet1 = @max(tiny, cbet1); // Evaluate alp0 from sin(alp1) * cos(bet1) = sin(alp0), const salp0 = salp1 * cbet1; // alp0 in [0, pi/2 - |bet1|] // Alt: calp0 = hypot(sbet1, calp1 * cbet1). The following // is slightly better (consider the case salp1 = 0). const calp0 = math.hypot(calp1, salp1 * sbet1); // Evaluate sig with tan(bet1) = tan(sig1) * cos(alp1). // sig = 0 is nearest northward crossing of equator. // With bet1 = 0, alp1 = pi/2, we have sig1 = 0 (equatorial line). // With bet1 = pi/2, alp1 = -pi, sig1 = pi/2 // With bet1 = -pi/2, alp1 = 0 , sig1 = -pi/2 // Evaluate omg1 with tan(omg1) = sin(alp0) * tan(sig1). // With alp0 in (0, pi/2], quadrants for sig and omg coincide. // No atan2(0,0) ambiguity at poles since cbet1 = +epsilon. // With alp0 = 0, omg1 = 0 for alp1 = 0, omg1 = pi for alp1 = pi. var ssig1 = sbet1; const somg1 = salp0 * sbet1; var csig1 = if (sbet1 != 0 or calp1 != 0) cbet1 * calp1 else 1; const comg1 = csig1; norm2(&ssig1, &csig1); // sig1 in (-pi, pi] // norm2(somg1, comg1); -- don't need to normalize! const k2 = sq(calp0) * g.ep2; const eps = k2 / (2 * (1 + @sqrt(1 + k2)) + k2); var c1a: [nC]f64 = undefined; const a1m1 = a1m1f(eps); c1f(eps, &c1a); const b11 = sinSeries(ssig1, csig1, &c1a, nC1); const s = @sin(b11); const c = @cos(b11); // tau1 = sig1 + B11 const stau1 = ssig1 * c + csig1 * s; const ctau1 = csig1 * c - ssig1 * s; var c1pa: [nC]f64 = undefined; c1pf(eps, &c1pa); var c3a: [nC]f64 = undefined; g.c3f(eps, &c3a); const a3c = -g.f * salp0 * g.a3f(eps); const b31 = sinSeries(ssig1, csig1, &c3a, nC3 - 1); // geod_genposition, with s12 a distance. const tau12 = s12 / (g.b * (1 + a1m1)); const st = @sin(tau12); const ct = @cos(tau12); // tau2 = tau1 + tau12 var b12 = -sinSeries(stau1 * ct + ctau1 * st, ctau1 * ct - stau1 * st, &c1pa, nC1p); var sig12 = tau12 - (b12 - b11); var ssig12 = @sin(sig12); var csig12 = @cos(sig12); if (@abs(g.f) > 0.01) { // Reverted distance series is inaccurate for |f| > 1/100, so correct // sig12 with 1 Newton iteration. const ssig2 = ssig1 * csig12 + csig1 * ssig12; const csig2 = csig1 * csig12 - ssig1 * ssig12; b12 = sinSeries(ssig2, csig2, &c1a, nC1); const serr = (1 + a1m1) * (sig12 + (b12 - b11)) - s12 / g.b; sig12 = sig12 - serr / @sqrt(1 + k2 * sq(ssig2)); ssig12 = @sin(sig12); csig12 = @cos(sig12); } // sig2 = sig1 + sig12 const ssig2 = ssig1 * csig12 + csig1 * ssig12; var csig2 = csig1 * csig12 - ssig1 * ssig12; // sin(bet2) = cos(alp0) * sin(sig2) const sbet2 = calp0 * ssig2; // Alt: cbet2 = hypot(csig2, salp0 * ssig2); var cbet2 = math.hypot(salp0, calp0 * csig2); if (cbet2 == 0) { // I.e., salp0 = 0, csig2 = 0. Break the degeneracy in this case cbet2 = tiny; csig2 = tiny; } // tan(alp0) = cos(sig2)*tan(alp2) const salp2 = salp0; const calp2 = calp0 * csig2; // No need to normalize // tan(omg2) = sin(alp0) * tan(sig2) const somg2 = salp0 * ssig2; const comg2 = csig2; // No need to normalize // omg12 = omg2 - omg1 const omg12 = math.atan2(somg2 * comg1 - comg2 * somg1, comg2 * comg1 + somg2 * somg1); const lam12 = omg12 + a3c * (sig12 + (sinSeries(ssig2, csig2, &c3a, nC3 - 1) - b31)); const lon12 = lam12 / degree; return .{ .latitude = atan2d(sbet2, g.f1 * cbet2), .longitude = angNormalize(angNormalize(lon1) + angNormalize(lon12)), .azimuth = atan2d(salp2, calp2), }; } const Lengths = struct { s12b: f64, m12b: f64, m0: f64 }; /// Return m12b = (reduced length)/b; also calculate s12b = distance/b, and /// m0 = coefficient of secular term in expression for reduced length. The /// distance is worked out only when asked for, since the reduced length is /// then summed in a different order. fn lengths( g: *const Geodesic, eps: f64, sig12: f64, ssig1: f64, csig1: f64, dn1: f64, ssig2: f64, csig2: f64, dn2: f64, comptime distance: bool, ) Lengths { _ = g; var ca: [nC]f64 = undefined; var cb: [nC]f64 = undefined; var a1 = a1m1f(eps); c1f(eps, &ca); var a2 = a2m1f(eps); c2f(eps, &cb); const m0 = a1 - a2; a2 = 1 + a2; a1 = 1 + a1; var s12b: f64 = 0; var j12: f64 = undefined; if (distance) { const b1 = sinSeries(ssig2, csig2, &ca, nC1) - sinSeries(ssig1, csig1, &ca, nC1); // Missing a factor of b s12b = a1 * (sig12 + b1); const b2 = sinSeries(ssig2, csig2, &cb, nC2) - sinSeries(ssig1, csig1, &cb, nC2); j12 = m0 * sig12 + (a1 * b1 - a2 * b2); } else { // Assume here that nC1 >= nC2 for (1..nC2 + 1) |l| cb[l] = a1 * ca[l] - a2 * cb[l]; j12 = m0 * sig12 + (sinSeries(ssig2, csig2, &cb, nC2) - sinSeries(ssig1, csig1, &cb, nC2)); } return .{ .s12b = s12b, // Missing a factor of b. // Add parens around (csig1 * ssig2) and (ssig1 * csig2) to ensure // accurate cancellation in the case of coincident points. .m12b = dn2 * (csig1 * ssig2) - dn1 * (ssig1 * csig2) - csig1 * csig2 * j12, .m0 = m0, }; } /// Solve k^4+2*k^3-(x^2+y^2-1)*k^2-2*y^2*k-y^2 = 0 for positive root k. /// This solution is adapted from Geocentric::Reverse. fn astroid(x: f64, y: f64) f64 { const p = sq(x); const q = sq(y); const r = (p + q - 1) / 6; if (q == 0 and r <= 0) { // y = 0 with |x| <= 1. Handle this case directly. // for y small, positive root is k = abs(y)/sqrt(1-x^2) return 0; } // Avoid possible division by zero when r = 0 by multiplying equations // for s and t by r^3 and r, resp. const S = p * q / 4; // S = r^3 * s const r2 = sq(r); const r3 = r * r2; // The discriminant of the quadratic equation for T3. This is zero on // the evolute curve p^(1/3)+q^(1/3) = 1 const disc = S * (S + 2 * r3); var u = r; if (disc >= 0) { var T3 = S + r3; // Pick the sign on the sqrt to maximize abs(T3). This minimizes loss // of precision due to cancellation. The result is unchanged because // of the way the T is used in definition of u. T3 += if (T3 < 0) -@sqrt(disc) else @sqrt(disc); // T3 = (r * t)^3 // N.B. cbrt always returns the double root. cbrt(-8) = -2. const T = math.cbrt(T3); // T = r * t // T can be zero; but then r2 / T -> 0. u += T + (if (T != 0) r2 / T else 0); } else { // T is complex, but the way u is defined the result is double. const ang = math.atan2(@sqrt(-disc), -(S + r3)); // There are three possible cube roots. We choose the root which // avoids cancellation. Note that disc < 0 implies that r < 0. u += 2 * r * @cos(ang / 3); } const v = @sqrt(sq(u) + q); // guaranteed positive // Avoid loss of accuracy when u < 0. const uv = if (u < 0) q / (v - u) else u + v; // u+v, guaranteed positive const w = (uv - q) / (2 * v); // positive? // Rearrange expression for k to avoid loss of accuracy due to // subtraction. Division by 0 not possible because uv > 0, w >= 0. return uv / (@sqrt(uv + sq(w)) + w); // guaranteed positive } const Start = struct { /// Negative when Newton's method is needed. sig12: f64, salp1: f64, calp1: f64, /// Only set when `sig12` is not negative. salp2: f64 = 0, calp2: f64 = 0, /// Only set for short lines. dnm: f64 = 0, }; /// Return a starting point for Newton's method in salp1 and calp1 (sig12 is /// -1). If Newton's method doesn't need to be used, return also salp2 and /// calp2 and sig12. fn inverseStart( g: *const Geodesic, sbet1: f64, cbet1: f64, dn1: f64, sbet2: f64, cbet2: f64, dn2: f64, lam12: f64, slam12: f64, clam12: f64, ) Start { var result: Start = .{ .sig12 = -1, .salp1 = 0, .calp1 = 0 }; var salp1: f64 = 0; var calp1: f64 = 0; // bet12 = bet2 - bet1 in [0, pi); bet12a = bet2 + bet1 in (-pi, 0] const sbet12 = sbet2 * cbet1 - cbet2 * sbet1; const cbet12 = cbet2 * cbet1 + sbet2 * sbet1; const shortline = cbet12 >= 0 and sbet12 < 0.5 and cbet2 * lam12 < 0.5; const sbet12a = sbet2 * cbet1 + cbet2 * sbet1; var somg12: f64 = undefined; var comg12: f64 = undefined; if (shortline) { var sbetm2 = sq(sbet1 + sbet2); // sin((bet1+bet2)/2)^2 // = (sbet1 + sbet2)^2 / ((sbet1 + sbet2)^2 + (cbet1 + cbet2)^2) sbetm2 /= sbetm2 + sq(cbet1 + cbet2); result.dnm = @sqrt(1 + g.ep2 * sbetm2); const omg12 = lam12 / (g.f1 * result.dnm); somg12 = @sin(omg12); comg12 = @cos(omg12); } else { somg12 = slam12; comg12 = clam12; } salp1 = cbet2 * somg12; calp1 = if (comg12 >= 0) sbet12 + cbet2 * sbet1 * sq(somg12) / (1 + comg12) else sbet12a - cbet2 * sbet1 * sq(somg12) / (1 - comg12); const ssig12 = math.hypot(salp1, calp1); const csig12 = sbet1 * sbet2 + cbet1 * cbet2 * comg12; if (shortline and ssig12 < g.etol2) { // really short lines var salp2 = cbet1 * somg12; var calp2 = sbet12 - cbet1 * sbet2 * (if (comg12 >= 0) sq(somg12) / (1 + comg12) else 1 - comg12); norm2(&salp2, &calp2); result.salp2 = salp2; result.calp2 = calp2; // Set return value result.sig12 = math.atan2(ssig12, csig12); } else if (@abs(g.n) > 0.1 or // No astroid calc if too eccentric csig12 >= 0 or ssig12 >= 6 * @abs(g.n) * math.pi * sq(cbet1)) { // Nothing to do, zeroth order spherical approximation is OK } else { // Scale lam12 and bet2 to x, y coordinate system where antipodal // point is at origin and singular point is at y = 0, x = -1. var x: f64 = undefined; var y: f64 = undefined; var lamscale: f64 = undefined; var betscale: f64 = undefined; const lam12x = math.atan2(-slam12, -clam12); // lam12 - pi if (g.f >= 0) { // In fact f == 0 does not get here // x = dlong, y = dlat const k2 = sq(sbet1) * g.ep2; const eps = k2 / (2 * (1 + @sqrt(1 + k2)) + k2); lamscale = g.f * cbet1 * g.a3f(eps) * math.pi; betscale = lamscale * cbet1; x = lam12x / lamscale; y = sbet12a / betscale; } else { // f < 0 // x = dlat, y = dlong const cbet12a = cbet2 * cbet1 - sbet2 * sbet1; const bet12a = math.atan2(sbet12a, cbet12a); // In the case of lon12 = 180, this repeats a calculation made in // Inverse. const l = g.lengths(g.n, math.pi + bet12a, sbet1, -cbet1, dn1, sbet2, cbet2, dn2, false); x = -1 + l.m12b / (cbet1 * cbet2 * l.m0 * math.pi); betscale = if (x < -0.01) sbet12a / x else -g.f * sq(cbet1) * math.pi; lamscale = betscale / cbet1; y = lam12x / lamscale; } if (y > -tol1 and x > -1 - xthresh) { // strip near cut if (g.f >= 0) { salp1 = @min(1.0, -x); calp1 = -@sqrt(1 - sq(salp1)); } else { calp1 = @max(@as(f64, if (x > -tol1) 0 else -1), x); salp1 = @sqrt(1 - sq(calp1)); } } else { // Estimate alp1, by solving the astroid problem. // // It's better to estimate omg12 from astroid and use spherical // formula to compute alp1 than to estimate alpha1 directly; this // reduces the mean number of Newton iterations for astroid cases // from 2.24 to 2.12. Because omg12 is near pi, estimate work // with omg12a = pi - omg12 const k = astroid(x, y); const omg12a = lamscale * (if (g.f >= 0) -x * k / (1 + k) else -y * (1 + k) / k); somg12 = @sin(omg12a); comg12 = -@cos(omg12a); // Update spherical estimate of alp1 using omg12 instead of lam12 salp1 = cbet2 * somg12; calp1 = sbet12a - cbet2 * sbet1 * sq(somg12) / (1 - comg12); } } // Sanity check on starting guess. Backwards check allows NaN through. if (!(salp1 <= 0)) { norm2(&salp1, &calp1); } else { salp1 = 1; calp1 = 0; } result.salp1 = salp1; result.calp1 = calp1; return result; } const Lambda = struct { lam12: f64, salp2: f64, calp2: f64, sig12: f64, ssig1: f64, csig1: f64, ssig2: f64, csig2: f64, eps: f64, domg12: f64, /// Only set when asked for. dlam12: f64 = 0, }; fn lambda12( g: *const Geodesic, sbet1: f64, cbet1: f64, dn1: f64, sbet2: f64, cbet2: f64, dn2: f64, salp1: f64, calp1_in: f64, slam120: f64, clam120: f64, diffp: bool, ) Lambda { var calp1 = calp1_in; if (sbet1 == 0 and calp1 == 0) // Break degeneracy of equatorial line. This case has already been // handled. calp1 = -tiny; // sin(alp1) * cos(bet1) = sin(alp0) const salp0 = salp1 * cbet1; const calp0 = math.hypot(calp1, salp1 * sbet1); // calp0 > 0 // tan(bet1) = tan(sig1) * cos(alp1) // tan(omg1) = sin(alp0) * tan(sig1) = tan(omg1)=tan(alp1)*sin(bet1) var ssig1 = sbet1; const somg1 = salp0 * sbet1; var csig1 = calp1 * cbet1; const comg1 = csig1; norm2(&ssig1, &csig1); // norm2(&somg1, &comg1); -- don't need to normalize! // Enforce symmetries in the case abs(bet2) = -bet1. Need to be careful // about this case, since this can yield singularities in the Newton // iteration. // sin(alp2) * cos(bet2) = sin(alp0) const salp2 = if (cbet2 != cbet1) salp0 / cbet2 else salp1; // calp2 = sqrt(1 - sq(salp2)) // = sqrt(sq(calp0) - sq(sbet2)) / cbet2 // and subst for calp0 and rearrange to give (choose positive sqrt // to give alp2 in [0, pi/2]). const calp2 = if (cbet2 != cbet1 or @abs(sbet2) != -sbet1) @sqrt(sq(calp1 * cbet1) + (if (cbet1 < -sbet1) (cbet2 - cbet1) * (cbet1 + cbet2) else (sbet1 - sbet2) * (sbet1 + sbet2))) / cbet2 else @abs(calp1); // tan(bet2) = tan(sig2) * cos(alp2) // tan(omg2) = sin(alp0) * tan(sig2). var ssig2 = sbet2; const somg2 = salp0 * sbet2; var csig2 = calp2 * cbet2; const comg2 = csig2; norm2(&ssig2, &csig2); // norm2(&somg2, &comg2); -- don't need to normalize! // sig12 = sig2 - sig1, limit to [0, pi] const sig12 = math.atan2(@max(0.0, csig1 * ssig2 - ssig1 * csig2) + 0, csig1 * csig2 + ssig1 * ssig2); // omg12 = omg2 - omg1, limit to [0, pi] const somg12 = @max(0.0, comg1 * somg2 - somg1 * comg2) + 0; const comg12 = comg1 * comg2 + somg1 * somg2; // eta = omg12 - lam120 const eta = math.atan2(somg12 * clam120 - comg12 * slam120, comg12 * clam120 + somg12 * slam120); const k2 = sq(calp0) * g.ep2; const eps = k2 / (2 * (1 + @sqrt(1 + k2)) + k2); var ca: [nC]f64 = undefined; g.c3f(eps, &ca); const b312 = sinSeries(ssig2, csig2, &ca, nC3 - 1) - sinSeries(ssig1, csig1, &ca, nC3 - 1); const domg12 = -g.f * g.a3f(eps) * salp0 * (sig12 + b312); var result: Lambda = .{ .lam12 = eta + domg12, .salp2 = salp2, .calp2 = calp2, .sig12 = sig12, .ssig1 = ssig1, .csig1 = csig1, .ssig2 = ssig2, .csig2 = csig2, .eps = eps, .domg12 = domg12, }; if (diffp) { if (calp2 == 0) { result.dlam12 = -2 * g.f1 * dn1 / sbet1; } else { const l = g.lengths(eps, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, false); result.dlam12 = l.m12b * g.f1 / (calp2 * cbet2); } } return result; } /// Evaluate A3 fn a3f(g: *const Geodesic, eps: f64) f64 { return polyval(&g.A3x, eps); } /// Evaluate C3 coeffs. Elements c[1] through c[nC3 - 1] are set fn c3f(g: *const Geodesic, eps: f64, c: *[nC]f64) void { var mult: f64 = 1; var o: usize = 0; for (1..nC3) |l| { // l is index of C3[l] const m = nC3 - l - 1; // order of polynomial in eps mult *= eps; c[l] = mult * polyval(g.C3x[o..][0 .. m + 1], eps); o += m + 1; } } /// The scale factor A1-1 = mean value of (d/dsigma)I1 - 1 fn a1m1f(eps: f64) f64 { const coeff = [_]f64{ // (1-eps)*A1-1, polynomial in eps2 of order 3 1, 4, 64, 0, 256, }; const m = nA1 / 2; const t = polyval(coeff[0 .. m + 1], sq(eps)) / coeff[m + 1]; return (t + eps) / (1 - eps); } /// The coefficients C1[l] in the Fourier expansion of B1 fn c1f(eps: f64, c: *[nC]f64) void { const coeff = [_]f64{ // C1[1]/eps^1, polynomial in eps2 of order 2 -1, 6, -16, 32, // C1[2]/eps^2, polynomial in eps2 of order 2 -9, 64, -128, 2048, // C1[3]/eps^3, polynomial in eps2 of order 1 9, -16, 768, // C1[4]/eps^4, polynomial in eps2 of order 1 3, -5, 512, // C1[5]/eps^5, polynomial in eps2 of order 0 -7, 1280, // C1[6]/eps^6, polynomial in eps2 of order 0 -7, 2048, }; fourier(eps, &coeff, nC1, c); } /// The coefficients C1p[l] in the Fourier expansion of B1p fn c1pf(eps: f64, c: *[nC]f64) void { const coeff = [_]f64{ // C1p[1]/eps^1, polynomial in eps2 of order 2 205, -432, 768, 1536, // C1p[2]/eps^2, polynomial in eps2 of order 2 4005, -4736, 3840, 12288, // C1p[3]/eps^3, polynomial in eps2 of order 1 -225, 116, 384, // C1p[4]/eps^4, polynomial in eps2 of order 1 -7173, 2695, 7680, // C1p[5]/eps^5, polynomial in eps2 of order 0 3467, 7680, // C1p[6]/eps^6, polynomial in eps2 of order 0 38081, 61440, }; fourier(eps, &coeff, nC1p, c); } /// The scale factor A2-1 = mean value of (d/dsigma)I2 - 1 fn a2m1f(eps: f64) f64 { const coeff = [_]f64{ // (eps+1)*A2-1, polynomial in eps2 of order 3 -11, -28, -192, 0, 256, }; const m = nA2 / 2; const t = polyval(coeff[0 .. m + 1], sq(eps)) / coeff[m + 1]; return (t - eps) / (1 + eps); } /// The coefficients C2[l] in the Fourier expansion of B2 fn c2f(eps: f64, c: *[nC]f64) void { const coeff = [_]f64{ // C2[1]/eps^1, polynomial in eps2 of order 2 1, 2, 16, 32, // C2[2]/eps^2, polynomial in eps2 of order 2 35, 64, 384, 2048, // C2[3]/eps^3, polynomial in eps2 of order 1 15, 80, 768, // C2[4]/eps^4, polynomial in eps2 of order 1 7, 35, 512, // C2[5]/eps^5, polynomial in eps2 of order 0 63, 1280, // C2[6]/eps^6, polynomial in eps2 of order 0 77, 2048, }; fourier(eps, &coeff, nC2, c); } /// c[1] through c[n], each eps^l times a polynomial in eps^2 of order /// (n - l) / 2 over a denominator: the shape C1, C1p and C2 share. fn fourier(eps: f64, coeff: []const f64, comptime n: usize, c: *[nC]f64) void { const eps2 = sq(eps); var d = eps; var o: usize = 0; for (1..n + 1) |l| { // l is index of C[l] const m = (n - l) / 2; // order of polynomial in eps^2 c[l] = d * polyval(coeff[o..][0 .. m + 1], eps2) / coeff[o + m + 1]; o += m + 2; d *= eps; } } /// The scale factor A3 = mean value of (d/dsigma)I3 fn a3coeff(g: *Geodesic) void { const coeff = [_]f64{ // A3, coeff of eps^5, polynomial in n of order 0 -3, 128, // A3, coeff of eps^4, polynomial in n of order 1 -2, -3, 64, // A3, coeff of eps^3, polynomial in n of order 2 -1, -3, -1, 16, // A3, coeff of eps^2, polynomial in n of order 2 3, -1, -2, 8, // A3, coeff of eps^1, polynomial in n of order 1 1, -1, 2, // A3, coeff of eps^0, polynomial in n of order 0 1, 1, }; var o: usize = 0; var k: usize = 0; var j: usize = nA3; while (j > 0) { // coeff of eps^j j -= 1; const m = @min(nA3 - j - 1, j); // order of polynomial in n g.A3x[k] = polyval(coeff[o..][0 .. m + 1], g.n) / coeff[o + m + 1]; k += 1; o += m + 2; } } /// The coefficients C3[l] in the Fourier expansion of B3 fn c3coeff(g: *Geodesic) void { const coeff = [_]f64{ // C3[1], coeff of eps^5, polynomial in n of order 0 3, 128, // C3[1], coeff of eps^4, polynomial in n of order 1 2, 5, 128, // C3[1], coeff of eps^3, polynomial in n of order 2 -1, 3, 3, 64, // C3[1], coeff of eps^2, polynomial in n of order 2 -1, 0, 1, 8, // C3[1], coeff of eps^1, polynomial in n of order 1 -1, 1, 4, // C3[2], coeff of eps^5, polynomial in n of order 0 5, 256, // C3[2], coeff of eps^4, polynomial in n of order 1 1, 3, 128, // C3[2], coeff of eps^3, polynomial in n of order 2 -3, -2, 3, 64, // C3[2], coeff of eps^2, polynomial in n of order 2 1, -3, 2, 32, // C3[3], coeff of eps^5, polynomial in n of order 0 7, 512, // C3[3], coeff of eps^4, polynomial in n of order 1 -10, 9, 384, // C3[3], coeff of eps^3, polynomial in n of order 2 5, -9, 5, 192, // C3[4], coeff of eps^5, polynomial in n of order 0 7, 512, // C3[4], coeff of eps^4, polynomial in n of order 1 -14, 7, 512, // C3[5], coeff of eps^5, polynomial in n of order 0 21, 2560, }; var o: usize = 0; var k: usize = 0; for (1..nC3) |l| { // l is index of C3[l] var j: usize = nC3 - 1; while (j >= l) : (j -= 1) { // coeff of eps^j const m = @min(nC3 - j - 1, j); // order of polynomial in n g.C3x[k] = polyval(coeff[o..][0 .. m + 1], g.n) / coeff[o + m + 1]; k += 1; o += m + 2; } } } // -- Arithmetic -------------------------------------------------------------- fn sq(x: f64) f64 { return x * x; } /// The error-free sum: u + v = s + t exactly, s = round(u + v). fn sumx(u: f64, v: f64) struct { f64, f64 } { const s = u + v; var up = s - v; var vpp = s - up; up -= u; vpp -= v; return .{ s, if (s != 0) 0 - (up + vpp) else s }; } /// Horner's method over `p`, highest power first. fn polyval(p: []const f64, x: f64) f64 { if (p.len == 0) return 0; var y = p[0]; for (p[1..]) |c| y = y * x + c; return y; } fn norm2(sinx: *f64, cosx: *f64) void { const r = math.hypot(sinx.*, cosx.*); sinx.* /= r; cosx.* /= r; } /// Evaluate /// y = sum(c[i] * sin(2*i * x), i, 1, n) /// using Clenshaw summation. N.B. c[0] is unused. /// Approx operation count = (n + 5) mult and (2 * n + 2) add fn sinSeries(sinx: f64, cosx: f64, c: *const [nC]f64, n: usize) f64 { var i = n + 1; // Point to one beyond last element const ar = 2 * (cosx - sinx) * (cosx + sinx); // 2 * cos(2 * x) var y0: f64 = 0; // accumulators for sum var y1: f64 = 0; if (n & 1 != 0) { i -= 1; y0 = c[i]; } // Now n is even var k = n / 2; while (k > 0) : (k -= 1) { // Unroll loop x 2, so accumulators return to their original role i -= 1; y1 = ar * y0 - y1 + c[i]; i -= 1; y0 = ar * y1 - y0 + c[i]; } return 2 * sinx * cosx * y0; // sin(2 * x) * y0 } /// C's `remainder`: x - n*y for the integer n nearest x/y, ties to even, /// which is exact. `@rem` truncates instead, so it is taken modulo 2y, which /// keeps the parity of the quotient, and the tie is settled from there. fn remainder(x: f64, y: f64) f64 { const r = @rem(x, 2 * y); const a = @abs(r); if (a <= y / 2) return r; if (a < 3 * y / 2) return r - math.copysign(y, r); return r - math.copysign(2 * y, r); } /// C's `remquo(x, 90, &q)`: the remainder in [-45, 45], and the quotient /// modulo four, which is all the quadrant needs. Exact, as `remainder` is. fn remquo90(x: f64) struct { f64, i32 } { // x = 360k + r, and 360k is a whole number of quarter turns. const r = @rem(x, td); const a = @abs(r); // The nearest multiple of 90, ties to even. const n: i32 = if (a <= 45) 0 else if (a < 135) 1 else if (a <= 225) 2 else if (a < 315) 3 else 4; const rem = a - @as(f64, @floatFromInt(n)) * qd; return if (math.signbit(r)) .{ -rem, -n } else .{ rem, n }; } fn angNormalize(x: f64) f64 { const y = remainder(x, td); return if (@abs(y) == hd) math.copysign(hd, x) else y; } fn latFix(x: f64) f64 { return if (@abs(x) > qd) nan else x; } /// y - x, reduced to [-180, 180], and the rounding error it carries. fn angDiff(x: f64, y: f64) struct { f64, f64 } { // Use remainder instead of AngNormalize, since we treat boundary cases // later taking account of the error var d, var t = sumx(remainder(-x, td), remainder(y, td)); // This second sum can only change d if abs(d) < 128, so don't need to // apply remainder yet again. d, t = sumx(remainder(d, td), t); // Fix the sign if d = -180, 0, 180. if (d == 0 or @abs(d) == hd) // If t == 0, take sign from y - x // else (t != 0, implies d = +/-180), d and t must have opposite signs d = math.copysign(d, if (t == 0) y - x else -t); return .{ d, t }; } fn angRound(x: f64) f64 { const z: f64 = 1.0 / 16.0; var y = @abs(x); const w = z - y; // The compiler mustn't "simplify" z - (z - y) to y, and without // fast-math it doesn't. y = if (w > 0) z - w else y; return math.copysign(y, x); } /// The sine and cosine of `r` degrees in quadrant `q` of the angle `x`. fn quadrant(r: f64, q: i32, x: f64) struct { f64, f64 } { const s = @sin(r); const c = @cos(r); var sinx: f64, var cosx: f64 = switch (@mod(q, 4)) { 0 => .{ s, c }, 1 => .{ c, -s }, 2 => .{ -s, -c }, else => .{ -c, s }, }; cosx += 0; // special values from F.10.1.12 // special values from F.10.1.13 if (sinx == 0) sinx = math.copysign(sinx, x); return .{ sinx, cosx }; } /// In order to minimize round-off errors, this function exactly reduces the /// argument to the range [-45, 45] before converting it to radians. fn sincosd(x: f64) struct { f64, f64 } { const r, const q = remquo90(x); // now abs(r) <= 45 return quadrant(r * degree, q, x); } /// `sincosd` of x + t, where t is a small correction to x. fn sincosde(x: f64, t: f64) struct { f64, f64 } { const r, const q = remquo90(x); // now abs(r) <= 45 return quadrant(angRound(r + t) * degree, q, x); } /// In order to minimize round-off errors, this function rearranges the /// arguments so that result of atan2 is in the range [-pi/4, pi/4] before /// converting it to degrees and mapping the result to the correct quadrant. fn atan2d(y_in: f64, x_in: f64) f64 { var x = x_in; var y = y_in; var q: u2 = 0; if (@abs(y) > @abs(x)) { std.mem.swap(f64, &x, &y); q = 2; } if (math.signbit(x)) { x = -x; q += 1; } // here x >= 0 and x >= abs(y), so angle is in [-pi/4, pi/4] const ang = math.atan2(y, x) / degree; return switch (q) { 1 => math.copysign(hd, y) - ang, 2 => qd - ang, 3 => -qd + ang, else => ang, }; } // -- Tests ------------------------------------------------------------------- const testing = std.testing; const wgs84_a = 6378137; const wgs84_f = 1.0 / 298.257223563; fn expectNear(expected: f64, actual: f64, tolerance: f64) !void { try testing.expectApproxEqAbs(expected, actual, tolerance); } // Twenty geodesics from Karney's test set on WGS 84, as geodtest.c has them: // lat1, lon1, azi1, lat2, lon2 (unrolled), azi2, s12, a12. geodtest.c // carries the reduced length, geodesic scales and area as well, which this // port does not compute. const testcases = [_][8]f64{ .{ 35.60777, -139.44815, 111.098748429560326, -11.17491, -69.95921, 129.289270889708762, 8935244.5604818305, 80.50729714281974 }, .{ 55.52454, 106.05087, 22.020059880982801, 77.03196, 197.18234, 109.112041110671519, 4105086.1713924406, 36.892740690445894 }, .{ -21.97856, 142.59065, -32.44456876433189, 41.84138, 98.56635, -41.84359951440466, 8394328.894657671, 75.62930491011522 }, .{ -66.99028, 112.2363, 173.73491240878403, -12.70631, 285.90344, 2.512956620913668, 11150344.2312080241, 100.278634181155759 }, .{ -17.42761, 173.34268, -159.033557661192928, -15.84784, 5.93557, -20.787484651536988, 16076603.1631180673, 144.640108810286253 }, .{ 32.84994, 48.28919, 150.492927788121982, -56.28556, 202.29132, 48.113449399816759, 16727068.9438164461, 150.565799985466607 }, .{ 6.96833, 52.74123, 92.581585386317712, -7.39675, 206.17291, 90.721692165923907, 17102477.2496958388, 154.147366239113561 }, .{ -50.56724, -16.30485, -105.439679907590164, -33.56571, -94.97412, -47.348547835650331, 6455670.5118668696, 58.083719495371259 }, .{ -58.93002, -8.90775, 140.965397902500679, -8.91104, 133.13503, 19.255429433416599, 11756066.0219864627, 105.755691241406877 }, .{ -68.82867, -74.28391, 93.774347763114881, -50.63005, -8.36685, 34.65564085411343, 3956936.926063544, 35.572254987389284 }, .{ -10.62672, -32.0898, -86.426713286747751, 5.883, -134.31681, -80.473780971034875, 11470869.3864563009, 103.387395634504061 }, .{ -21.76221, 166.90563, 29.319421206936428, 48.72884, 213.97627, 43.508671946410168, 9098627.3986554915, 81.963476716121964 }, .{ -19.79938, -174.47484, 71.167275780171533, -11.99349, -154.35109, 65.589099775199228, 2319004.8601169389, 20.896611684802389 }, .{ -11.95887, -116.94513, 92.712619830452549, 4.57352, 7.16501, 78.64960934409585, 13834722.5801401374, 124.688684161089762 }, .{ -87.85331, 85.66836, -65.120313040242748, 66.48646, 16.09921, -4.888658719272296, 17286615.3147144645, 155.58592449699137 }, .{ 1.74708, 128.32011, -101.584843631173858, -11.16617, 11.87109, -86.325793296437476, 12942901.1241347408, 116.650512484301857 }, .{ -25.72959, -144.90758, -153.647468693117198, -57.70581, -269.17879, -48.343983158876487, 9413446.7452453107, 84.664533838404295 }, .{ -41.22777, 122.32875, 14.285113402275739, -7.57291, 130.37946, 10.805303085187369, 3812686.035106021, 34.34330804743883 }, .{ 11.01307, 138.25278, 79.43682622782374, 6.62726, 247.05981, 103.708090215522657, 11911190.819018408, 107.341669954114577 }, .{ -29.47124, 95.14681, -163.779130441688382, -27.46601, -69.15955, -15.909335945554969, 13487015.8381145492, 121.294026715742277 }, }; test "Karney's test set: inverse" { const g: Geodesic = .init(wgs84_a, wgs84_f); for (testcases) |t| { const r = g.inverse(t[0], t[1], t[3], t[4]); try expectNear(t[2], r.azimuth1, 1e-13); try expectNear(t[5], r.azimuth2, 1e-13); try expectNear(t[6], r.distance, 1e-8); try expectNear(t[7], r.arc, 1e-13); } } test "Karney's test set: direct" { const g: Geodesic = .init(wgs84_a, wgs84_f); for (testcases) |t| { const r = g.direct(t[0], t[1], t[2], t[6]); try expectNear(t[3], r.latitude, 1e-13); // The test set's longitudes are unrolled; these are not. try expectNear(0, angDiff(t[4], r.longitude)[0], 1e-13); try expectNear(t[5], r.azimuth, 1e-13); } } test "GeodSolve0 and 1: JFK to CDG, both ways" { const g: Geodesic = .init(wgs84_a, wgs84_f); const i = g.inverse(40.6, -73.8, 49.01666667, 2.55); try expectNear(53.47022, i.azimuth1, 0.5e-5); try expectNear(111.59367, i.azimuth2, 0.5e-5); try expectNear(5853226, i.distance, 0.5); const d = g.direct(40.63972222, -73.77888889, 53.5, 5850e3); try expectNear(49.01467, d.latitude, 0.5e-5); try expectNear(2.56106, d.longitude, 0.5e-5); try expectNear(111.62947, d.azimuth, 0.5e-5); } test "GeodSolve2: nearly antipodal on a prolate ellipsoid" { const g: Geodesic = .init(6.4e6, -1.0 / 150.0); var r = g.inverse(0.07476, 0, -0.07476, 180); try expectNear(90.00078, r.azimuth1, 0.5e-5); try expectNear(90.00078, r.azimuth2, 0.5e-5); try expectNear(20106193, r.distance, 0.5); r = g.inverse(0.1, 0, -0.1, 180); try expectNear(90.00105, r.azimuth1, 0.5e-5); try expectNear(90.00105, r.azimuth2, 0.5e-5); try expectNear(20106193, r.distance, 0.5); } test "GeodSolve4: a very short line" { const g: Geodesic = .init(wgs84_a, wgs84_f); try expectNear(0.072, g.inverse(36.493349428792, 0, 36.49334942879201, 0.0000008).distance, 0.5e-3); } test "GeodSolve5: arriving at the pole" { const g: Geodesic = .init(wgs84_a, wgs84_f); const r = g.direct(0.01777745589997, 30, 0, 10e6); try expectNear(90, r.latitude, 0.5e-5); if (r.longitude < 0) { try expectNear(-150, r.longitude, 0.5e-5); try expectNear(180, @abs(r.azimuth), 0.5e-5); } else { try expectNear(30, r.longitude, 0.5e-5); try expectNear(0, r.azimuth, 0.5e-5); } } test "GeodSolve6, 9, 10, 11: nearly antipodal points" { const g: Geodesic = .init(wgs84_a, wgs84_f); try expectNear(20003898.214, g.inverse(88.202499451857, 0, -88.202499451857, 179.981022032992859592).distance, 0.5e-3); try expectNear(20003925.854, g.inverse(89.262080389218, 0, -89.262080389218, 179.992207982775375662).distance, 0.5e-3); try expectNear(20003926.881, g.inverse(89.333123580033, 0, -89.333123580032997687, 179.99295812360148422).distance, 0.5e-3); try expectNear(19993558.287, g.inverse(56.320923501171, 0, -56.320923501171, 179.664747671772880215).distance, 0.5e-3); try expectNear(19991596.095, g.inverse(52.784459512564, 0, -52.784459512563990912, 179.634407464943777557).distance, 0.5e-3); try expectNear(19989144.774, g.inverse(48.522876735459, 0, -48.52287673545898293, 179.599720456223079643).distance, 0.5e-3); } test "GeodSolve12: an extremely prolate ellipsoid" { const g: Geodesic = .init(89.8, -1.83); const r = g.inverse(0, 0, -10, 160); try expectNear(120.27, r.azimuth1, 1e-2); try expectNear(105.15, r.azimuth2, 1e-2); try expectNear(266.7, r.distance, 1e-1); } test "latitudes an ulp apart, rounded the wrong way round, are not a NaN" { // Not one of Karney's: geodesic.c v2.2 answers NaN for both of these, // valid as they are, and the port did too until it treated the two // latitudes as equal. What is expected is the C's answer with the // latitudes made equal, or, for the second, with glibc's sin and cos, // which happen to round them the right way round. const g: Geodesic = .init(6.4e6, -1.0 / 150.0); var r = g.inverse(27.941263379826182, 150.01618669482269, 27.941263379826179, 150.01618844851433); try expectNear(0.17280053107867049, r.distance, 1e-9); try expectNear(89.999999589139719, r.azimuth1, 1e-6); r = g.inverse(-46.269650861397665, 28.037529339220526, -46.26965086139767, 28.037526575117187); try expectNear(0.21268888771184552, r.distance, 1e-9); try expectNear(-90.0000012635644, r.azimuth1, 1e-6); } test "GeodSolve14: a NaN longitude gives NaNs" { const g: Geodesic = .init(wgs84_a, wgs84_f); const r = g.inverse(0, 0, 1, nan); try testing.expect(math.isNan(r.azimuth1)); try testing.expect(math.isNan(r.azimuth2)); try testing.expect(math.isNan(r.distance)); } test "GeodSolve33: along the equator and past its end" { const Case = struct { f: f64, lat2: f64, lon2: f64, azi1: f64, azi2: f64, s12: f64 }; const cases = [_]Case{ .{ .f = wgs84_f, .lat2 = 0, .lon2 = 179, .azi1 = 90, .azi2 = 90, .s12 = 19926189 }, .{ .f = wgs84_f, .lat2 = 0, .lon2 = 179.5, .azi1 = 55.96650, .azi2 = 124.03350, .s12 = 19980862 }, .{ .f = wgs84_f, .lat2 = 0, .lon2 = 180, .azi1 = 0, .azi2 = 180, .s12 = 20003931 }, .{ .f = wgs84_f, .lat2 = 1, .lon2 = 180, .azi1 = 0, .azi2 = 180, .s12 = 19893357 }, .{ .f = 0, .lat2 = 0, .lon2 = 179, .azi1 = 90, .azi2 = 90, .s12 = 19994492 }, .{ .f = 0, .lat2 = 0, .lon2 = 180, .azi1 = 0, .azi2 = 180, .s12 = 20106193 }, .{ .f = 0, .lat2 = 1, .lon2 = 180, .azi1 = 0, .azi2 = 180, .s12 = 19994492 }, .{ .f = -1.0 / 300.0, .lat2 = 0, .lon2 = 179, .azi1 = 90, .azi2 = 90, .s12 = 19994492 }, .{ .f = -1.0 / 300.0, .lat2 = 0, .lon2 = 180, .azi1 = 90, .azi2 = 90, .s12 = 20106193 }, .{ .f = -1.0 / 300.0, .lat2 = 0.5, .lon2 = 180, .azi1 = 33.02493, .azi2 = 146.97364, .s12 = 20082617 }, .{ .f = -1.0 / 300.0, .lat2 = 1, .lon2 = 180, .azi1 = 0, .azi2 = 180, .s12 = 20027270 }, }; for (cases) |c| { const g: Geodesic = .init(if (c.f == wgs84_f) wgs84_a else 6.4e6, c.f); const r = g.inverse(0, 0, c.lat2, c.lon2); try expectNear(c.azi1, r.azimuth1, 0.5e-5); try expectNear(c.azi2, @abs(r.azimuth2), 0.5e-5); try expectNear(c.s12, r.distance, 0.5); } } test remainder { try testing.expectEqual(@as(f64, 0), remainder(360, 360)); try testing.expectEqual(@as(f64, 180), remainder(180, 360)); try testing.expectEqual(@as(f64, -180), remainder(540, 360)); // 1.5: ties to 2 try testing.expectEqual(@as(f64, 180), remainder(-540, 360)); try testing.expectEqual(@as(f64, -170), remainder(190, 360)); try testing.expectEqual(@as(f64, 10), remainder(3610, 360)); try testing.expect(math.signbit(remainder(-0.0, 360))); } test remquo90 { const cases = [_]struct { f64, f64, i32 }{ .{ 0, 0, 0 }, .{ 45, 45, 0 }, .{ 46, -44, 1 }, .{ 135, -45, 2 }, .{ 225, 45, 2 }, .{ 315, -45, 4 }, .{ -46, 44, -1 }, .{ 400, 40, 4 }, .{ -90, 0, -1 }, .{ 719, -1, 8 }, }; for (cases) |c| { const r, const q = remquo90(c[0]); try testing.expectEqual(c[1], r); try testing.expectEqual(@mod(c[2], 4), @mod(q, 4)); } }