GeographicLib  1.43
GeodesicExact.cpp
Go to the documentation of this file.
1 /**
2  * \file GeodesicExact.cpp
3  * \brief Implementation for GeographicLib::GeodesicExact class
4  *
5  * Copyright (c) Charles Karney (2012-2015) <charles@karney.com> and licensed
6  * under the MIT/X11 License. For more information, see
7  * http://geographiclib.sourceforge.net/
8  *
9  * This is a reformulation of the geodesic problem. The notation is as
10  * follows:
11  * - at a general point (no suffix or 1 or 2 as suffix)
12  * - phi = latitude
13  * - beta = latitude on auxiliary sphere
14  * - omega = longitude on auxiliary sphere
15  * - lambda = longitude
16  * - alpha = azimuth of great circle
17  * - sigma = arc length along great circle
18  * - s = distance
19  * - tau = scaled distance (= sigma at multiples of pi/2)
20  * - at northwards equator crossing
21  * - beta = phi = 0
22  * - omega = lambda = 0
23  * - alpha = alpha0
24  * - sigma = s = 0
25  * - a 12 suffix means a difference, e.g., s12 = s2 - s1.
26  * - s and c prefixes mean sin and cos
27  **********************************************************************/
28 
31 
32 #if defined(_MSC_VER)
33 // Squelch warnings about potentially uninitialized local variables and
34 // constant conditional expressions
35 # pragma warning (disable: 4701 4127)
36 #endif
37 
38 namespace GeographicLib {
39 
40  using namespace std;
41 
43  : maxit2_(maxit1_ + Math::digits() + 10)
44  // Underflow guard. We require
45  // tiny_ * epsilon() > 0
46  // tiny_ + epsilon() == epsilon()
47  , tiny_(sqrt(numeric_limits<real>::min()))
48  , tol0_(numeric_limits<real>::epsilon())
49  // Increase multiplier in defn of tol1_ from 100 to 200 to fix inverse
50  // case 52.784459512564 0 -52.784459512563990912 179.634407464943777557
51  // which otherwise failed for Visual Studio 10 (Release and Debug)
52  , tol1_(200 * tol0_)
53  , tol2_(sqrt(tol0_))
54  // Check on bisection interval
55  , tolb_(tol0_ * tol2_)
56  , xthresh_(1000 * tol2_)
57  , _a(a)
58  , _f(f <= 1 ? f : 1/f)
59  , _f1(1 - _f)
60  , _e2(_f * (2 - _f))
61  , _ep2(_e2 / Math::sq(_f1)) // e2 / (1 - e2)
62  , _n(_f / ( 2 - _f))
63  , _b(_a * _f1)
64  // The Geodesic class substitutes atanh(sqrt(e2)) for asinh(sqrt(ep2)) in
65  // the definition of _c2. The latter is more accurate for very oblate
66  // ellipsoids (which the Geodesic class does not attempt to handle). Of
67  // course, the area calculation in GeodesicExact is still based on a
68  // series and so only holds for moderately oblate (or prolate)
69  // ellipsoids.
70  , _c2((Math::sq(_a) + Math::sq(_b) *
71  (_f == 0 ? 1 :
72  (_f > 0 ? Math::asinh(sqrt(_ep2)) : atan(sqrt(-_e2))) /
73  sqrt(abs(_e2))))/2) // authalic radius squared
74  // The sig12 threshold for "really short". Using the auxiliary sphere
75  // solution with dnm computed at (bet1 + bet2) / 2, the relative error in
76  // the azimuth consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2.
77  // (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000. For a
78  // given f and sig12, the max error occurs for lines near the pole. If
79  // the old rule for computing dnm = (dn1 + dn2)/2 is used, then the error
80  // increases by a factor of 2.) Setting this equal to epsilon gives
81  // sig12 = etol2. Here 0.1 is a safety factor (error decreased by 100)
82  // and max(0.001, abs(f)) stops etol2 getting too large in the nearly
83  // spherical case.
84  , _etol2(0.1 * tol2_ /
85  sqrt( max(real(0.001), abs(_f)) * min(real(1), 1 - _f/2) / 2 ))
86  {
87  if (!(Math::isfinite(_a) && _a > 0))
88  throw GeographicErr("Major radius is not positive");
89  if (!(Math::isfinite(_b) && _b > 0))
90  throw GeographicErr("Minor radius is not positive");
91  C4coeff();
92  }
93 
95  static const GeodesicExact wgs84(Constants::WGS84_a(),
97  return wgs84;
98  }
99 
100  Math::real GeodesicExact::CosSeries(real sinx, real cosx,
101  const real c[], int n) {
102  // Evaluate
103  // y = sum(c[i] * cos((2*i+1) * x), i, 0, n-1)
104  // using Clenshaw summation.
105  // Approx operation count = (n + 5) mult and (2 * n + 2) add
106  c += n ; // Point to one beyond last element
107  real
108  ar = 2 * (cosx - sinx) * (cosx + sinx), // 2 * cos(2 * x)
109  y0 = n & 1 ? *--c : 0, y1 = 0; // accumulators for sum
110  // Now n is even
111  n /= 2;
112  while (n--) {
113  // Unroll loop x 2, so accumulators return to their original role
114  y1 = ar * y0 - y1 + *--c;
115  y0 = ar * y1 - y0 + *--c;
116  }
117  return cosx * (y0 - y1); // cos(x) * (y0 - y1)
118  }
119 
120  GeodesicLineExact GeodesicExact::Line(real lat1, real lon1, real azi1,
121  unsigned caps) const {
122  return GeodesicLineExact(*this, lat1, lon1, azi1, caps);
123  }
124 
125  Math::real GeodesicExact::GenDirect(real lat1, real lon1, real azi1,
126  bool arcmode, real s12_a12,
127  unsigned outmask,
128  real& lat2, real& lon2, real& azi2,
129  real& s12, real& m12,
130  real& M12, real& M21,
131  real& S12) const {
132  return GeodesicLineExact(*this, lat1, lon1, azi1,
133  // Automatically supply DISTANCE_IN if necessary
134  outmask | (arcmode ? NONE : DISTANCE_IN))
135  . // Note the dot!
136  GenPosition(arcmode, s12_a12, outmask,
137  lat2, lon2, azi2, s12, m12, M12, M21, S12);
138  }
139 
140  Math::real GeodesicExact::GenInverse(real lat1, real lon1,
141  real lat2, real lon2,
142  unsigned outmask,
143  real& s12, real& azi1, real& azi2,
144  real& m12, real& M12, real& M21,
145  real& S12) const {
146  outmask &= OUT_ALL;
147  // Compute longitude difference (AngDiff does this carefully). Result is
148  // in [-180, 180] but -180 is only for west-going geodesics. 180 is for
149  // east-going and meridional geodesics.
150  real lon12 = Math::AngDiff(Math::AngNormalize(lon1),
151  Math::AngNormalize(lon2));
152  // If very close to being on the same half-meridian, then make it so.
153  lon12 = Math::AngRound(lon12);
154  // Make longitude difference positive.
155  int lonsign = lon12 >= 0 ? 1 : -1;
156  lon12 *= lonsign;
157  // If really close to the equator, treat as on equator.
158  lat1 = Math::AngRound(lat1);
159  lat2 = Math::AngRound(lat2);
160  // Swap points so that point with higher (abs) latitude is point 1
161  int swapp = abs(lat1) >= abs(lat2) ? 1 : -1;
162  if (swapp < 0) {
163  lonsign *= -1;
164  swap(lat1, lat2);
165  }
166  // Make lat1 <= 0
167  int latsign = lat1 < 0 ? 1 : -1;
168  lat1 *= latsign;
169  lat2 *= latsign;
170  // Now we have
171  //
172  // 0 <= lon12 <= 180
173  // -90 <= lat1 <= 0
174  // lat1 <= lat2 <= -lat1
175  //
176  // longsign, swapp, latsign register the transformation to bring the
177  // coordinates to this canonical form. In all cases, 1 means no change was
178  // made. We make these transformations so that there are few cases to
179  // check, e.g., on verifying quadrants in atan2. In addition, this
180  // enforces some symmetries in the results returned.
181 
182  real phi, sbet1, cbet1, sbet2, cbet2, s12x, m12x;
183  // Initialize for the meridian. No longitude calculation is done in this
184  // case to let the parameter default to 0.
185  EllipticFunction E(-_ep2);
186 
187  phi = lat1 * Math::degree();
188  // Ensure cbet1 = +epsilon at poles
189  sbet1 = _f1 * sin(phi);
190  cbet1 = lat1 == -90 ? tiny_ : cos(phi);
191  Math::norm(sbet1, cbet1);
192 
193  phi = lat2 * Math::degree();
194  // Ensure cbet2 = +epsilon at poles
195  sbet2 = _f1 * sin(phi);
196  cbet2 = abs(lat2) == 90 ? tiny_ : cos(phi);
197  Math::norm(sbet2, cbet2);
198 
199  // If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure of the
200  // |bet1| - |bet2|. Alternatively (cbet1 >= -sbet1), abs(sbet2) + sbet1 is
201  // a better measure. This logic is used in assigning calp2 in Lambda12.
202  // Sometimes these quantities vanish and in that case we force bet2 = +/-
203  // bet1 exactly. An example where is is necessary is the inverse problem
204  // 48.522876735459 0 -48.52287673545898293 179.599720456223079643
205  // which failed with Visual Studio 10 (Release and Debug)
206 
207  if (cbet1 < -sbet1) {
208  if (cbet2 == cbet1)
209  sbet2 = sbet2 < 0 ? sbet1 : -sbet1;
210  } else {
211  if (abs(sbet2) == -sbet1)
212  cbet2 = cbet1;
213  }
214 
215  real
216  dn1 = (_f >= 0 ? sqrt(1 + _ep2 * Math::sq(sbet1)) :
217  sqrt(1 - _e2 * Math::sq(cbet1)) / _f1),
218  dn2 = (_f >= 0 ? sqrt(1 + _ep2 * Math::sq(sbet2)) :
219  sqrt(1 - _e2 * Math::sq(cbet2)) / _f1);
220 
221  real
222  lam12 = lon12 * Math::degree(),
223  slam12 = abs(lon12) == 180 ? 0 : sin(lam12),
224  clam12 = cos(lam12); // lon12 == 90 isn't interesting
225 
226  // initial values to suppress warning
227  real a12, sig12, calp1, salp1, calp2 = 0, salp2 = 0;
228 
229  bool meridian = lat1 == -90 || slam12 == 0;
230 
231  if (meridian) {
232 
233  // Endpoints are on a single full meridian, so the geodesic might lie on
234  // a meridian.
235 
236  calp1 = clam12; salp1 = slam12; // Head to the target longitude
237  calp2 = 1; salp2 = 0; // At the target we're heading north
238 
239  real
240  // tan(bet) = tan(sig) * cos(alp)
241  ssig1 = sbet1, csig1 = calp1 * cbet1,
242  ssig2 = sbet2, csig2 = calp2 * cbet2;
243 
244  // sig12 = sig2 - sig1
245  sig12 = atan2(max(csig1 * ssig2 - ssig1 * csig2, real(0)),
246  csig1 * csig2 + ssig1 * ssig2);
247  {
248  real dummy;
249  Lengths(E, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2,
250  cbet1, cbet2, s12x, m12x, dummy,
251  (outmask & GEODESICSCALE) != 0U, M12, M21);
252  }
253  // Add the check for sig12 since zero length geodesics might yield m12 <
254  // 0. Test case was
255  //
256  // echo 20.001 0 20.001 0 | GeodSolve -i
257  //
258  // In fact, we will have sig12 > pi/2 for meridional geodesic which is
259  // not a shortest path.
260  if (sig12 < 1 || m12x >= 0) {
261  m12x *= _b;
262  s12x *= _b;
263  a12 = sig12 / Math::degree();
264  } else
265  // m12 < 0, i.e., prolate and too close to anti-podal
266  meridian = false;
267  }
268 
269  real omg12 = 0; // initial value to suppress warning
270  if (!meridian &&
271  sbet1 == 0 && // and sbet2 == 0
272  // Mimic the way Lambda12 works with calp1 = 0
273  (_f <= 0 || lam12 <= Math::pi() - _f * Math::pi())) {
274 
275  // Geodesic runs along equator
276  calp1 = calp2 = 0; salp1 = salp2 = 1;
277  s12x = _a * lam12;
278  sig12 = omg12 = lam12 / _f1;
279  m12x = _b * sin(sig12);
280  if (outmask & GEODESICSCALE)
281  M12 = M21 = cos(sig12);
282  a12 = lon12 / _f1;
283 
284  } else if (!meridian) {
285 
286  // Now point1 and point2 belong within a hemisphere bounded by a
287  // meridian and geodesic is neither meridional or equatorial.
288 
289  // Figure a starting point for Newton's method
290  real dnm;
291  sig12 = InverseStart(E, sbet1, cbet1, dn1, sbet2, cbet2, dn2,
292  lam12,
293  salp1, calp1, salp2, calp2, dnm);
294 
295  if (sig12 >= 0) {
296  // Short lines (InverseStart sets salp2, calp2, dnm)
297  s12x = sig12 * _b * dnm;
298  m12x = Math::sq(dnm) * _b * sin(sig12 / dnm);
299  if (outmask & GEODESICSCALE)
300  M12 = M21 = cos(sig12 / dnm);
301  a12 = sig12 / Math::degree();
302  omg12 = lam12 / (_f1 * dnm);
303  } else {
304 
305  // Newton's method. This is a straightforward solution of f(alp1) =
306  // lambda12(alp1) - lam12 = 0 with one wrinkle. f(alp) has exactly one
307  // root in the interval (0, pi) and its derivative is positive at the
308  // root. Thus f(alp) is positive for alp > alp1 and negative for alp <
309  // alp1. During the course of the iteration, a range (alp1a, alp1b) is
310  // maintained which brackets the root and with each evaluation of
311  // f(alp) the range is shrunk, if possible. Newton's method is
312  // restarted whenever the derivative of f is negative (because the new
313  // value of alp1 is then further from the solution) or if the new
314  // estimate of alp1 lies outside (0,pi); in this case, the new starting
315  // guess is taken to be (alp1a + alp1b) / 2.
316  //
317  // initial values to suppress warnings (if loop is executed 0 times)
318  real ssig1 = 0, csig1 = 0, ssig2 = 0, csig2 = 0;
319  unsigned numit = 0;
320  // Bracketing range
321  real salp1a = tiny_, calp1a = 1, salp1b = tiny_, calp1b = -1;
322  for (bool tripn = false, tripb = false;
323  numit < maxit2_ || GEOGRAPHICLIB_PANIC;
324  ++numit) {
325  // 1/4 meridan = 10e6 m and random input. max err is estimated max
326  // error in nm (checking solution of inverse problem by direct
327  // solution). iter is mean and sd of number of iterations
328  //
329  // max iter
330  // log2(b/a) err mean sd
331  // -7 387 5.33 3.68
332  // -6 345 5.19 3.43
333  // -5 269 5.00 3.05
334  // -4 210 4.76 2.44
335  // -3 115 4.55 1.87
336  // -2 69 4.35 1.38
337  // -1 36 4.05 1.03
338  // 0 15 0.01 0.13
339  // 1 25 5.10 1.53
340  // 2 96 5.61 2.09
341  // 3 318 6.02 2.74
342  // 4 985 6.24 3.22
343  // 5 2352 6.32 3.44
344  // 6 6008 6.30 3.45
345  // 7 19024 6.19 3.30
346  real dv;
347  real v = Lambda12(sbet1, cbet1, dn1, sbet2, cbet2, dn2, salp1, calp1,
348  salp2, calp2, sig12, ssig1, csig1, ssig2, csig2,
349  E, omg12, numit < maxit1_, dv) - lam12;
350  // 2 * tol0 is approximately 1 ulp for a number in [0, pi].
351  // Reversed test to allow escape with NaNs
352  if (tripb || !(abs(v) >= (tripn ? 8 : 2) * tol0_)) break;
353  // Update bracketing values
354  if (v > 0 && (numit > maxit1_ || calp1/salp1 > calp1b/salp1b))
355  { salp1b = salp1; calp1b = calp1; }
356  else if (v < 0 && (numit > maxit1_ || calp1/salp1 < calp1a/salp1a))
357  { salp1a = salp1; calp1a = calp1; }
358  if (numit < maxit1_ && dv > 0) {
359  real
360  dalp1 = -v/dv;
361  real
362  sdalp1 = sin(dalp1), cdalp1 = cos(dalp1),
363  nsalp1 = salp1 * cdalp1 + calp1 * sdalp1;
364  if (nsalp1 > 0 && abs(dalp1) < Math::pi()) {
365  calp1 = calp1 * cdalp1 - salp1 * sdalp1;
366  salp1 = nsalp1;
367  Math::norm(salp1, calp1);
368  // In some regimes we don't get quadratic convergence because
369  // slope -> 0. So use convergence conditions based on epsilon
370  // instead of sqrt(epsilon).
371  tripn = abs(v) <= 16 * tol0_;
372  continue;
373  }
374  }
375  // Either dv was not postive or updated value was outside legal
376  // range. Use the midpoint of the bracket as the next estimate.
377  // This mechanism is not needed for the WGS84 ellipsoid, but it does
378  // catch problems with more eccentric ellipsoids. Its efficacy is
379  // such for the WGS84 test set with the starting guess set to alp1 =
380  // 90deg:
381  // the WGS84 test set: mean = 5.21, sd = 3.93, max = 24
382  // WGS84 and random input: mean = 4.74, sd = 0.99
383  salp1 = (salp1a + salp1b)/2;
384  calp1 = (calp1a + calp1b)/2;
385  Math::norm(salp1, calp1);
386  tripn = false;
387  tripb = (abs(salp1a - salp1) + (calp1a - calp1) < tolb_ ||
388  abs(salp1 - salp1b) + (calp1 - calp1b) < tolb_);
389  }
390  {
391  real dummy;
392  Lengths(E, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2,
393  cbet1, cbet2, s12x, m12x, dummy,
394  (outmask & GEODESICSCALE) != 0U, M12, M21);
395  }
396  m12x *= _b;
397  s12x *= _b;
398  a12 = sig12 / Math::degree();
399  }
400  }
401 
402  if (outmask & DISTANCE)
403  s12 = 0 + s12x; // Convert -0 to 0
404 
405  if (outmask & REDUCEDLENGTH)
406  m12 = 0 + m12x; // Convert -0 to 0
407 
408  if (outmask & AREA) {
409  real
410  // From Lambda12: sin(alp1) * cos(bet1) = sin(alp0)
411  salp0 = salp1 * cbet1,
412  calp0 = Math::hypot(calp1, salp1 * sbet1); // calp0 > 0
413  real alp12;
414  if (calp0 != 0 && salp0 != 0) {
415  real
416  // From Lambda12: tan(bet) = tan(sig) * cos(alp)
417  ssig1 = sbet1, csig1 = calp1 * cbet1,
418  ssig2 = sbet2, csig2 = calp2 * cbet2,
419  k2 = Math::sq(calp0) * _ep2,
420  eps = k2 / (2 * (1 + sqrt(1 + k2)) + k2),
421  // Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0).
422  A4 = Math::sq(_a) * calp0 * salp0 * _e2;
423  Math::norm(ssig1, csig1);
424  Math::norm(ssig2, csig2);
425  real C4a[nC4_];
426  C4f(eps, C4a);
427  real
428  B41 = CosSeries(ssig1, csig1, C4a, nC4_),
429  B42 = CosSeries(ssig2, csig2, C4a, nC4_);
430  S12 = A4 * (B42 - B41);
431  } else
432  // Avoid problems with indeterminate sig1, sig2 on equator
433  S12 = 0;
434 
435  if (!meridian &&
436  omg12 < real(0.75) * Math::pi() && // Long difference too big
437  sbet2 - sbet1 < real(1.75)) { // Lat difference too big
438  // Use tan(Gamma/2) = tan(omg12/2)
439  // * (tan(bet1/2)+tan(bet2/2))/(1+tan(bet1/2)*tan(bet2/2))
440  // with tan(x/2) = sin(x)/(1+cos(x))
441  real
442  somg12 = sin(omg12), domg12 = 1 + cos(omg12),
443  dbet1 = 1 + cbet1, dbet2 = 1 + cbet2;
444  alp12 = 2 * atan2( somg12 * ( sbet1 * dbet2 + sbet2 * dbet1 ),
445  domg12 * ( sbet1 * sbet2 + dbet1 * dbet2 ) );
446  } else {
447  // alp12 = alp2 - alp1, used in atan2 so no need to normalize
448  real
449  salp12 = salp2 * calp1 - calp2 * salp1,
450  calp12 = calp2 * calp1 + salp2 * salp1;
451  // The right thing appears to happen if alp1 = +/-180 and alp2 = 0, viz
452  // salp12 = -0 and alp12 = -180. However this depends on the sign
453  // being attached to 0 correctly. The following ensures the correct
454  // behavior.
455  if (salp12 == 0 && calp12 < 0) {
456  salp12 = tiny_ * calp1;
457  calp12 = -1;
458  }
459  alp12 = atan2(salp12, calp12);
460  }
461  S12 += _c2 * alp12;
462  S12 *= swapp * lonsign * latsign;
463  // Convert -0 to 0
464  S12 += 0;
465  }
466 
467  // Convert calp, salp to azimuth accounting for lonsign, swapp, latsign.
468  if (swapp < 0) {
469  swap(salp1, salp2);
470  swap(calp1, calp2);
471  if (outmask & GEODESICSCALE)
472  swap(M12, M21);
473  }
474 
475  salp1 *= swapp * lonsign; calp1 *= swapp * latsign;
476  salp2 *= swapp * lonsign; calp2 *= swapp * latsign;
477 
478  if (outmask & AZIMUTH) {
479  azi1 = Math::atan2d(salp1, calp1);
480  azi2 = Math::atan2d(salp2, calp2);
481  }
482 
483  // Returned value in [0, 180]
484  return a12;
485  }
486 
487  void GeodesicExact::Lengths(const EllipticFunction& E,
488  real sig12,
489  real ssig1, real csig1, real dn1,
490  real ssig2, real csig2, real dn2,
491  real cbet1, real cbet2,
492  real& s12b, real& m12b, real& m0,
493  bool scalep, real& M12, real& M21) const {
494  // Return m12b = (reduced length)/_b; also calculate s12b = distance/_b,
495  // and m0 = coefficient of secular term in expression for reduced length.
496 
497  // It's OK to have repeated dummy arguments,
498  // e.g., s12b = m0 = M12 = M21 = dummy
499  m0 = - E.k2() * E.D() / (Math::pi() / 2);
500  real J12 = m0 *
501  (sig12 + E.deltaD(ssig2, csig2, dn2) - E.deltaD(ssig1, csig1, dn1));
502  // Missing a factor of _b.
503  // Add parens around (csig1 * ssig2) and (ssig1 * csig2) to ensure accurate
504  // cancellation in the case of coincident points.
505  m12b = dn2 * (csig1 * ssig2) - dn1 * (ssig1 * csig2) - csig1 * csig2 * J12;
506  // Missing a factor of _b
507  s12b = E.E() / (Math::pi() / 2) *
508  (sig12 + E.deltaE(ssig2, csig2, dn2) - E.deltaE(ssig1, csig1, dn1));
509  if (scalep) {
510  real csig12 = csig1 * csig2 + ssig1 * ssig2;
511  real t = _ep2 * (cbet1 - cbet2) * (cbet1 + cbet2) / (dn1 + dn2);
512  M12 = csig12 + (t * ssig2 - csig2 * J12) * ssig1 / dn1;
513  M21 = csig12 - (t * ssig1 - csig1 * J12) * ssig2 / dn2;
514  }
515  }
516 
517  Math::real GeodesicExact::Astroid(real x, real y) {
518  // Solve k^4+2*k^3-(x^2+y^2-1)*k^2-2*y^2*k-y^2 = 0 for positive root k.
519  // This solution is adapted from Geocentric::Reverse.
520  real k;
521  real
522  p = Math::sq(x),
523  q = Math::sq(y),
524  r = (p + q - 1) / 6;
525  if ( !(q == 0 && r <= 0) ) {
526  real
527  // Avoid possible division by zero when r = 0 by multiplying equations
528  // for s and t by r^3 and r, resp.
529  S = p * q / 4, // S = r^3 * s
530  r2 = Math::sq(r),
531  r3 = r * r2,
532  // The discrimant of the quadratic equation for T3. This is zero on
533  // the evolute curve p^(1/3)+q^(1/3) = 1
534  disc = S * (S + 2 * r3);
535  real u = r;
536  if (disc >= 0) {
537  real T3 = S + r3;
538  // Pick the sign on the sqrt to maximize abs(T3). This minimizes loss
539  // of precision due to cancellation. The result is unchanged because
540  // of the way the T is used in definition of u.
541  T3 += T3 < 0 ? -sqrt(disc) : sqrt(disc); // T3 = (r * t)^3
542  // N.B. cbrt always returns the real root. cbrt(-8) = -2.
543  real T = Math::cbrt(T3); // T = r * t
544  // T can be zero; but then r2 / T -> 0.
545  u += T + (T ? r2 / T : 0);
546  } else {
547  // T is complex, but the way u is defined the result is real.
548  real ang = atan2(sqrt(-disc), -(S + r3));
549  // There are three possible cube roots. We choose the root which
550  // avoids cancellation. Note that disc < 0 implies that r < 0.
551  u += 2 * r * cos(ang / 3);
552  }
553  real
554  v = sqrt(Math::sq(u) + q), // guaranteed positive
555  // Avoid loss of accuracy when u < 0.
556  uv = u < 0 ? q / (v - u) : u + v, // u+v, guaranteed positive
557  w = (uv - q) / (2 * v); // positive?
558  // Rearrange expression for k to avoid loss of accuracy due to
559  // subtraction. Division by 0 not possible because uv > 0, w >= 0.
560  k = uv / (sqrt(uv + Math::sq(w)) + w); // guaranteed positive
561  } else { // q == 0 && r <= 0
562  // y = 0 with |x| <= 1. Handle this case directly.
563  // for y small, positive root is k = abs(y)/sqrt(1-x^2)
564  k = 0;
565  }
566  return k;
567  }
568 
569  Math::real GeodesicExact::InverseStart(EllipticFunction& E,
570  real sbet1, real cbet1, real dn1,
571  real sbet2, real cbet2, real dn2,
572  real lam12,
573  real& salp1, real& calp1,
574  // Only updated if return val >= 0
575  real& salp2, real& calp2,
576  // Only updated for short lines
577  real& dnm)
578  const {
579  // Return a starting point for Newton's method in salp1 and calp1 (function
580  // value is -1). If Newton's method doesn't need to be used, return also
581  // salp2 and calp2 and function value is sig12.
582  real
583  sig12 = -1, // Return value
584  // bet12 = bet2 - bet1 in [0, pi); bet12a = bet2 + bet1 in (-pi, 0]
585  sbet12 = sbet2 * cbet1 - cbet2 * sbet1,
586  cbet12 = cbet2 * cbet1 + sbet2 * sbet1;
587 #if defined(__GNUC__) && __GNUC__ == 4 && \
588  (__GNUC_MINOR__ < 6 || defined(__MINGW32__))
589  // Volatile declaration needed to fix inverse cases
590  // 88.202499451857 0 -88.202499451857 179.981022032992859592
591  // 89.262080389218 0 -89.262080389218 179.992207982775375662
592  // 89.333123580033 0 -89.333123580032997687 179.99295812360148422
593  // which otherwise fail with g++ 4.4.4 x86 -O3 (Linux)
594  // and g++ 4.4.0 (mingw) and g++ 4.6.1 (tdm mingw).
595  real sbet12a;
596  {
597  GEOGRAPHICLIB_VOLATILE real xx1 = sbet2 * cbet1;
598  GEOGRAPHICLIB_VOLATILE real xx2 = cbet2 * sbet1;
599  sbet12a = xx1 + xx2;
600  }
601 #else
602  real sbet12a = sbet2 * cbet1 + cbet2 * sbet1;
603 #endif
604  bool shortline = cbet12 >= 0 && sbet12 < real(0.5) &&
605  cbet2 * lam12 < real(0.5);
606  real omg12 = lam12;
607  if (shortline) {
608  real sbetm2 = Math::sq(sbet1 + sbet2);
609  // sin((bet1+bet2)/2)^2
610  // = (sbet1 + sbet2)^2 / ((sbet1 + sbet2)^2 + (cbet1 + cbet2)^2)
611  sbetm2 /= sbetm2 + Math::sq(cbet1 + cbet2);
612  dnm = sqrt(1 + _ep2 * sbetm2);
613  omg12 /= _f1 * dnm;
614  }
615  real somg12 = sin(omg12), comg12 = cos(omg12);
616 
617  salp1 = cbet2 * somg12;
618  calp1 = comg12 >= 0 ?
619  sbet12 + cbet2 * sbet1 * Math::sq(somg12) / (1 + comg12) :
620  sbet12a - cbet2 * sbet1 * Math::sq(somg12) / (1 - comg12);
621 
622  real
623  ssig12 = Math::hypot(salp1, calp1),
624  csig12 = sbet1 * sbet2 + cbet1 * cbet2 * comg12;
625 
626  if (shortline && ssig12 < _etol2) {
627  // really short lines
628  salp2 = cbet1 * somg12;
629  calp2 = sbet12 - cbet1 * sbet2 *
630  (comg12 >= 0 ? Math::sq(somg12) / (1 + comg12) : 1 - comg12);
631  Math::norm(salp2, calp2);
632  // Set return value
633  sig12 = atan2(ssig12, csig12);
634  } else if (abs(_n) > real(0.1) || // Skip astroid calc if too eccentric
635  csig12 >= 0 ||
636  ssig12 >= 6 * abs(_n) * Math::pi() * Math::sq(cbet1)) {
637  // Nothing to do, zeroth order spherical approximation is OK
638  } else {
639  // Scale lam12 and bet2 to x, y coordinate system where antipodal point
640  // is at origin and singular point is at y = 0, x = -1.
641  real y, lamscale, betscale;
642  // Volatile declaration needed to fix inverse case
643  // 56.320923501171 0 -56.320923501171 179.664747671772880215
644  // which otherwise fails with g++ 4.4.4 x86 -O3
646  if (_f >= 0) { // In fact f == 0 does not get here
647  // x = dlong, y = dlat
648  {
649  real k2 = Math::sq(sbet1) * _ep2;
650  E.Reset(-k2, -_ep2, 1 + k2, 1 + _ep2);
651  lamscale = _e2/_f1 * cbet1 * 2 * E.H();
652  }
653  betscale = lamscale * cbet1;
654 
655  x = (lam12 - Math::pi()) / lamscale;
656  y = sbet12a / betscale;
657  } else { // _f < 0
658  // x = dlat, y = dlong
659  real
660  cbet12a = cbet2 * cbet1 - sbet2 * sbet1,
661  bet12a = atan2(sbet12a, cbet12a);
662  real m12b, m0, dummy;
663  // In the case of lon12 = 180, this repeats a calculation made in
664  // Inverse.
665  Lengths(E, Math::pi() + bet12a,
666  sbet1, -cbet1, dn1, sbet2, cbet2, dn2,
667  cbet1, cbet2, dummy, m12b, m0, false,
668  dummy, dummy);
669  x = -1 + m12b / (cbet1 * cbet2 * m0 * Math::pi());
670  betscale = x < -real(0.01) ? sbet12a / x :
671  -_f * Math::sq(cbet1) * Math::pi();
672  lamscale = betscale / cbet1;
673  y = (lam12 - Math::pi()) / lamscale;
674  }
675 
676  if (y > -tol1_ && x > -1 - xthresh_) {
677  // strip near cut
678  // Need real(x) here to cast away the volatility of x for min/max
679  if (_f >= 0) {
680  salp1 = min(real(1), -real(x)); calp1 = - sqrt(1 - Math::sq(salp1));
681  } else {
682  calp1 = max(real(x > -tol1_ ? 0 : -1), real(x));
683  salp1 = sqrt(1 - Math::sq(calp1));
684  }
685  } else {
686  // Estimate alp1, by solving the astroid problem.
687  //
688  // Could estimate alpha1 = theta + pi/2, directly, i.e.,
689  // calp1 = y/k; salp1 = -x/(1+k); for _f >= 0
690  // calp1 = x/(1+k); salp1 = -y/k; for _f < 0 (need to check)
691  //
692  // However, it's better to estimate omg12 from astroid and use
693  // spherical formula to compute alp1. This reduces the mean number of
694  // Newton iterations for astroid cases from 2.24 (min 0, max 6) to 2.12
695  // (min 0 max 5). The changes in the number of iterations are as
696  // follows:
697  //
698  // change percent
699  // 1 5
700  // 0 78
701  // -1 16
702  // -2 0.6
703  // -3 0.04
704  // -4 0.002
705  //
706  // The histogram of iterations is (m = number of iterations estimating
707  // alp1 directly, n = number of iterations estimating via omg12, total
708  // number of trials = 148605):
709  //
710  // iter m n
711  // 0 148 186
712  // 1 13046 13845
713  // 2 93315 102225
714  // 3 36189 32341
715  // 4 5396 7
716  // 5 455 1
717  // 6 56 0
718  //
719  // Because omg12 is near pi, estimate work with omg12a = pi - omg12
720  real k = Astroid(x, y);
721  real
722  omg12a = lamscale * ( _f >= 0 ? -x * k/(1 + k) : -y * (1 + k)/k );
723  somg12 = sin(omg12a); comg12 = -cos(omg12a);
724  // Update spherical estimate of alp1 using omg12 instead of lam12
725  salp1 = cbet2 * somg12;
726  calp1 = sbet12a - cbet2 * sbet1 * Math::sq(somg12) / (1 - comg12);
727  }
728  }
729  // Sanity check on starting guess. Backwards check allows NaN through.
730  if (!(salp1 <= 0))
731  Math::norm(salp1, calp1);
732  else {
733  salp1 = 1; calp1 = 0;
734  }
735  return sig12;
736  }
737 
738  Math::real GeodesicExact::Lambda12(real sbet1, real cbet1, real dn1,
739  real sbet2, real cbet2, real dn2,
740  real salp1, real calp1,
741  real& salp2, real& calp2,
742  real& sig12,
743  real& ssig1, real& csig1,
744  real& ssig2, real& csig2,
745  EllipticFunction& E,
746  real& omg12,
747  bool diffp, real& dlam12) const
748  {
749 
750  if (sbet1 == 0 && calp1 == 0)
751  // Break degeneracy of equatorial line. This case has already been
752  // handled.
753  calp1 = -tiny_;
754 
755  real
756  // sin(alp1) * cos(bet1) = sin(alp0)
757  salp0 = salp1 * cbet1,
758  calp0 = Math::hypot(calp1, salp1 * sbet1); // calp0 > 0
759 
760  real somg1, comg1, somg2, comg2, cchi1, cchi2, lam12;
761  // tan(bet1) = tan(sig1) * cos(alp1)
762  // tan(omg1) = sin(alp0) * tan(sig1) = tan(omg1)=tan(alp1)*sin(bet1)
763  ssig1 = sbet1; somg1 = salp0 * sbet1;
764  csig1 = comg1 = calp1 * cbet1;
765  // Without normalization we have schi1 = somg1.
766  cchi1 = _f1 * dn1 * comg1;
767  Math::norm(ssig1, csig1);
768  // Math::norm(somg1, comg1); -- don't need to normalize!
769  // Math::norm(schi1, cchi1); -- don't need to normalize!
770 
771  // Enforce symmetries in the case abs(bet2) = -bet1. Need to be careful
772  // about this case, since this can yield singularities in the Newton
773  // iteration.
774  // sin(alp2) * cos(bet2) = sin(alp0)
775  salp2 = cbet2 != cbet1 ? salp0 / cbet2 : salp1;
776  // calp2 = sqrt(1 - sq(salp2))
777  // = sqrt(sq(calp0) - sq(sbet2)) / cbet2
778  // and subst for calp0 and rearrange to give (choose positive sqrt
779  // to give alp2 in [0, pi/2]).
780  calp2 = cbet2 != cbet1 || abs(sbet2) != -sbet1 ?
781  sqrt(Math::sq(calp1 * cbet1) +
782  (cbet1 < -sbet1 ?
783  (cbet2 - cbet1) * (cbet1 + cbet2) :
784  (sbet1 - sbet2) * (sbet1 + sbet2))) / cbet2 :
785  abs(calp1);
786  // tan(bet2) = tan(sig2) * cos(alp2)
787  // tan(omg2) = sin(alp0) * tan(sig2).
788  ssig2 = sbet2; somg2 = salp0 * sbet2;
789  csig2 = comg2 = calp2 * cbet2;
790  // Without normalization we have schi2 = somg2.
791  cchi2 = _f1 * dn2 * comg2;
792  Math::norm(ssig2, csig2);
793  // Math::norm(somg2, comg2); -- don't need to normalize!
794  // Math::norm(schi2, cchi2); -- don't need to normalize!
795 
796  // sig12 = sig2 - sig1, limit to [0, pi]
797  sig12 = atan2(max(csig1 * ssig2 - ssig1 * csig2, real(0)),
798  csig1 * csig2 + ssig1 * ssig2);
799 
800  // omg12 = omg2 - omg1, limit to [0, pi]
801  omg12 = atan2(max(comg1 * somg2 - somg1 * comg2, real(0)),
802  comg1 * comg2 + somg1 * somg2);
803  real k2 = Math::sq(calp0) * _ep2;
804  E.Reset(-k2, -_ep2, 1 + k2, 1 + _ep2);
805  real chi12 = atan2(max(cchi1 * somg2 - somg1 * cchi2, real(0)),
806  cchi1 * cchi2 + somg1 * somg2);
807  lam12 = chi12 -
808  _e2/_f1 * salp0 * E.H() / (Math::pi() / 2) *
809  (sig12 + E.deltaH(ssig2, csig2, dn2) - E.deltaH(ssig1, csig1, dn1) );
810 
811  if (diffp) {
812  if (calp2 == 0)
813  dlam12 = - 2 * _f1 * dn1 / sbet1;
814  else {
815  real dummy;
816  Lengths(E, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2,
817  cbet1, cbet2, dummy, dlam12, dummy,
818  false, dummy, dummy);
819  dlam12 *= _f1 / (calp2 * cbet2);
820  }
821  }
822 
823  return lam12;
824  }
825 
826  void GeodesicExact::C4f(real eps, real c[]) const {
827  // Evaluate C4 coeffs
828  // Elements c[0] thru c[nC4_ - 1] are set
829  real mult = 1;
830  int o = 0;
831  for (int l = 0; l < nC4_; ++l) { // l is index of C4[l]
832  int m = nC4_ - l - 1; // order of polynomial in eps
833  c[l] = mult * Math::polyval(m, _C4x + o, eps);
834  o += m + 1;
835  mult *= eps;
836  }
837  // Post condition: o == nC4x_
838  if (!(o == nC4x_))
839  throw GeographicErr("C4 misalignment");
840  }
841 
842 } // namespace GeographicLib
static T AngNormalize(T x)
Definition: Math.hpp:445
static T pi()
Definition: Math.hpp:214
GeographicLib::Math::real real
Definition: GeodSolve.cpp:32
static T cbrt(T x)
Definition: Math.hpp:357
static bool isfinite(T x)
Definition: Math.hpp:614
Mathematical functions needed by GeographicLib.
Definition: Math.hpp:102
Elliptic integrals and functions.
static void norm(T &x, T &y)
Definition: Math.hpp:392
#define GEOGRAPHICLIB_VOLATILE
Definition: Math.hpp:84
Math::real GenInverse(real lat1, real lon1, real lat2, real lon2, unsigned outmask, real &s12, real &azi1, real &azi2, real &m12, real &M12, real &M21, real &S12) const
static T hypot(T x, T y)
Definition: Math.hpp:255
static T sq(T x)
Definition: Math.hpp:244
GeodesicLineExact Line(real lat1, real lon1, real azi1, unsigned caps=ALL) const
Header for GeographicLib::GeodesicLineExact class.
static T atan2d(T y, T x)
Definition: Math.hpp:551
static T polyval(int N, const T p[], T x)
Definition: Math.hpp:433
Namespace for GeographicLib.
Definition: Accumulator.cpp:12
static T degree()
Definition: Math.hpp:228
static T AngDiff(T x, T y)
Definition: Math.hpp:475
Math::real GenDirect(real lat1, real lon1, real azi1, bool arcmode, real s12_a12, unsigned outmask, real &lat2, real &lon2, real &azi2, real &s12, real &m12, real &M12, real &M21, real &S12) const
Exact geodesic calculations.
Math::real deltaE(real sn, real cn, real dn) const
Header for GeographicLib::GeodesicExact class.
Exception handling for GeographicLib.
Definition: Constants.hpp:382
static T AngRound(T x)
Definition: Math.hpp:498
Math::real deltaD(real sn, real cn, real dn) const
#define GEOGRAPHICLIB_PANIC
Definition: Math.hpp:87
static const GeodesicExact & WGS84()