GeographicLib  2.0
Math.hpp
Go to the documentation of this file.
1 /**
2  * \file Math.hpp
3  * \brief Header for GeographicLib::Math class
4  *
5  * Copyright (c) Charles Karney (2008-2022) <charles@karney.com> and licensed
6  * under the MIT/X11 License. For more information, see
7  * https://geographiclib.sourceforge.io/
8  **********************************************************************/
9 
10 // Constants.hpp includes Math.hpp. Place this include outside Math.hpp's
11 // include guard to enforce this ordering.
13 
14 #if !defined(GEOGRAPHICLIB_MATH_HPP)
15 #define GEOGRAPHICLIB_MATH_HPP 1
16 
17 #if !defined(GEOGRAPHICLIB_WORDS_BIGENDIAN)
18 # define GEOGRAPHICLIB_WORDS_BIGENDIAN 0
19 #endif
20 
21 #if !defined(GEOGRAPHICLIB_HAVE_LONG_DOUBLE)
22 # define GEOGRAPHICLIB_HAVE_LONG_DOUBLE 0
23 #endif
24 
25 #if !defined(GEOGRAPHICLIB_PRECISION)
26 /**
27  * The precision of floating point numbers used in %GeographicLib. 1 means
28  * float (single precision); 2 (the default) means double; 3 means long double;
29  * 4 is reserved for quadruple precision. Nearly all the testing has been
30  * carried out with doubles and that's the recommended configuration. In order
31  * for long double to be used, GEOGRAPHICLIB_HAVE_LONG_DOUBLE needs to be
32  * defined. Note that with Microsoft Visual Studio, long double is the same as
33  * double.
34  **********************************************************************/
35 # define GEOGRAPHICLIB_PRECISION 2
36 #endif
37 
38 #include <cmath>
39 #include <algorithm>
40 #include <limits>
41 
42 #if GEOGRAPHICLIB_PRECISION == 4
43 #include <boost/version.hpp>
44 #include <boost/multiprecision/float128.hpp>
45 #include <boost/math/special_functions.hpp>
46 #elif GEOGRAPHICLIB_PRECISION == 5
47 #include <mpreal.h>
48 #endif
49 
50 #if GEOGRAPHICLIB_PRECISION > 3
51 // volatile keyword makes no sense for multiprec types
52 #define GEOGRAPHICLIB_VOLATILE
53 // Signal a convergence failure with multiprec types by throwing an exception
54 // at loop exit.
55 #define GEOGRAPHICLIB_PANIC \
56  (throw GeographicLib::GeographicErr("Convergence failure"), false)
57 #else
58 #define GEOGRAPHICLIB_VOLATILE volatile
59 // Ignore convergence failures with standard floating points types by allowing
60 // loop to exit cleanly.
61 #define GEOGRAPHICLIB_PANIC false
62 #endif
63 
64 namespace GeographicLib {
65 
66  /**
67  * \brief Mathematical functions needed by %GeographicLib
68  *
69  * Define mathematical functions in order to localize system dependencies and
70  * to provide generic versions of the functions. In addition define a real
71  * type to be used by %GeographicLib.
72  *
73  * Example of use:
74  * \include example-Math.cpp
75  **********************************************************************/
77  private:
78  void dummy(); // Static check for GEOGRAPHICLIB_PRECISION
79  Math() = delete; // Disable constructor
80  public:
81 
82 #if GEOGRAPHICLIB_HAVE_LONG_DOUBLE
83  /**
84  * The extended precision type for real numbers, used for some testing.
85  * This is long double on computers with this type; otherwise it is double.
86  **********************************************************************/
87  typedef long double extended;
88 #else
89  typedef double extended;
90 #endif
91 
92 #if GEOGRAPHICLIB_PRECISION == 2
93  /**
94  * The real type for %GeographicLib. Nearly all the testing has been done
95  * with \e real = double. However, the algorithms should also work with
96  * float and long double (where available). (<b>CAUTION</b>: reasonable
97  * accuracy typically cannot be obtained using floats.)
98  **********************************************************************/
99  typedef double real;
100 #elif GEOGRAPHICLIB_PRECISION == 1
101  typedef float real;
102 #elif GEOGRAPHICLIB_PRECISION == 3
103  typedef extended real;
104 #elif GEOGRAPHICLIB_PRECISION == 4
105  typedef boost::multiprecision::float128 real;
106 #elif GEOGRAPHICLIB_PRECISION == 5
107  typedef mpfr::mpreal real;
108 #else
109  typedef double real;
110 #endif
111 
112  /**
113  * The constants defining the meaning of degrees, minutes, and seconds, for
114  * angles. Read the
115  * constants as follows (for example): \e ms = 60 is the ratio 1 minute / 1
116  * second. The abbreviations are
117  * - \e t a whole turn (360&deg;)
118  * - \e h a half turn (180&deg;)
119  * - \e q a quarter turn (a right angle = 90&deg;)
120  * - \e d a degree
121  * - \e m a minute
122  * - \e s a second
123  * .
124  * Note that degree() is ratio 1 degree / 1 radian, thus, for example,
125  * Math::degree() * Math::qd is the ratio 1 quarter turn / 1 radian =
126  * &pi;/2.
127  *
128  * Defining all these in one place would mean that it's simple to convert
129  * to the centesimal system for measuring angles. The DMS class assumes
130  * that Math::dm and Math::ms are less than or equal to 100 (so that two
131  * digits suffice for the integer parts of the minutes and degrees
132  * components of an angle). Switching to the centesimal convention will
133  * break most of the tests. Also the normal degree definition is baked
134  * into some classes, e.g., UTMUPS, MGRS, Georef, Geohash, etc.
135  **********************************************************************/
136 #if GEOGRAPHICLIB_PRECISION == 4
137  static const int
138 #else
139  enum dms {
140 #endif
141  qd = 90, ///< degrees per quarter turn
142  dm = 60, ///< minutes per degree
143  ms = 60, ///< seconds per minute
144  hd = 2 * qd, ///< degrees per half turn
145  td = 2 * hd, ///< degrees per turn
146  ds = dm * ms ///< seconds per degree
147 #if GEOGRAPHICLIB_PRECISION == 4
148  ;
149 #else
150  };
151 #endif
152 
153  /**
154  * @return the number of bits of precision in a real number.
155  **********************************************************************/
156  static int digits();
157 
158  /**
159  * Set the binary precision of a real number.
160  *
161  * @param[in] ndigits the number of bits of precision.
162  * @return the resulting number of bits of precision.
163  *
164  * This only has an effect when GEOGRAPHICLIB_PRECISION = 5. See also
165  * Utility::set_digits for caveats about when this routine should be
166  * called.
167  **********************************************************************/
168  static int set_digits(int ndigits);
169 
170  /**
171  * @return the number of decimal digits of precision in a real number.
172  **********************************************************************/
173  static int digits10();
174 
175  /**
176  * Number of additional decimal digits of precision for real relative to
177  * double (0 for float).
178  **********************************************************************/
179  static int extra_digits();
180 
181  /**
182  * true if the machine is big-endian.
183  **********************************************************************/
184  static const bool bigendian = GEOGRAPHICLIB_WORDS_BIGENDIAN;
185 
186  /**
187  * @tparam T the type of the returned value.
188  * @return &pi;.
189  **********************************************************************/
190  template<typename T = real> static T pi() {
191  using std::atan2;
192  static const T pi = atan2(T(0), T(-1));
193  return pi;
194  }
195 
196  /**
197  * @tparam T the type of the returned value.
198  * @return the number of radians in a degree.
199  **********************************************************************/
200  template<typename T = real> static T degree() {
201  static const T degree = pi<T>() / hd;
202  return degree;
203  }
204 
205  /**
206  * Square a number.
207  *
208  * @tparam T the type of the argument and the returned value.
209  * @param[in] x
210  * @return <i>x</i><sup>2</sup>.
211  **********************************************************************/
212  template<typename T> static T sq(T x)
213  { return x * x; }
214 
215  /**
216  * Normalize a two-vector.
217  *
218  * @tparam T the type of the argument and the returned value.
219  * @param[in,out] x on output set to <i>x</i>/hypot(<i>x</i>, <i>y</i>).
220  * @param[in,out] y on output set to <i>y</i>/hypot(<i>x</i>, <i>y</i>).
221  **********************************************************************/
222  template<typename T> static void norm(T& x, T& y) {
223 #if defined(_MSC_VER) && defined(_M_IX86)
224  // hypot for Visual Studio (A=win32) fails monotonicity, e.g., with
225  // x = 0.6102683302836215
226  // y1 = 0.7906090004346522
227  // y2 = y1 + 1e-16
228  // the test
229  // hypot(x, y2) >= hypot(x, y1)
230  // fails. Reported 2021-03-14:
231  // https://developercommunity.visualstudio.com/t/1369259
232  // See also:
233  // https://bugs.python.org/issue43088
234  using std::sqrt; T h = sqrt(x * x + y * y);
235 #else
236  using std::hypot; T h = hypot(x, y);
237 #endif
238  x /= h; y /= h;
239  }
240 
241  /**
242  * The error-free sum of two numbers.
243  *
244  * @tparam T the type of the argument and the returned value.
245  * @param[in] u
246  * @param[in] v
247  * @param[out] t the exact error given by (\e u + \e v) - \e s.
248  * @return \e s = round(\e u + \e v).
249  *
250  * See D. E. Knuth, TAOCP, Vol 2, 4.2.2, Theorem B.
251  *
252  * \note \e t can be the same as one of the first two arguments.
253  **********************************************************************/
254  template<typename T> static T sum(T u, T v, T& t);
255 
256  /**
257  * Evaluate a polynomial.
258  *
259  * @tparam T the type of the arguments and returned value.
260  * @param[in] N the order of the polynomial.
261  * @param[in] p the coefficient array (of size \e N + 1).
262  * @param[in] x the variable.
263  * @return the value of the polynomial.
264  *
265  * Evaluate <i>y</i> = &sum;<sub><i>n</i>=0..<i>N</i></sub>
266  * <i>p</i><sub><i>n</i></sub> <i>x</i><sup><i>N</i>&minus;<i>n</i></sup>.
267  * Return 0 if \e N &lt; 0. Return <i>p</i><sub>0</sub>, if \e N = 0 (even
268  * if \e x is infinite or a nan). The evaluation uses Horner's method.
269  **********************************************************************/
270  template<typename T> static T polyval(int N, const T p[], T x) {
271  // This used to employ Math::fma; but that's too slow and it seemed not to
272  // improve the accuracy noticeably. This might change when there's direct
273  // hardware support for fma.
274  T y = N < 0 ? 0 : *p++;
275  while (--N >= 0) y = y * x + *p++;
276  return y;
277  }
278 
279  /**
280  * Normalize an angle.
281  *
282  * @tparam T the type of the argument and returned value.
283  * @param[in] x the angle in degrees.
284  * @return the angle reduced to the range [&minus;180&deg;, 180&deg;].
285  *
286  * The range of \e x is unrestricted. If the result is &plusmn;0&deg; or
287  * &plusmn;180&deg; then the sign is the sign of \e x.
288  **********************************************************************/
289  template<typename T> static T AngNormalize(T x);
290 
291  /**
292  * Normalize a latitude.
293  *
294  * @tparam T the type of the argument and returned value.
295  * @param[in] x the angle in degrees.
296  * @return x if it is in the range [&minus;90&deg;, 90&deg;], otherwise
297  * return NaN.
298  **********************************************************************/
299  template<typename T> static T LatFix(T x)
300  { using std::fabs; return fabs(x) > qd ? NaN<T>() : x; }
301 
302  /**
303  * The exact difference of two angles reduced to
304  * [&minus;180&deg;, 180&deg;].
305  *
306  * @tparam T the type of the arguments and returned value.
307  * @param[in] x the first angle in degrees.
308  * @param[in] y the second angle in degrees.
309  * @param[out] e the error term in degrees.
310  * @return \e d, the truncated value of \e y &minus; \e x.
311  *
312  * This computes \e z = \e y &minus; \e x exactly, reduced to
313  * [&minus;180&deg;, 180&deg;]; and then sets \e z = \e d + \e e where \e d
314  * is the nearest representable number to \e z and \e e is the truncation
315  * error. If \e z = &plusmn;0&deg; or &plusmn;180&deg;, then the sign of
316  * \e d is given by the sign of \e y &minus; \e x. The maximum absolute
317  * value of \e e is 2<sup>&minus;26</sup> (for doubles).
318  **********************************************************************/
319  template<typename T> static T AngDiff(T x, T y, T& e);
320 
321  /**
322  * Difference of two angles reduced to [&minus;180&deg;, 180&deg;]
323  *
324  * @tparam T the type of the arguments and returned value.
325  * @param[in] x the first angle in degrees.
326  * @param[in] y the second angle in degrees.
327  * @return \e y &minus; \e x, reduced to the range [&minus;180&deg;,
328  * 180&deg;].
329  *
330  * The result is equivalent to computing the difference exactly, reducing
331  * it to [&minus;180&deg;, 180&deg;] and rounding the result.
332  **********************************************************************/
333  template<typename T> static T AngDiff(T x, T y)
334  { T e; return AngDiff(x, y, e); }
335 
336  /**
337  * Coarsen a value close to zero.
338  *
339  * @tparam T the type of the argument and returned value.
340  * @param[in] x
341  * @return the coarsened value.
342  *
343  * The makes the smallest gap in \e x = 1/16 &minus; nextafter(1/16, 0) =
344  * 1/2<sup>57</sup> for doubles = 0.8 pm on the earth if \e x is an angle
345  * in degrees. (This is about 2000 times more resolution than we get with
346  * angles around 90&deg;.) We use this to avoid having to deal with near
347  * singular cases when \e x is non-zero but tiny (e.g.,
348  * 10<sup>&minus;200</sup>). This sign of &plusmn;0 is preserved.
349  **********************************************************************/
350  template<typename T> static T AngRound(T x);
351 
352  /**
353  * Evaluate the sine and cosine function with the argument in degrees
354  *
355  * @tparam T the type of the arguments.
356  * @param[in] x in degrees.
357  * @param[out] sinx sin(<i>x</i>).
358  * @param[out] cosx cos(<i>x</i>).
359  *
360  * The results obey exactly the elementary properties of the trigonometric
361  * functions, e.g., sin 9&deg; = cos 81&deg; = &minus; sin 123456789&deg;.
362  * If x = &minus;0 or a negative multiple of 180&deg;, then \e sinx =
363  * &minus;0; this is the only case where &minus;0 is returned.
364  **********************************************************************/
365  template<typename T> static void sincosd(T x, T& sinx, T& cosx);
366 
367  /**
368  * Evaluate the sine and cosine with reduced argument plus correction
369  *
370  * @tparam T the type of the arguments.
371  * @param[in] x reduced angle in degrees.
372  * @param[in] t correction in degrees.
373  * @param[out] sinx sin(<i>x</i> + <i>t</i>).
374  * @param[out] cosx cos(<i>x</i> + <i>t</i>).
375  *
376  * This is a variant of Math::sincosd allowing a correction to the angle to
377  * be supplied. \e x must be in [&minus;180&deg;, 180&deg;] and \e t is
378  * assumed to be a <i>small</i> correction. Math::AngRound is applied to
379  * the reduced angle to prevent problems with \e x + \e t being extremely
380  * close but not exactly equal to one of the four cardinal directions.
381  **********************************************************************/
382  template<typename T> static void sincosde(T x, T t, T& sinx, T& cosx);
383 
384  /**
385  * Evaluate the sine function with the argument in degrees
386  *
387  * @tparam T the type of the argument and the returned value.
388  * @param[in] x in degrees.
389  * @return sin(<i>x</i>).
390  *
391  * The result is +0 for \e x = +0 and positive multiples of 180&deg;. The
392  * result is &minus;0 for \e x = -0 and negative multiples of 180&deg;.
393  **********************************************************************/
394  template<typename T> static T sind(T x);
395 
396  /**
397  * Evaluate the cosine function with the argument in degrees
398  *
399  * @tparam T the type of the argument and the returned value.
400  * @param[in] x in degrees.
401  * @return cos(<i>x</i>).
402  *
403  * The result is +0 for \e x an odd multiple of 90&deg;.
404  **********************************************************************/
405  template<typename T> static T cosd(T x);
406 
407  /**
408  * Evaluate the tangent function with the argument in degrees
409  *
410  * @tparam T the type of the argument and the returned value.
411  * @param[in] x in degrees.
412  * @return tan(<i>x</i>).
413  *
414  * If \e x is an odd multiple of 90&deg;, then a suitably large (but
415  * finite) value is returned.
416  **********************************************************************/
417  template<typename T> static T tand(T x);
418 
419  /**
420  * Evaluate the atan2 function with the result in degrees
421  *
422  * @tparam T the type of the arguments and the returned value.
423  * @param[in] y
424  * @param[in] x
425  * @return atan2(<i>y</i>, <i>x</i>) in degrees.
426  *
427  * The result is in the range [&minus;180&deg; 180&deg;]. N.B.,
428  * atan2d(&plusmn;0, &minus;1) = &plusmn;180&deg;.
429  **********************************************************************/
430  template<typename T> static T atan2d(T y, T x);
431 
432  /**
433  * Evaluate the atan function with the result in degrees
434  *
435  * @tparam T the type of the argument and the returned value.
436  * @param[in] x
437  * @return atan(<i>x</i>) in degrees.
438  **********************************************************************/
439  template<typename T> static T atand(T x);
440 
441  /**
442  * Evaluate <i>e</i> atanh(<i>e x</i>)
443  *
444  * @tparam T the type of the argument and the returned value.
445  * @param[in] x
446  * @param[in] es the signed eccentricity = sign(<i>e</i><sup>2</sup>)
447  * sqrt(|<i>e</i><sup>2</sup>|)
448  * @return <i>e</i> atanh(<i>e x</i>)
449  *
450  * If <i>e</i><sup>2</sup> is negative (<i>e</i> is imaginary), the
451  * expression is evaluated in terms of atan.
452  **********************************************************************/
453  template<typename T> static T eatanhe(T x, T es);
454 
455  /**
456  * tan&chi; in terms of tan&phi;
457  *
458  * @tparam T the type of the argument and the returned value.
459  * @param[in] tau &tau; = tan&phi;
460  * @param[in] es the signed eccentricity = sign(<i>e</i><sup>2</sup>)
461  * sqrt(|<i>e</i><sup>2</sup>|)
462  * @return &tau;&prime; = tan&chi;
463  *
464  * See Eqs. (7--9) of
465  * C. F. F. Karney,
466  * <a href="https://doi.org/10.1007/s00190-011-0445-3">
467  * Transverse Mercator with an accuracy of a few nanometers,</a>
468  * J. Geodesy 85(8), 475--485 (Aug. 2011)
469  * (preprint
470  * <a href="https://arxiv.org/abs/1002.1417">arXiv:1002.1417</a>).
471  **********************************************************************/
472  template<typename T> static T taupf(T tau, T es);
473 
474  /**
475  * tan&phi; in terms of tan&chi;
476  *
477  * @tparam T the type of the argument and the returned value.
478  * @param[in] taup &tau;&prime; = tan&chi;
479  * @param[in] es the signed eccentricity = sign(<i>e</i><sup>2</sup>)
480  * sqrt(|<i>e</i><sup>2</sup>|)
481  * @return &tau; = tan&phi;
482  *
483  * See Eqs. (19--21) of
484  * C. F. F. Karney,
485  * <a href="https://doi.org/10.1007/s00190-011-0445-3">
486  * Transverse Mercator with an accuracy of a few nanometers,</a>
487  * J. Geodesy 85(8), 475--485 (Aug. 2011)
488  * (preprint
489  * <a href="https://arxiv.org/abs/1002.1417">arXiv:1002.1417</a>).
490  **********************************************************************/
491  template<typename T> static T tauf(T taup, T es);
492 
493  /**
494  * The NaN (not a number)
495  *
496  * @tparam T the type of the returned value.
497  * @return NaN if available, otherwise return the max real of type T.
498  **********************************************************************/
499  template<typename T = real> static T NaN();
500 
501  /**
502  * Infinity
503  *
504  * @tparam T the type of the returned value.
505  * @return infinity if available, otherwise return the max real.
506  **********************************************************************/
507  template<typename T = real> static T infinity();
508 
509  /**
510  * Swap the bytes of a quantity
511  *
512  * @tparam T the type of the argument and the returned value.
513  * @param[in] x
514  * @return x with its bytes swapped.
515  **********************************************************************/
516  template<typename T> static T swab(T x) {
517  union {
518  T r;
519  unsigned char c[sizeof(T)];
520  } b;
521  b.r = x;
522  for (int i = sizeof(T)/2; i--; )
523  std::swap(b.c[i], b.c[sizeof(T) - 1 - i]);
524  return b.r;
525  }
526 
527  };
528 
529 } // namespace GeographicLib
530 
531 #endif // GEOGRAPHICLIB_MATH_HPP
Header for GeographicLib::Constants class.
#define GEOGRAPHICLIB_EXPORT
Definition: Constants.hpp:67
GeographicLib::Math::real real
Definition: GeodSolve.cpp:31
#define GEOGRAPHICLIB_WORDS_BIGENDIAN
Definition: Math.hpp:18
Mathematical functions needed by GeographicLib.
Definition: Math.hpp:76
static T degree()
Definition: Math.hpp:200
static T LatFix(T x)
Definition: Math.hpp:299
double extended
Definition: Math.hpp:89
static void norm(T &x, T &y)
Definition: Math.hpp:222
static T sq(T x)
Definition: Math.hpp:212
static T pi()
Definition: Math.hpp:190
static T polyval(int N, const T p[], T x)
Definition: Math.hpp:270
static T AngDiff(T x, T y)
Definition: Math.hpp:333
static T swab(T x)
Definition: Math.hpp:516
Namespace for GeographicLib.
Definition: Accumulator.cpp:12
void swap(GeographicLib::NearestNeighbor< dist_t, pos_t, distfun_t > &a, GeographicLib::NearestNeighbor< dist_t, pos_t, distfun_t > &b)