Coverage for pygeodesy/fmath.py: 90%
314 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-10 14:08 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-10 14:08 -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, isbool, isint, isscalar, \
10 len2, map1, _xiterable
11from pygeodesy.constants import EPS0, EPS02, EPS1, NAN, PI, PI_2, PI_4, \
12 _0_0, _0_125, _1_6th, _0_25, _1_3rd, _0_5, _1_0, \
13 _N_1_0, _1_5, _copysign_0_0, _isfinite, remainder
14from pygeodesy.errors import _IsnotError, LenError, _TypeError, _ValueError, \
15 _xError, _xkwds_get1, _xkwds_pop2
16from pygeodesy.fsums import _2float, Fsum, fsum, fsum1_, _isFsumTuple, _1primed, \
17 Fmt, unstr
18from pygeodesy.interns import MISSING, _negative_, _not_scalar_
19from pygeodesy.lazily import _ALL_LAZY, _sys_version_info2
20# from pygeodesy.streprs import Fmt, unstr # from .fsums
21from pygeodesy.units import Int_, _isHeight, _isRadius, Float_ # PYCHOK for .heights
23from math import fabs, sqrt # pow
24import operator as _operator # in .datums, .trf, .utm
26__all__ = _ALL_LAZY.fmath
27__version__ = '24.05.29'
29# sqrt(2) <https://WikiPedia.org/wiki/Square_root_of_2>
30_0_4142 = 0.41421356237309504880 # ... sqrt(2) - 1
31_2_3rd = _1_3rd * 2
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] for
40 i=0..len(a)-1)}.
42 @arg a: Iterable of values (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
43 instance).
44 @arg b: Other values (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
45 all positional.
46 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) and the C{B{RESIDUAL}=0.0}
47 threshold (C{scalar}) for raising L{ResidualError}s, see class
48 L{Fsum<Fsum.__init__>}.
50 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.
52 @raise OverflowError: Partial C{2sum} overflow.
54 @raise TypeError: Invalid B{C{x}}.
56 @raise ValueError: Non-finite B{C{x}}.
58 @see: Function L{fdot} and method L{Fsum.fadd}.
59 '''
60 Fsum.__init__(self, **name_RESIDUAL)
61 self.fadd(_map_mul(a, b, Fdot))
64class Fhorner(Fsum):
65 '''Precision polynomial evaluation using the Horner form.
66 '''
67 def __init__(self, x, *cs, **name_RESIDUAL):
68 '''New L{Fhorner} evaluation of polynomial M{sum(cs[i] * x**i for
69 i=0..len(cs)-1)}.
71 @arg x: Polynomial argument (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
72 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
73 instance), all positional.
74 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) and the C{B{RESIDUAL}=0.0}
75 threshold (C{scalar}) for raising L{ResidualError}s, see class
76 L{Fsum<Fsum.__init__>}.
78 @raise OverflowError: Partial C{2sum} overflow.
80 @raise TypeError: Invalid B{C{x}}.
82 @raise ValueError: Non-finite B{C{x}}.
84 @see: Function L{fhorner} and methods L{Fsum.fadd} and L{Fsum.fmul}.
85 '''
86 Fsum.__init__(self, **name_RESIDUAL)
87 if cs:
88 self._fhorner(x, cs, Fhorner.__name__)
89 else:
90 self._fset_ps(_0_0)
93class Fhypot(Fsum):
94 '''Precision summation and hypotenuse, default C{root=2}.
95 '''
96 def __init__(self, *xs, **root_name_RESIDUAL_raiser):
97 '''New L{Fhypot} hypotenuse of (the I{root} of) several components
98 (raised to the power I{root}).
100 @arg xs: Components (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
101 all positional.
102 @kwarg root_name_RESIDUAL_raiser: Optional, exponent and C{B{root}=2} order
103 (C{scalar}), C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0}
104 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for
105 raising L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and
106 method L{root<Fsum.root>}.
107 '''
108 r = None # _xkwds_pop2 error
109 try:
110 r, kwds = _xkwds_pop2(root_name_RESIDUAL_raiser, root=2)
111 r, kwds = _xkwds_pop2(kwds, power=r) # for backward compatibility
112 raiser = _Fsum__init__(self, **kwds)
113 if xs:
114 self._facc_power(r, xs, Fhypot, **raiser)
115 self._fset(self.root(r, **raiser))
116 except Exception as X:
117 raise self._ErrorXs(X, xs, root=r)
120class Fpolynomial(Fsum):
121 '''Precision polynomial evaluation.
122 '''
123 def __init__(self, x, *cs, **name_RESIDUAL):
124 '''New L{Fpolynomial} evaluation of the polynomial
125 M{sum(cs[i] * x**i for i=0..len(cs)-1)}.
127 @arg x: Polynomial argument (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
128 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
129 instance), all positional.
130 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) and the C{B{RESIDUAL}=0.0}
131 threshold (C{scalar}) for raising L{ResidualError}s, see class
132 L{Fsum<Fsum.__init__>}.
134 @raise OverflowError: Partial C{2sum} overflow.
136 @raise TypeError: Invalid B{C{x}}.
138 @raise ValueError: Non-finite B{C{x}}.
140 @see: Class L{Fhorner}, function L{fpolynomial} and method L{Fsum.fadd}.
141 '''
142 Fsum.__init__(self, *cs[:1], **name_RESIDUAL)
143 n = len(cs) - 1
144 if n > 0:
145 self.fadd(_1map_mul(cs[1:], _powers(x, n)))
146 elif n < 0:
147 self._fset_ps(_0_0)
150class Fpowers(Fsum):
151 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.
152 '''
153 def __init__(self, power, *xs, **name_RESIDUAL_raiser):
154 '''New L{Fpowers} sum of (the I{power} of) several bases.
156 @arg power: The exponent (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
157 @arg xs: One or more bases (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
158 all positional.
159 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0}
160 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for raising
161 L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and method
162 L{fpow<Fsum.fpow>}.
163 '''
164 try:
165 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)
166 if xs:
167 self._facc_power(power, xs, Fpowers, **raiser) # x**0 == 1
168 except Exception as X:
169 raise self._ErrorXs(X, xs, power=power)
172class Froot(Fsum):
173 '''The root of a precision summation.
174 '''
175 def __init__(self, root, *xs, **name_RESIDUAL_raiser):
176 '''New L{Froot} root of a precision sum.
178 @arg root: The order (C{scalar} or an L{Fsum} or L{Fsum2Tuple}), non-zero.
179 @arg xs: Items to summate (each a C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
180 all positional.
181 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0}
182 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for raising
183 L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and method
184 L{fpow<Fsum.fpow>}.
185 '''
186 try:
187 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)
188 if xs:
189 self.fadd(xs)
190 self._fset(self.root(root, **raiser))
191 except Exception as X:
192 raise self._ErrorXs(X, xs, root=root)
195class Fcbrt(Froot):
196 '''Cubic root of a precision summation.
197 '''
198 def __init__(self, *xs, **name_RESIDUAL_raiser):
199 '''New L{Fcbrt} cubic root of a precision sum.
201 @see: Class L{Froot} for further details.
202 '''
203 Froot.__init__(self, 3, *xs, **name_RESIDUAL_raiser)
206class Fsqrt(Froot):
207 '''Square root of a precision summation.
208 '''
209 def __init__(self, *xs, **name_RESIDUAL_raiser):
210 '''New L{Fsqrt} square root of a precision sum.
212 @see: Class L{Froot} for further details.
213 '''
214 Froot.__init__(self, 2, *xs, **name_RESIDUAL_raiser)
217def _Fsum__init__(inst, raiser=MISSING, **name_RESIDUAL):
218 '''(INTERNAL) Init an C{F...} instance above.
219 '''
220 Fsum.__init__(inst, **name_RESIDUAL) # PYCHOK self
221 inst._fset_ps(_0_0)
222 return {} if raiser is MISSING else dict(raiser=raiser)
225def bqrt(x):
226 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)},
227 preserving C{type(B{x})}.
229 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
231 @return: I{Quartic} root (C{float} or an L{Fsum}).
233 @raise TypeeError: Invalid B{C{x}}.
235 @raise ValueError: Negative B{C{x}}.
237 @see: Functions L{zcrt} and L{zqrt}.
238 '''
239 return _root(x, _0_25, bqrt)
242try:
243 from math import cbrt as _cbrt # Python 3.11+
245except ImportError: # Python 3.10-
247 def _cbrt(x):
248 '''(INTERNAL) Compute the I{signed}, cube root M{x**(1/3)}.
249 '''
250 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>
251 # simpler and more accurate than Ken Turkowski's CubeRoot, see
252 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>
253 return _copysign(pow(fabs(x), _1_3rd), x) # to avoid complex
256def cbrt(x):
257 '''Compute the cube root M{x**(1/3)}, preserving C{type(B{x})}.
259 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
261 @return: Cubic root (C{float} or L{Fsum}).
263 @see: Functions L{cbrt2} and L{sqrt3}.
264 '''
265 if _isFsumTuple(x):
266 r = abs(x).fpow(_1_3rd)
267 if x.signOf() < 0:
268 r = -r
269 else:
270 r = _cbrt(x)
271 return r # cbrt(-0.0) == -0.0
274def cbrt2(x): # PYCHOK attr
275 '''Compute the cube root I{squared} M{x**(2/3)}, preserving C{type(B{x})}.
277 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
279 @return: Cube root I{squared} (C{float} or L{Fsum}).
281 @see: Functions L{cbrt} and L{sqrt3}.
282 '''
283 return abs(x).fpow(_2_3rd) if _isFsumTuple(x) else _cbrt(x**2)
286def euclid(x, y):
287 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by
288 M{max(abs(x), abs(y)) + min(abs(x), abs(y)) * 0.4142...}.
290 @arg x: X component (C{scalar} or L{Fsum} instance).
291 @arg y: Y component (C{scalar} or L{Fsum} instance).
293 @return: Appoximate norm (C{float} or L{Fsum}).
295 @see: Function L{euclid_}.
296 '''
297 x, y = abs(x), abs(y) # NOT fabs!
298 if y > x:
299 x, y = y, x
300 return x + y * _0_4142 # XXX * _0_5 before 20.10.02
303def euclid_(*xs):
304 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))} by
305 cascaded L{euclid}.
307 @arg xs: X arguments (each C{scalar} or an L{Fsum}
308 instance), all positional.
310 @return: Appoximate norm (C{float} or L{Fsum}).
312 @see: Function L{euclid}.
313 '''
314 e = _0_0
315 for x in sorted(map(abs, xs)): # NOT fabs, reverse=True!
316 # e = euclid(x, e)
317 if e < x:
318 e, x = x, e
319 if x:
320 e += x * _0_4142
321 return e
324def facos1(x):
325 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}.
327 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/
328 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.
329 '''
330 a = fabs(x)
331 if a < EPS0:
332 r = PI_2
333 elif a < EPS1:
334 H = Fhorner(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)
335 H *= Fsqrt(_1_0, -a)
336 r = float(H)
337 if x < 0:
338 r = PI - r
339 else:
340 r = PI if x < 0 else _0_0
341 return r
344def fasin1(x): # PYCHOK no cover
345 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}.
347 @see: L{facos1}.
348 '''
349 return PI_2 - facos1(x)
352def fatan(x):
353 '''Fast approximation of C{atan(B{x})}.
354 '''
355 a = fabs(x)
356 if a < _1_0:
357 r = fatan1(a) if a else _0_0
358 elif a > _1_0:
359 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)
360 else:
361 r = PI_4
362 if x < 0: # copysign0(r, x)
363 r = -r
364 return r
367def fatan1(x):
368 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} < 1}, I{unchecked}.
370 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/
371 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations
372 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/
373 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},
374 IEEE Signal Processing Magazine, 111, May 2006.
375 '''
376 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1
377 # PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x < 1
378 # x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))
379 H = Fhorner(x, _0_0, 1.0300981634, -0.1784, -0.0663)
380 return float(H)
383def fatan2(y, x):
384 '''Fast approximation of C{atan2(B{y}, B{x})}.
386 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/
387 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}
388 and L{fatan1}.
389 '''
390 a, b = fabs(x), fabs(y)
391 if b > a:
392 r = (PI_2 - fatan1(a / b)) if a else PI_2
393 elif a > b:
394 r = fatan1(b / a) if b else _0_0
395 elif a: # a == b != 0
396 r = PI_4
397 else: # a == b == 0
398 return _0_0
399 if x < 0:
400 r = PI - r
401 if y < 0: # copysign0(r, y)
402 r = -r
403 return r
406def favg(a, b, f=_0_5):
407 '''Return the precision average of two values.
409 @arg a: One (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
410 @arg b: Other (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
411 @kwarg f: Optional fraction (C{float}).
413 @return: M{a + f * (b - a)} (C{float}).
414 '''
415# @raise ValueError: Fraction out of range.
416# '''
417# if not 0 <= f <= 1: # XXX restrict fraction?
418# raise _ValueError(fraction=f)
419 # a + f * (b - a) == a * (1 - f) + b * f
420 return fsum1_(a, a * (-f), b * f)
423def fdot(a, *b):
424 '''Return the precision dot product M{sum(a[i] * b[i] for
425 i=0..len(a))}.
427 @arg a: Iterable of values (each C{scalar}).
428 @arg b: Other values (each C{scalar}), all positional.
430 @return: Dot product (C{float}).
432 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.
434 @see: Class L{Fdot} and U{Algorithm 5.10 B{DotK}
435 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.
436 '''
437 return fsum(_map_mul(a, b, fdot))
440def fdot3(xs, ys, zs, start=0):
441 '''Return the precision dot product M{start +
442 sum(a[i] * b[i] * c[i] for i=0..len(a)-1)}.
444 @arg xs: Iterable (each C{scalar} or an L{Fsum} or
445 L{Fsum2Tuple} instance).
446 @arg ys: Iterable (each C{scalar} or an L{Fsum} or
447 L{Fsum2Tuple} instance).
448 @arg zs: Iterable (each C{scalar} or an L{Fsum} or
449 L{Fsum2Tuple} instance).
450 @kwarg start: Optional bias (C{scalar} or an L{Fsum}
451 or L{Fsum2Tuple}).
453 @return: Dot product (C{float}).
455 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})}
456 and/or C{len(B{zs})}.
458 @raise OverflowError: Partial C{2sum} overflow.
459 '''
460 def _mul3(xs, ys, zs, s, p):
461 if s:
462 yield s
463 if p:
464 yield _1_0
465 _F = Fsum
466 for x, y, z in zip(xs, ys, zs):
467 yield (_F(x) * y) * z
468 if p:
469 yield _N_1_0
471 n = len(xs)
472 if not n == len(ys) == len(zs):
473 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))
475 return fsum(_mul3(xs, ys, zs, start, n < 4))
478def fhorner(x, *cs):
479 '''Evaluate the polynomial M{sum(cs[i] * x**i for
480 i=0..len(cs)-1)} using the Horner form.
482 @return: Horner sum (C{float}).
484 @see: Class L{Fhorner} for further details.
485 '''
486 H = Fhorner(x, *cs)
487 return float(H)
490def fidw(xs, ds, beta=2):
491 '''Interpolate using U{Inverse Distance Weighting
492 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).
494 @arg xs: Known values (each C{scalar} or an L{Fsum} or
495 L{Fsum2Tuple} instance).
496 @arg ds: Non-negative distances (each C{scalar} or an L{Fsum}
497 or L{Fsum2Tuple} instance).
498 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).
500 @return: Interpolated value C{x} (C{float}).
502 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.
504 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.
506 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or
507 weighted B{C{ds}} below L{EPS}.
509 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.
510 '''
511 n, xs = len2(xs)
512 if n > 1:
513 b = -Int_(beta=beta, low=0, high=3)
514 if b < 0:
515 try: # weighted
516 _F = Fsum
517 W = _F()
518 X = _F()
519 for i, d in enumerate(_xiterable(ds)):
520 x = xs[i]
521 D = _F(d)
522 if D < EPS0:
523 if D < 0:
524 raise ValueError(_negative_)
525 x = float(x)
526 i = n
527 break
528 if D.fpow(b):
529 W += D
530 X += D.fmul(x)
531 else:
532 x = X.fover(W, raiser=False)
533 i += 1 # len(xs) >= len(ds)
534 except IndexError:
535 i += 1 # len(xs) < i < len(ds)
536 except Exception as X:
537 _I = Fmt.INDEX
538 raise _xError(X, _I(xs=i), x, _I(ds=i), d)
539 else: # b == 0
540 x = fsum(xs) / n # fmean(xs)
541 i = n
542 elif n:
543 x = float(xs[0])
544 i = n
545 else:
546 x = _0_0
547 i, _ = len2(ds)
548 if i != n:
549 raise LenError(fidw, xs=n, ds=i)
550 return x
553def fmean(xs):
554 '''Compute the accurate mean M{sum(xs) / len(xs)}.
556 @arg xs: Values (C{scalar} or L{Fsum} instances).
558 @return: Mean value (C{float}).
560 @raise LenError: No B{C{xs}} values.
562 @raise OverflowError: Partial C{2sum} overflow.
563 '''
564 n, xs = len2(xs)
565 if n < 1:
566 raise LenError(fmean, xs=xs)
567 return Fsum(*xs).fover(n) if n > 1 else _2float(index=0, xs=xs[0])
570def fmean_(*xs):
571 '''Compute the accurate mean M{sum(xs) / len(xs)}.
573 @see: Function L{fmean} for further details.
574 '''
575 return fmean(xs)
578def fpolynomial(x, *cs, **over):
579 '''Evaluate the polynomial M{sum(cs[i] * x**i for
580 i=0..len(cs)) [/ over]}.
582 @kwarg over: Optional final, I{non-zero} divisor (C{scalar}).
584 @return: Polynomial value (C{float}).
586 @see: Class L{Fpolynomial} for further details.
587 '''
588 P = Fpolynomial(x, *cs)
589 d = _xkwds_get1(over, over=0) if over else 0
590 return P.fover(d) if d else float(P)
593def fpowers(x, n, alts=0):
594 '''Return a series of powers M{[x**i for i=1..n]}.
596 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
597 @arg n: Highest exponent (C{int}).
598 @kwarg alts: Only alternating powers, starting with this
599 exponent (C{int}).
601 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).
603 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.
605 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.
606 '''
607 if not isint(n):
608 raise _IsnotError(int.__name__, n=n)
609 elif n < 1:
610 raise _ValueError(n=n)
612 p = x if isint(x) or _isFsumTuple(x) else _2float(x=x)
613 ps = tuple(_powers(p, n))
615 if alts > 0: # x**2, x**4, ...
616 # ps[alts-1::2] chokes PyChecker
617 ps = ps[slice(alts-1, None, 2)]
619 return ps
622try:
623 from math import prod as fprod # Python 3.8
624except ImportError:
626 def fprod(xs, start=1):
627 '''Iterable product, like C{math.prod} or C{numpy.prod}.
629 @arg xs: Iterable of values to be multiplied (each
630 C{scalar} or an L{Fsum}).
631 @kwarg start: Initial value, also the value returned
632 for an empty B{C{xs}} (C{scalar}).
634 @return: The product (C{float} or an L{Fsum}).
636 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
637 numpy/reference/generated/numpy.prod.html>}.
638 '''
639 return freduce(_operator.mul, xs, start)
642def frandoms(n, seeded=None):
643 '''Generate C{n} (long) lists of random C{floats}.
645 @arg n: Number of lists to generate (C{int}, non-negative).
646 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or
647 if C{True}, seed using today's C{year-day}.
649 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/
650 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.
651 '''
652 from random import gauss, random, seed, shuffle
654 if seeded is None:
655 pass
656 elif seeded and isbool(seeded):
657 from time import localtime
658 seed(localtime().tm_yday)
659 elif isscalar(seeded):
660 seed(seeded)
662 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 7
663 for _ in range(n):
664 s = 0
665 t = list(c)
666 _a = t.append
667 for _ in range(n * 8):
668 v = gauss(0, random())**7 - s
669 _a(v)
670 s += v
671 shuffle(t)
672 yield t
675def frange(start, number, step=1):
676 '''Generate a range of C{float}s.
678 @arg start: First value (C{float}).
679 @arg number: The number of C{float}s to generate (C{int}).
680 @kwarg step: Increment value (C{float}).
682 @return: A generator (C{float}s).
684 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
685 numpy/reference/generated/numpy.arange.html>}.
686 '''
687 if not isint(number):
688 raise _IsnotError(int.__name__, number=number)
689 for i in range(number):
690 yield start + (step * i)
693try:
694 from functools import reduce as freduce
695except ImportError:
696 try:
697 freduce = reduce # PYCHOK expected
698 except NameError: # Python 3+
700 def freduce(f, xs, *start):
701 '''For missing C{functools.reduce}.
702 '''
703 if start:
704 r = v = start[0]
705 else:
706 r, v = 0, MISSING
707 for v in xs:
708 r = f(r, v)
709 if v is MISSING:
710 raise _TypeError(xs=(), start=MISSING)
711 return r
714def fremainder(x, y):
715 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.
717 @arg x: Numerator (C{scalar}).
718 @arg y: Modulus, denominator (C{scalar}).
720 @return: Remainder (C{scalar}, preserving signed
721 0.0) or C{NAN} for any non-finite B{C{x}}.
723 @raise ValueError: Infinite or near-zero B{C{y}}.
725 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/
726 project/geographiclib/>} and Python 3.7+
727 U{math.remainder<https://docs.Python.org/3/
728 library/math.html#math.remainder>}.
729 '''
730 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and
731 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native
732 # fmod( 0, 360) == 0.0
733 # fmod( 360, 360) == 0.0
734 # fmod(-0, 360) == 0.0
735 # fmod(-0.0, 360) == -0.0
736 # fmod(-360, 360) == -0.0
737 # however, using the % operator ...
738 # 0 % 360 == 0
739 # 360 % 360 == 0
740 # 360.0 % 360 == 0.0
741 # -0 % 360 == 0
742 # -360 % 360 == 0 == (-360) % 360
743 # -0.0 % 360 == 0.0 == (-0.0) % 360
744 # -360.0 % 360 == 0.0 == (-360.0) % 360
746 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)
747 # == +0.0. This fixes this bug. See also Math::AngNormalize
748 # in the C++ library, Math.sincosd has a similar fix.
749 if _isfinite(x):
750 try:
751 r = remainder(x, y) if x else x
752 except Exception as e:
753 raise _xError(e, unstr(fremainder, x, y))
754 else: # handle x INF and NINF as NAN
755 r = NAN
756 return r
759if _sys_version_info2 < (3, 8): # PYCHOK no cover
760 from math import hypot # OK in Python 3.7-
762 def hypot_(*xs):
763 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.
765 Similar to Python 3.8+ n-dimension U{math.hypot
766 <https://docs.Python.org/3.8/library/math.html#math.hypot>},
767 but exceptions, C{nan} and C{infinite} values are
768 handled differently.
770 @arg xs: X arguments (C{scalar}s), all positional.
772 @return: Norm (C{float}).
774 @raise OverflowError: Partial C{2sum} overflow.
776 @raise ValueError: Invalid or no B{C{xs}} values.
778 @note: The Python 3.8+ Euclidian distance U{math.dist
779 <https://docs.Python.org/3.8/library/math.html#math.dist>}
780 between 2 I{n}-dimensional points I{p1} and I{p2} can be
781 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},
782 provided I{p1} and I{p2} have the same, non-zero length I{n}.
783 '''
784 return float(Fhypot(*xs, raiser=False))
786elif _sys_version_info2 < (3, 10):
787 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see
788 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},
789 # U{cffk<https://Bugs.Python.org/issue43088>} and module
790 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}
792 def hypot(x, y):
793 '''Compute the norm M{sqrt(x**2 + y**2)}.
795 @arg x: X argument (C{scalar}).
796 @arg y: Y argument (C{scalar}).
798 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).
799 '''
800 return float(Fhypot(x, y, raiser=False))
802 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9
803else:
804 from math import hypot # PYCHOK in Python 3.10+
805 hypot_ = hypot
808def hypot1(x):
809 '''Compute the norm M{sqrt(1 + x**2)}.
811 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
813 @return: Norm (C{float}).
814 '''
815 if _isFsumTuple(x):
816 h = float(Fhypot(_1_0, x)) if x else _1_0
817 else:
818 h = hypot(_1_0, x) if x else _1_0
819 return h
822def hypot2(x, y):
823 '''Compute the I{squared} norm M{x**2 + y**2}.
825 @arg x: X (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
826 @arg y: Y (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
828 @return: C{B{x}**2 + B{y}**2} (C{float}).
829 '''
830 x, y = map1(abs, x, y) # NOT fabs!
831 if y > x:
832 x, y = y, x
833 if x:
834 h2 = x**2
835 if y:
836 h2 *= (y / x)**2 + _1_0
837 h2 = float(h2)
838 else:
839 h2 = _0_0
840 return h2
843def hypot2_(*xs):
844 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.
846 @arg xs: Components (each C{scalar} or an L{Fsum} or
847 L{Fsum2Tuple} instance), all positional.
849 @return: Squared norm (C{float}).
851 @see: Class L{Fpowers} for further details.
852 '''
853 h2 = float(max(map(abs, xs))) if xs else _0_0
854 if h2:
855 _h = _1_0 / h2
856 h2 = Fpowers(2, *((x * _h) for x in xs))
857 h2 = h2.fover(_h**2)
858 return h2
861def _map_mul(xs, ys, where):
862 '''(INTERNAL) Yield each B{C{x * y}}.
863 '''
864 n = len(ys)
865 if len(xs) != n: # PYCHOK no cover
866 raise LenError(where, xs=len(xs), ys=n)
867 return _1map_mul(xs, ys) if n < 4 else map(
868 _operator.mul, map(Fsum, xs), ys)
871def _1map_mul(xs, ys):
872 '''(INTERNAL) Yield each B{C{x * y}}, 1-primed.
873 '''
874 return _1primed(map(_operator.mul, map(Fsum, xs), ys))
877def norm2(x, y):
878 '''Normalize a 2-dimensional vector.
880 @arg x: X component (C{scalar}).
881 @arg y: Y component (C{scalar}).
883 @return: 2-Tuple C{(x, y)}, normalized.
885 @raise ValueError: Invalid B{C{x}} or B{C{y}}
886 or zero norm.
887 '''
888 try:
889 h = hypot(x, y)
890 if h:
891 x, y = (x / h), (y / h)
892 else:
893 x = _copysign_0_0(x) # pass?
894 y = _copysign_0_0(y)
895 except Exception as e:
896 raise _xError(e, x=x, y=y, h=h)
897 return x, y
900def norm_(*xs):
901 '''Normalize all n-dimensional vector components.
903 @arg xs: Components (C{scalar}s), all positional.
905 @return: Yield each component, normalized.
907 @raise ValueError: Invalid or insufficent B{C{xs}}
908 or zero norm.
909 '''
910 try:
911 i = x = h = None
912 h = hypot_(*xs)
913 _h = (_1_0 / h) if h else _0_0
914 for i, x in enumerate(xs):
915 yield x * _h
916 except Exception as X:
917 raise _xError(X, Fmt.SQUARE(xs=i), x, h=h)
920def _powers(x, n):
921 '''(INTERNAL) Yield C{x**i for i=1..n}.
922 '''
923 p = 1 # type(p) == type(x)
924 for _ in range(n):
925 p *= x
926 yield p
929def _root(x, p, where):
930 '''(INTERNAL) Raise C{x} to power C{0 < p < 1}.
931 '''
932 try:
933 if x > 0:
934 return Fsum(x).fpow(p).as_iscalar
935 elif x < 0:
936 raise ValueError(_negative_)
937 except Exception as X:
938 raise _xError(X, unstr(where, x))
939 return _0_0
942def sqrt0(x, Error=None):
943 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},
944 preserving C{type(B{x})}.
946 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
947 @kwarg Error: Error to raise for negative B{C{x}}.
949 @return: Square root (C{float} or L{Fsum}) or C{0.0}.
951 @raise TypeeError: Invalid B{C{x}}.
953 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}
954 returns C{0.0}.
955 '''
956 if Error and x < 0:
957 raise Error(unstr(sqrt0, x))
958 return _root(x, _0_5, sqrt0) if x > EPS02 else (_0_0 if x < EPS02 else EPS0)
961def sqrt3(x):
962 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},
963 preserving C{type(B{x})}.
965 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
967 @return: Square root I{cubed} (C{float} or L{Fsum}).
969 @raise TypeeError: Invalid B{C{x}}.
971 @raise ValueError: Negative B{C{x}}.
973 @see: Functions L{cbrt} and L{cbrt2}.
974 '''
975 return _root(x, _1_5, sqrt3)
978def sqrt_a(h, b):
979 '''Compute C{I{a}} side of a right-angled triangle from
980 C{sqrt(B{h}**2 - B{b}**2)}.
982 @arg h: Hypotenuse or outer annulus radius (C{scalar}).
983 @arg b: Triangle side or inner annulus radius (C{scalar}).
985 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).
987 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.
989 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.
991 @see: Inner tangent chord B{I{d}} of an U{annulus
992 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}
993 and function U{annulus_area<https://People.SC.FSU.edu/
994 ~jburkardt/py_src/geometry/geometry.py>}.
995 '''
996 try:
997 if not (_isHeight(h) and _isRadius(b)):
998 raise TypeError(_not_scalar_)
999 c = fabs(h)
1000 if c > EPS0:
1001 s = _1_0 - (b / c)**2
1002 if s < 0:
1003 raise ValueError(_h_lt_b_)
1004 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)
1005 else: # PYCHOK no cover
1006 b = fabs(b)
1007 d = c - b
1008 if d < 0:
1009 raise ValueError(_h_lt_b_)
1010 d *= c + b
1011 a = sqrt(d) if d else _0_0
1012 except Exception as x:
1013 raise _xError(x, h=h, b=b)
1014 return copysign0(a, h)
1017def zcrt(x):
1018 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},
1019 preserving C{type(B{x})}.
1021 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
1023 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).
1025 @see: Functions L{bqrt} and L{zqrt}.
1027 @raise TypeeError: Invalid B{C{x}}.
1029 @raise ValueError: Negative B{C{x}}.
1030 '''
1031 return _root(x, _1_6th, zcrt)
1034def zqrt(x):
1035 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,
1036 M{x**(1 / 8)}, preserving C{type(B{x})}.
1038 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
1040 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).
1042 @see: Functions L{bqrt} and L{zcrt}.
1044 @raise TypeeError: Invalid B{C{x}}.
1046 @raise ValueError: Negative B{C{x}}.
1047 '''
1048 return _root(x, _0_125, zqrt)
1050# **) MIT License
1051#
1052# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1053#
1054# Permission is hereby granted, free of charge, to any person obtaining a
1055# copy of this software and associated documentation files (the "Software"),
1056# to deal in the Software without restriction, including without limitation
1057# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1058# and/or sell copies of the Software, and to permit persons to whom the
1059# Software is furnished to do so, subject to the following conditions:
1060#
1061# The above copyright notice and this permission notice shall be included
1062# in all copies or substantial portions of the Software.
1063#
1064# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1065# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1066# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1067# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1068# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1069# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1070# OTHER DEALINGS IN THE SOFTWARE.