GeographicLib: Math.hpp Source File

GeographicLib 2.5

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