Coverage for pygeodesy/fmath.py: 93%
276 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-04-04 14:33 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-04-04 14:33 -0400
2# -*- coding: utf-8 -*-
4u'''Utilities using precision floating point summation.
5'''
6# make sure int/int division yields float quotient, see .basics
7from __future__ import division as _; del _ # PYCHOK semicolon
9from pygeodesy.basics import _copysign, copysign0, isint, len2
10from pygeodesy.constants import EPS0, EPS02, EPS1, NAN, PI, PI_2, PI_4, \
11 _0_0, _0_125, _0_25, _0_5, _1_0, _1_3rd, \
12 _1_5, _1_6th, _2_0, _2_3rd, _3_0, \
13 _copysign_0_0, _isfinite, _over, remainder
14from pygeodesy.errors import _IsnotError, LenError, _TypeError, _ValueError, \
15 _xError, _xkwds_get, _xkwds_pop2
16from pygeodesy.fsums import _2float, Fsum, _fsum, fsum, fsum1_, _pow_op_, \
17 _1primed, Fmt, unstr
18from pygeodesy.interns import MISSING, _few_, _h_, _invokation_, _negative_, \
19 _not_scalar_, _SPACE_, _too_
20from pygeodesy.lazily import _ALL_LAZY, _sys_version_info2
21# from pygeodesy.streprs import Fmt, unstr # from .fsums
22from pygeodesy.units import Int_, _isHeight, _isRadius, Float_ # PYCHOK for .heights
24from math import fabs, sqrt # pow
25import operator as _operator # in .datums, .trf, .utm
27__all__ = _ALL_LAZY.fmath
28__version__ = '24.04.04'
30# sqrt(2) <https://WikiPedia.org/wiki/Square_root_of_2>
31_0_4142 = 0.41421356237309504880 # ... sqrt(2) - 1
32_h_lt_b_ = 'abs(h) < abs(b)'
35class Fdot(Fsum):
36 '''Precision dot product.
37 '''
38 def __init__(self, a, *b, **name_RESIDUAL):
39 '''New L{Fdot} precision dot product M{sum(a[i] * b[i]
40 for i=0..len(a)-1)}.
42 @arg a: Iterable, list, tuple, etc. (C{scalar}s).
43 @arg b: Other values (C{scalar}s), all positional.
44 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and
45 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.
47 @raise OverflowError: Partial C{2sum} overflow.
49 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.
51 @see: Function L{fdot} and method L{Fsum.fadd}.
52 '''
53 Fsum.__init__(self, **name_RESIDUAL)
54 self.fadd(_map_mul(a, b, Fdot))
57class Fhorner(Fsum):
58 '''Precision polynomial evaluation using the Horner form.
59 '''
60 def __init__(self, x, *cs, **name_RESIDUAL):
61 '''New L{Fhorner} evaluation of polynomial M{sum(cs[i] * x**i
62 for i=0..len(cs)-1)}.
64 @arg x: Polynomial argument (C{scalar} or C{Fsum} instance).
65 @arg cs: Polynomial coeffients (C{scalar} or C{Fsum}
66 instances), all positional.
67 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and
68 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.
70 @raise OverflowError: Partial C{2sum} overflow.
72 @raise TypeError: Non-scalar B{C{x}}.
74 @raise ValueError: Non-finite B{C{x}}.
76 @see: Function L{fhorner} and methods L{Fsum.fadd} and
77 L{Fsum.fmul}.
78 '''
79 Fsum.__init__(self, **name_RESIDUAL)
80 if cs:
81 if isinstance(x, Fsum):
82 _mul = self._mul_Fsum
83 else:
84 _mul = self._mul_scalar
85 x = _2float(x=x)
86 op = Fhorner.__name__
87 if len(cs) > 1 and x:
88 for c in reversed(cs):
89 self._fset_ps(_mul(x, op))
90 self._fadd(c, op, up=False)
91 self._update()
92 else: # x == 0
93 self._fadd(cs[0], op)
94 else:
95 self._fset(_0_0)
98class Fhypot(Fsum):
99 '''Precision summation and hypotenuse, default C{power=2}.
100 '''
101 def __init__(self, *xs, **power_name_RESIDUAL):
102 '''New L{Fhypot} hypotenuse of (the I{power} of) several components.
104 @arg xs: One or more components (each a C{scalar} or an C{Fsum}
105 instance).
106 @kwarg power_name_RESIDUAL: Optional, C{scalar} exponent and
107 root order C{B{power}=2}, a C{B{name}=NN} and
108 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.
109 '''
110 try:
111 p, kwds = _xkwds_pop2(power_name_RESIDUAL, power=2)
112 Fsum.__init__(self, **kwds)
113 if xs:
114 r = _1_0 / p
115 self._facc_power(p, xs, Fhypot)
116 self._fpow(r, _pow_op_)
117 else:
118 self._fset(_0_0)
119 except Exception as x:
120 raise self._ErrorXs(x, xs, power=p)
123class Fpolynomial(Fsum):
124 '''Precision polynomial evaluation.
125 '''
126 def __init__(self, x, *cs, **name_RESIDUAL):
127 '''New L{Fpolynomial} evaluation of the polynomial
128 M{sum(cs[i] * x**i for i=0..len(cs)-1)}.
130 @arg x: Polynomial argument (C{scalar} or L{Fsum}).
131 @arg cs: Polynomial coeffients (each a C{scalar} or
132 an L{Fsum} instance), all positional.
133 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and
134 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.
136 @raise OverflowError: Partial C{2sum} overflow.
138 @raise TypeError: Non-scalar B{C{x}}.
140 @raise ValueError: Non-finite B{C{x}}.
142 @see: Class L{Fhorner}, function L{fpolynomial} and
143 method L{Fsum.fadd}.
144 '''
145 Fsum.__init__(self, *cs[:1], **name_RESIDUAL)
146 n = len(cs) - 1
147 if n > 0:
148 self.fadd(_1map_mul(cs[1:], _powers(x, n)))
149 elif n < 0:
150 self._fset(_0_0)
153class Fpowers(Fsum):
154 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.
155 '''
156 def __init__(self, power, *xs, **name_RESIDUAL):
157 '''New L{Fpowers} sum of (the I{power} of) several values.
159 @arg power: The exponent (C{scalar} or L{Fsum}).
160 @arg xs: One or more values (each a C{scalar} or an
161 C{Fsum} instance).
162 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and
163 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.
164 '''
165 try:
166 Fsum.__init__(self, **name_RESIDUAL)
167 if xs:
168 self._facc_power(power, xs, Fpowers) # x**0 == 1
169 else:
170 self._fset(_0_0)
171 except Exception as x:
172 raise self._ErrorXs(x, xs, power=power)
175class Fn_rt(Fsum):
176 '''N-th root of a precision summation.
177 '''
178 def __init__(self, root, *xs, **name_RESIDUAL):
179 '''New L{Fn_rt} root of a precision sum.
181 @arg root: The order (C{scalar} or C{Fsum}),
182 non-zero.
183 @arg xs: Values to summate (each a C{scalar} or
184 an C{Fsum} instance).
185 @kwarg name_RESIDUAL: See L{Fsum.__init__}.
186 '''
187 try:
188 Fsum.__init__(self, **name_RESIDUAL)
189 if xs:
190 r = _1_0 / root
191 self. fadd(xs)
192 self._fpow(r, _pow_op_) # self **= r
193 else:
194 self._fset(_0_0)
195 except Exception as x:
196 raise self._ErrorXs(x, xs, root=root)
199class Fcbrt(Fn_rt):
200 '''Cubic root of a precision summation.
201 '''
202 def __init__(self, *xs, **name_RESIDUAL):
203 '''New L{Fcbrt} cubic root of a precision sum.
205 @see: Class L{Fn_rt} for further details.
206 '''
207 Fn_rt.__init__(self, _3_0, *xs, **name_RESIDUAL)
210class Fsqrt(Fn_rt):
211 '''Square root of a precision summation.
212 '''
213 def __init__(self, *xs, **name_RESIDUAL):
214 '''New L{Fsqrt} square root of a precision sum.
216 @see: Class L{Fn_rt} for further details.
217 '''
218 Fn_rt.__init__(self, _2_0, *xs, **name_RESIDUAL)
221def bqrt(x):
222 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)}.
224 @arg x: Value (C{scalar}).
226 @return: I{Quartic} root (C{float}).
228 @raise ValueError: Negative B{C{x}}.
230 @see: Functions L{zcrt} and L{zqrt}.
231 '''
232 return _root(x, _0_25, bqrt)
235try:
236 from math import cbrt # Python 3.11+
238 def cbrt2(x):
239 '''Compute the cube root I{squared} M{x**(2/3)}.
240 '''
241 return cbrt(x)**2 # cbrt(-0.0*2) == -0.0
243except ImportError: # Python 3.10-
245 def cbrt(x):
246 '''Compute the cube root M{x**(1/3)}.
248 @arg x: Value (C{scalar}).
250 @return: Cubic root (C{float}).
252 @see: Functions L{cbrt2} and L{sqrt3}.
253 '''
254 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>
255 # simpler and more accurate than Ken Turkowski's CubeRoot, see
256 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>
257 return _copysign(pow(fabs(x), _1_3rd), x) # cbrt(-0.0) == -0.0
259 def cbrt2(x): # PYCHOK attr
260 '''Compute the cube root I{squared} M{x**(2/3)}.
262 @arg x: Value (C{scalar}).
264 @return: Cube root I{squared} (C{float}).
266 @see: Functions L{cbrt} and L{sqrt3}.
267 '''
268 return pow(fabs(x), _2_3rd) # XXX pow(fabs(x), _1_3rd)**2
271def euclid(x, y):
272 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by
273 M{max(abs(x), abs(y)) + min(abs(x), abs(y)) * 0.4142...}.
275 @arg x: X component (C{scalar}).
276 @arg y: Y component (C{scalar}).
278 @return: Appoximate norm (C{float}).
280 @see: Function L{euclid_}.
281 '''
282 x, y = fabs(x), fabs(y)
283 if x < y:
284 x, y = y, x
285 return x + y * _0_4142 # XXX * _0_5 before 20.10.02
288def euclid_(*xs):
289 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))}
290 by cascaded L{euclid}.
292 @arg xs: X arguments, positional (C{scalar}s).
294 @return: Appoximate norm (C{float}).
296 @see: Function L{euclid}.
297 '''
298 e = _0_0
299 for x in sorted(map(fabs, xs)): # XXX not reverse=True
300 # e = euclid(x, e)
301 if e < x:
302 e, x = x, e
303 if x:
304 e += x * _0_4142
305 return e
308def facos1(x):
309 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}.
311 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/
312 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.
313 '''
314 a = fabs(x)
315 if a < EPS0:
316 r = PI_2
317 elif a < EPS1:
318 H = Fhorner(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)
319 r = float(H * sqrt(_1_0 - a))
320 if x < 0:
321 r = PI - r
322 else:
323 r = PI if x < 0 else _0_0
324 return r
327def fasin1(x): # PYCHOK no cover
328 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}.
330 @see: L{facos1}.
331 '''
332 return PI_2 - facos1(x)
335def fatan(x):
336 '''Fast approximation of C{atan(B{x})}.
337 '''
338 a = fabs(x)
339 if a < _1_0:
340 r = fatan1(a) if a else _0_0
341 elif a > _1_0:
342 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)
343 else:
344 r = PI_4
345 if x < 0: # copysign0(r, x)
346 r = -r
347 return r
350def fatan1(x):
351 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} <= 1}, I{unchecked}.
353 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/
354 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations
355 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/
356 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},
357 IEEE Signal Processing Magazine, 111, May 2006.
358 '''
359 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1
360 # PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x - 1
361 # x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))
362 H = Fhorner(x, _0_0, 1.0300981634, -0.1784, -0.0663)
363 return float(H)
366def fatan2(y, x):
367 '''Fast approximation of C{atan2(B{y}, B{x})}.
369 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/
370 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}
371 and L{fatan1}.
372 '''
373 a, b = fabs(x), fabs(y)
374 if b > a:
375 r = (PI_2 - fatan1(a / b)) if a else PI_2
376 elif a > b:
377 r = fatan1(b / a) if b else _0_0
378 elif a: # a == b != 0
379 r = PI_4
380 else: # a == b == 0
381 return _0_0
382 if x < 0:
383 r = PI - r
384 if y < 0: # copysign0(r, y)
385 r = -r
386 return r
389def favg(v1, v2, f=_0_5):
390 '''Return the average of two values.
392 @arg v1: One value (C{scalar}).
393 @arg v2: Other value (C{scalar}).
394 @kwarg f: Optional fraction (C{float}).
396 @return: M{v1 + f * (v2 - v1)} (C{float}).
397 '''
398# @raise ValueError: Fraction out of range.
399# '''
400# if not 0 <= f <= 1: # XXX restrict fraction?
401# raise _ValueError(fraction=f)
402 # v1 + f * (v2 - v1) == v1 * (1 - f) + v2 * f
403 return fsum1_(v1, -f * v1, f * v2)
406def fdot(a, *b):
407 '''Return the precision dot product M{sum(a[i] * b[i] for
408 i=0..len(a))}.
410 @arg a: Iterable, list, tuple, etc. (C{scalar}s).
411 @arg b: All positional arguments (C{scalar}s).
413 @return: Dot product (C{float}).
415 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.
417 @see: Class L{Fdot} and U{Algorithm 5.10 B{DotK}
418 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.
419 '''
420 return fsum(_map_mul(a, b, fdot))
423def fdot3(a, b, c, start=0):
424 '''Return the precision dot product M{start +
425 sum(a[i] * b[i] * c[i] for i=0..len(a)-1)}.
427 @arg a: Iterable, list, tuple, etc. (C{scalar}s).
428 @arg b: Iterable, list, tuple, etc. (C{scalar}s).
429 @arg c: Iterable, list, tuple, etc. (C{scalar}s).
430 @kwarg start: Optional bias (C{scalar}).
432 @return: Dot product (C{float}).
434 @raise LenError: Unequal C{len(B{a})}, C{len(B{b})}
435 and/or C{len(B{c})}.
437 @raise OverflowError: Partial C{2sum} overflow.
438 '''
439 def _mul3(a, b, c): # map function
440 return a * b * c
442 def _mul3_(a, b, c, start):
443 yield start
444 for abc in map(_mul3, a, b, c):
445 yield abc
447 if not len(a) == len(b) == len(c):
448 raise LenError(fdot3, a=len(a), b=len(b), c=len(c))
450 return fsum(_mul3_(a, b, c, start) if start else map(_mul3, a, b, c))
453def fhorner(x, *cs):
454 '''Evaluate the polynomial M{sum(cs[i] * x**i for
455 i=0..len(cs)-1)} using the Horner form.
457 @arg x: Polynomial argument (C{scalar}).
458 @arg cs: Polynomial coeffients (C{scalar}s).
460 @return: Horner value (C{float}).
462 @raise OverflowError: Partial C{2sum} overflow.
464 @raise TypeError: Non-scalar B{C{x}}.
466 @raise ValueError: No B{C{cs}} coefficients or B{C{x}} is not finite.
468 @see: Function L{fpolynomial} and class L{Fhorner}.
469 '''
470 H = Fhorner(x, *cs)
471 return float(H)
474def fidw(xs, ds, beta=2):
475 '''Interpolate using U{Inverse Distance Weighting
476 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).
478 @arg xs: Known values (C{scalar}s).
479 @arg ds: Non-negative distances (C{scalar}s).
480 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).
482 @return: Interpolated value C{x} (C{float}).
484 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.
486 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} value,
487 weighted B{C{ds}} below L{EPS}.
489 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.
490 '''
491 n, xs = len2(xs)
492 d, ds = len2(ds)
493 if n != d or n < 1:
494 raise LenError(fidw, xs=n, ds=d)
496 d, x = min(zip(ds, xs))
497 if d > EPS0 and n > 1:
498 b = -Int_(beta=beta, low=0, high=3)
499 if b < 0:
500 ws = tuple(float(d)**b for d in ds)
501 t = fsum(_1map_mul(xs, ws)) # Fdot(xs, *ws)
502 x = _over(t, fsum(ws, floats=True))
503 else: # b == 0
504 x = fsum(xs) / n # fmean(xs)
505 elif d < 0: # PYCHOK no cover
506 n = Fmt.SQUARE(distance=ds.index(d))
507 raise _ValueError(n, d, txt=_negative_)
508 return x
511def fmean(xs):
512 '''Compute the accurate mean M{sum(xs) / len(xs)}.
514 @arg xs: Values (C{scalar} or L{Fsum} instances).
516 @return: Mean value (C{float}).
518 @raise LenError: No B{C{xs}} values.
520 @raise OverflowError: Partial C{2sum} overflow.
521 '''
522 n, xs = len2(xs)
523 if n < 1:
524 raise LenError(fmean, xs=xs)
525 return Fsum(*xs).fover(n) if n > 1 else _2float(index=0, xs=xs[0])
528def fmean_(*xs):
529 '''Compute the accurate mean M{sum(xs) / len(xs)}.
531 @see: Function L{fmean} for further details.
532 '''
533 return fmean(xs)
536def fpolynomial(x, *cs, **over):
537 '''Evaluate the polynomial M{sum(cs[i] * x**i for
538 i=0..len(cs)) [/ over]}.
540 @arg x: Polynomial argument (C{scalar}).
541 @arg cs: Polynomial coeffients (C{scalar}s), all
542 positional.
543 @kwarg over: Optional final, I{non-zero} divisor
544 (C{scalar}).
546 @return: Polynomial value (C{float}).
548 @raise OverflowError: Partial C{2sum} overflow.
550 @raise TypeError: Non-scalar B{C{x}}.
552 @raise ValueError: No B{C{cs}} coefficients or B{C{x}} is not finite.
554 @see: Function L{fhorner} and class L{Fpolynomial}.
555 '''
556 P = Fpolynomial(x, *cs)
557 d = _xkwds_get(over, over=0) if over else 0
558 return P.fover(d) if d else float(P)
561def fpowers(x, n, alts=0):
562 '''Return a series of powers M{[x**i for i=1..n]}.
564 @arg x: Value (C{scalar} or L{Fsum}).
565 @arg n: Highest exponent (C{int}).
566 @kwarg alts: Only alternating powers, starting with this
567 exponent (C{int}).
569 @return: Tuple of powers of B{C{x}} (C{type(B{x})}).
571 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.
573 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.
574 '''
575 if not isint(n):
576 raise _IsnotError(int.__name__, n=n)
577 elif n < 1:
578 raise _ValueError(n=n)
580 p = x if isint(x) or isinstance(x, Fsum) else _2float(x=x)
581 ps = tuple(_powers(p, n))
583 if alts > 0: # x**2, x**4, ...
584 # ps[alts-1::2] chokes PyChecker
585 ps = ps[slice(alts-1, None, 2)]
587 return ps
590try:
591 from math import prod as fprod # Python 3.8
592except ImportError:
594 def fprod(xs, start=1):
595 '''Iterable product, like C{math.prod} or C{numpy.prod}.
597 @arg xs: Terms to be multiplied, an iterable, list,
598 tuple, etc. (C{scalar}s).
599 @kwarg start: Initial term, also the value returned
600 for an empty B{C{xs}} (C{scalar}).
602 @return: The product (C{float}).
604 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
605 numpy/reference/generated/numpy.prod.html>}.
606 '''
607 return freduce(_operator.mul, xs, start)
610def frange(start, number, step=1):
611 '''Generate a range of C{float}s.
613 @arg start: First value (C{float}).
614 @arg number: The number of C{float}s to generate (C{int}).
615 @kwarg step: Increment value (C{float}).
617 @return: A generator (C{float}s).
619 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
620 numpy/reference/generated/numpy.arange.html>}.
621 '''
622 if not isint(number):
623 raise _IsnotError(int.__name__, number=number)
624 for i in range(number):
625 yield start + (step * i)
628try:
629 from functools import reduce as freduce
630except ImportError:
631 try:
632 freduce = reduce # PYCHOK expected
633 except NameError: # Python 3+
635 def freduce(f, xs, *start):
636 '''For missing C{functools.reduce}.
637 '''
638 if start:
639 r = v = start[0]
640 else:
641 r, v = 0, MISSING
642 for v in xs:
643 r = f(r, v)
644 if v is MISSING:
645 raise _TypeError(xs=(), start=MISSING)
646 return r
649def fremainder(x, y):
650 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.
652 @arg x: Numerator (C{scalar}).
653 @arg y: Modulus, denominator (C{scalar}).
655 @return: Remainder (C{scalar}, preserving signed
656 0.0) or C{NAN} for any non-finite B{C{x}}.
658 @raise ValueError: Infinite or near-zero B{C{y}}.
660 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/
661 project/geographiclib/>} and Python 3.7+
662 U{math.remainder<https://docs.Python.org/3/
663 library/math.html#math.remainder>}.
664 '''
665 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and
666 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native
667 # fmod( 0, 360) == 0.0
668 # fmod( 360, 360) == 0.0
669 # fmod(-0, 360) == 0.0
670 # fmod(-0.0, 360) == -0.0
671 # fmod(-360, 360) == -0.0
672 # however, using the % operator ...
673 # 0 % 360 == 0
674 # 360 % 360 == 0
675 # 360.0 % 360 == 0.0
676 # -0 % 360 == 0
677 # -360 % 360 == 0 == (-360) % 360
678 # -0.0 % 360 == 0.0 == (-0.0) % 360
679 # -360.0 % 360 == 0.0 == (-360.0) % 360
681 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)
682 # == +0.0. This fixes this bug. See also Math::AngNormalize
683 # in the C++ library, Math.sincosd has a similar fix.
684 if _isfinite(x):
685 try:
686 r = remainder(x, y) if x else x
687 except Exception as e:
688 raise _xError(e, unstr(fremainder, x, y))
689 else: # handle x INF and NINF as NAN
690 r = NAN
691 return r
694if _sys_version_info2 < (3, 8): # PYCHOK no cover
695 from math import hypot # OK in Python 3.7-
697 def hypot_(*xs):
698 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.
700 Similar to Python 3.8+ n-dimension U{math.hypot
701 <https://docs.Python.org/3.8/library/math.html#math.hypot>},
702 but exceptions, C{nan} and C{infinite} values are
703 handled differently.
705 @arg xs: X arguments (C{scalar}s), all positional.
707 @return: Norm (C{float}).
709 @raise OverflowError: Partial C{2sum} overflow.
711 @raise ValueError: Invalid or no B{C{xs}} values.
713 @note: The Python 3.8+ Euclidian distance U{math.dist
714 <https://docs.Python.org/3.8/library/math.html#math.dist>}
715 between 2 I{n}-dimensional points I{p1} and I{p2} can be
716 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},
717 provided I{p1} and I{p2} have the same, non-zero length I{n}.
718 '''
719 h, x2 = _h_x2(xs, hypot_)
720 return (h * sqrt(x2)) if x2 else _0_0
722elif _sys_version_info2 < (3, 10):
723 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see
724 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},
725 # U{cffk<https://Bugs.Python.org/issue43088>} and module
726 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}
728 def hypot(x, y):
729 '''Compute the norm M{sqrt(x**2 + y**2)}.
731 @arg x: X argument (C{scalar}).
732 @arg y: Y argument (C{scalar}).
734 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).
735 '''
736 if x:
737 h = sqrt(x**2 + y**2) if y else fabs(x)
738 elif y:
739 h = fabs(y)
740 else:
741 h = _0_0
742 return h
744 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9
745else:
746 from math import hypot # PYCHOK in Python 3.10+
747 hypot_ = hypot
750def _h_x2(xs, which):
751 '''(INTERNAL) Helper for L{hypot_} and L{hypot2_}.
752 '''
753 n, xs = len2(xs)
754 if n > 0:
755 h = float(max(map(fabs, xs)))
756 if h < EPS0:
757 x2 = _0_0
758 elif n > 1:
759 _h = (_1_0 / h) if h != _1_0 else _1_0
760 x2 = _fsum(_1primed((x * _h)**2 for x in xs))
761 else:
762 x2 = _1_0
763 return h, x2
765 t = Fmt.PAREN(which.__name__, xs)
766 raise _ValueError(t, txt=_too_(_few_))
769def hypot1(x):
770 '''Compute the norm M{sqrt(1 + x**2)}.
772 @arg x: Argument (C{scalar}).
774 @return: Norm (C{float}).
775 '''
776 return hypot(_1_0, x) if x else _1_0
779def hypot2(x, y):
780 '''Compute the I{squared} norm M{x**2 + y**2}.
782 @arg x: X argument (C{scalar}).
783 @arg y: Y argument (C{scalar}).
785 @return: C{B{x}**2 + B{y}**2} (C{float}).
786 '''
787 if fabs(x) < fabs(y):
788 x, y = y, x
789 if x:
790 h2 = x**2
791 if y:
792 h2 *= (y / x)**2 + _1_0
793 else:
794 h2 = _0_0
795 return h2
798def hypot2_(*xs):
799 '''Compute the I{squared} norm C{sum(x**2 for x in B{xs})}.
801 @arg xs: X arguments (C{scalar}s), all positional.
803 @return: Squared norm (C{float}).
805 @raise OverflowError: Partial C{2sum} overflow.
807 @raise ValueError: Invalid or no B{C{xs}} value.
809 @see: Function L{hypot_}.
810 '''
811 h, x2 = _h_x2(xs, hypot2_)
812 return (h**2 * x2) if x2 else _0_0
815def _map_mul(a, b, where):
816 '''(INTERNAL) Yield each B{C{a * b}}.
817 '''
818 n = len(b)
819 if len(a) != n: # PYCHOK no cover
820 raise LenError(where, a=len(a), b=n)
821 return map(_operator.mul, a, b) if n > 3 else _1map_mul(a, b)
824def _1map_mul(a, b):
825 '''(INTERNAL) Yield each B{C{a * b}}, 1-primed.
826 '''
827 return _1primed(map(_operator.mul, a, b))
830def norm2(x, y):
831 '''Normalize a 2-dimensional vector.
833 @arg x: X component (C{scalar}).
834 @arg y: Y component (C{scalar}).
836 @return: 2-Tuple C{(x, y)}, normalized.
838 @raise ValueError: Invalid B{C{x}} or B{C{y}}
839 or zero norm.
840 '''
841 try:
842 h = hypot(x, y)
843 if h:
844 x, y = (x / h), (y / h)
845 else:
846 x = _copysign_0_0(x) # pass?
847 y = _copysign_0_0(y)
848 except Exception as e:
849 raise _xError(e, x=x, y=y, h=h)
850 return x, y
853def norm_(*xs):
854 '''Normalize all n-dimensional vector components.
856 @arg xs: Components (C{scalar}s), all positional.
858 @return: Yield each component, normalized.
860 @raise ValueError: Invalid or insufficent B{C{xs}}
861 or zero norm.
862 '''
863 try:
864 h = hypot_(*xs)
865 _h = (_1_0 / h) if h else _0_0
866 for i, x in enumerate(xs):
867 yield x * _h
868 except Exception as e:
869 raise _xError(e, Fmt.SQUARE(xs=i), x, _h_, h)
872def _powers(x, n):
873 '''(INTERNAL) Yield C{x**i for i=1..n}.
874 '''
875 p = 1 # type(p) == type(x)
876 for _ in range(n):
877 p *= x
878 yield p
881def _root(x, p, where):
882 '''(INTERNAL) Raise C{x} to power C{0 < p < 1}.
883 '''
884 if x < 0:
885 t = _SPACE_(_invokation_, where.__name__)
886 raise _ValueError(unstr(t, x), txt=_negative_)
887 return pow(x, p) if x else _0_0
890def sqrt0(x, Error=None):
891 '''Return the square root iff C{B{x} >} L{EPS02}.
893 @arg x: Value (C{scalar}).
894 @kwarg Error: Error to raise for negative B{C{x}}.
896 @return: Square root (C{float}) or C{0.0}.
898 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}
899 returns C{0.0}.
900 '''
901 if Error and x < 0:
902 raise Error(Fmt.PAREN(sqrt=x))
903 return sqrt(x) if x > EPS02 else (_0_0 if x < EPS02 else EPS0)
906def sqrt3(x):
907 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)}.
909 @arg x: Value (C{scalar}).
911 @return: Square root I{cubed} (C{float}).
913 @raise ValueError: Negative B{C{x}}.
915 @see: Functions L{cbrt} and L{cbrt2}.
916 '''
917 return _root(x, _1_5, sqrt3)
920def sqrt_a(h, b):
921 '''Compute C{I{a}} side of a right-angled triangle from
922 C{sqrt(B{h}**2 - B{b}**2)}.
924 @arg h: Hypotenuse or outer annulus radius (C{scalar}).
925 @arg b: Triangle side or inner annulus radius (C{scalar}).
927 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).
929 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.
931 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.
933 @see: Inner tangent chord B{I{d}} of an U{annulus
934 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}
935 and function U{annulus_area<https://People.SC.FSU.edu/
936 ~jburkardt/py_src/geometry/geometry.py>}.
937 '''
938 try:
939 if not (_isHeight(h) and _isRadius(b)):
940 raise TypeError(_not_scalar_)
941 c = fabs(h)
942 if c > EPS0:
943 s = _1_0 - (b / c)**2
944 if s < 0:
945 raise ValueError(_h_lt_b_)
946 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)
947 else: # PYCHOK no cover
948 b = fabs(b)
949 d = c - b
950 if d < 0:
951 raise ValueError(_h_lt_b_)
952 d *= c + b
953 a = sqrt(d) if d else _0_0
954 except Exception as x:
955 raise _xError(x, h=h, b=b)
956 return copysign0(a, h)
959def zcrt(x):
960 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)}.
962 @arg x: Value (C{scalar}).
964 @return: I{Zenzi-cubic} root (C{float}).
966 @see: Functions L{bqrt} and L{zqrt}.
968 @raise ValueError: Negative B{C{x}}.
969 '''
970 return _root(x, _1_6th, zcrt)
973def zqrt(x):
974 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root, M{x**(1 / 8)}.
976 @arg x: Value (C{scalar}).
978 @return: I{Zenzi-quartic} root (C{float}).
980 @see: Functions L{bqrt} and L{zcrt}.
982 @raise ValueError: Negative B{C{x}}.
983 '''
984 return _root(x, _0_125, zqrt)
986# **) MIT License
987#
988# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
989#
990# Permission is hereby granted, free of charge, to any person obtaining a
991# copy of this software and associated documentation files (the "Software"),
992# to deal in the Software without restriction, including without limitation
993# the rights to use, copy, modify, merge, publish, distribute, sublicense,
994# and/or sell copies of the Software, and to permit persons to whom the
995# Software is furnished to do so, subject to the following conditions:
996#
997# The above copyright notice and this permission notice shall be included
998# in all copies or substantial portions of the Software.
999#
1000# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1001# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1002# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1003# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1004# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1005# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1006# OTHER DEALINGS IN THE SOFTWARE.