Coverage for pygeodesy/fmath.py: 90%
322 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-06 16:50 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-06 16:50 -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
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_get, _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.06'
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
43 L{Fsum2Tuple} instance).
44 @arg b: Other values (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
45 instance), all positional.
46 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}
47 threshold, see L{Fsum<Fsum.__init__>}.
49 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.
51 @raise OverflowError: Partial C{2sum} overflow.
53 @raise TypeError: Invalid B{C{x}}.
55 @raise ValueError: Non-finite B{C{x}}.
57 @see: Function L{fdot} and method L{Fsum.fadd}.
58 '''
59 Fsum.__init__(self, **name_RESIDUAL)
60 self.fadd(_map_mul(a, b, Fdot))
63class Fhorner(Fsum):
64 '''Precision polynomial evaluation using the Horner form.
65 '''
66 def __init__(self, x, *cs, **name_RESIDUAL):
67 '''New L{Fhorner} evaluation of polynomial M{sum(cs[i] * x**i for
68 i=0..len(cs)-1)}.
70 @arg x: Polynomial argument (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
71 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or
72 L{Fsum2Tuple} instance), all positional.
73 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}
74 threshold, see L{Fsum<Fsum.__init__>}.
76 @raise OverflowError: Partial C{2sum} overflow.
78 @raise TypeError: Invalid B{C{x}}.
80 @raise ValueError: Non-finite B{C{x}}.
82 @see: Function L{fhorner} and methods L{Fsum.fadd} and L{Fsum.fmul}.
83 '''
84 Fsum.__init__(self, **name_RESIDUAL)
85 if cs:
86 if _isFsumTuple(x):
87 _mul = self._mul_Fsum
88 else:
89 _mul = self._mul_scalar
90 x = _2float(x=x)
91 op = Fhorner.__name__
92 if len(cs) > 1 and x:
93 for c in reversed(cs):
94 self._fset_ps(_mul(x, op))
95 self._fadd(c, op, up=False)
96 self._update()
97 else: # x == 0
98 self._fadd(cs[0], op)
99 else:
100 self._fset_ps(_0_0)
103class Fhypot(Fsum):
104 '''Precision summation and hypotenuse, default C{root=2}.
105 '''
106 def __init__(self, *xs, **root_name_RESIDUAL_raiser):
107 '''New L{Fhypot} hypotenuse of (the I{root} of) several components
108 (raised to the power I{root}).
110 @arg xs: Components (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
111 instance), all positional.
112 @kwarg root_name_RESIDUAL_raiser: Optional, exponent and C{B{root}=2}
113 order, C{B{name}=NN}, C{B{RESIDUAL}=0.0} threshold and
114 C{B{raiser}=True}, see class L{Fsum<Fsum.__init__>} and
115 method L{root<Fsum.root>}.
116 '''
117 r = None # _xkwds_pop2 error
118 try:
119 r, kwds = _xkwds_pop2(root_name_RESIDUAL_raiser, root=2)
120 r, kwds = _xkwds_pop2(kwds, power=r) # for backward compatibility
121 raiser = _Fsum__init__(self, **kwds)
122 if xs:
123 self._facc_power(r, xs, Fhypot, **raiser)
124 self._fset(self.root(r, **raiser))
125 except Exception as X:
126 raise self._ErrorXs(X, xs, root=r)
129class Fpolynomial(Fsum):
130 '''Precision polynomial evaluation.
131 '''
132 def __init__(self, x, *cs, **name_RESIDUAL):
133 '''New L{Fpolynomial} evaluation of the polynomial
134 M{sum(cs[i] * x**i for i=0..len(cs)-1)}.
136 @arg x: Polynomial argument (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
137 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or
138 L{Fsum2Tuple} instance), all positional.
139 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}
140 threshold, see L{Fsum<Fsum.__init__>}.
142 @raise OverflowError: Partial C{2sum} overflow.
144 @raise TypeError: Invalid B{C{x}}.
146 @raise ValueError: Non-finite B{C{x}}.
148 @see: Class L{Fhorner}, function L{fpolynomial} and method L{Fsum.fadd}.
149 '''
150 Fsum.__init__(self, *cs[:1], **name_RESIDUAL)
151 n = len(cs) - 1
152 if n > 0:
153 self.fadd(_1map_mul(cs[1:], _powers(x, n)))
154 elif n < 0:
155 self._fset_ps(_0_0)
158class Fpowers(Fsum):
159 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.
160 '''
161 def __init__(self, power, *xs, **name_RESIDUAL_raiser):
162 '''New L{Fpowers} sum of (the I{power} of) several bases.
164 @arg power: The exponent (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
165 @arg xs: One or more bases (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
166 instance), all positional.
167 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN}, C{B{RESIDUAL}=0.0}
168 threshold and C{B{raiser}=True}, see L{Fsum<Fsum.__init__>}
169 and L{fpow<Fsum.fpow>}.
170 '''
171 try:
172 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)
173 if xs:
174 self._facc_power(power, xs, Fpowers, **raiser) # x**0 == 1
175 except Exception as X:
176 raise self._ErrorXs(X, xs, power=power)
179class Froot(Fsum):
180 '''The root of a precision summation.
181 '''
182 def __init__(self, root, *xs, **name_RESIDUAL_raiser):
183 '''New L{Froot} root of a precision sum.
185 @arg root: The order (C{scalar} or an L{Fsum} or L{Fsum2Tuple}), non-zero.
186 @arg xs: Items to summate (each a C{scalar} or an L{Fsum} or L{Fsum2Tuple}
187 instance), all positional.
188 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN}, C{B{RESIDUAL}=0.0}
189 threshold and C{B{raiser}=True}, see L{Fsum<Fsum.__init__>}
190 and L{fpow<Fsum.fpow>}.
191 '''
192 try:
193 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)
194 if xs:
195 self.fadd(xs)
196 self._fset(self.root(root, **raiser))
197 except Exception as X:
198 raise self._ErrorXs(X, xs, root=root)
201class Fcbrt(Froot):
202 '''Cubic root of a precision summation.
203 '''
204 def __init__(self, *xs, **name_RESIDUAL_raiser):
205 '''New L{Fcbrt} cubic root of a precision sum.
207 @see: Class L{Froot} for further details.
208 '''
209 Froot.__init__(self, 3, *xs, **name_RESIDUAL_raiser)
212class Fsqrt(Froot):
213 '''Square root of a precision summation.
214 '''
215 def __init__(self, *xs, **name_RESIDUAL_raiser):
216 '''New L{Fsqrt} square root of a precision sum.
218 @see: Class L{Froot} for further details.
219 '''
220 Froot.__init__(self, 2, *xs, **name_RESIDUAL_raiser)
223def _Fsum__init__(inst, raiser=MISSING, **name_RESIDUAL):
224 '''(INTERNAL) Init an C{F...} instance above.
225 '''
226 Fsum.__init__(inst, **name_RESIDUAL) # PYCHOK self
227 inst._fset_ps(_0_0)
228 return {} if raiser is MISSING else dict(raiser=raiser)
231def bqrt(x):
232 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)},
233 preserving C{type(B{x})}.
235 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
237 @return: I{Quartic} root (C{float} or an L{Fsum}).
239 @raise TypeeError: Invalid B{C{x}}.
241 @raise ValueError: Negative B{C{x}}.
243 @see: Functions L{zcrt} and L{zqrt}.
244 '''
245 return _root(x, _0_25, bqrt)
248try:
249 from math import cbrt as _cbrt # Python 3.11+
251except ImportError: # Python 3.10-
253 def _cbrt(x):
254 '''(INTERNAL) Compute the I{signed}, cube root M{x**(1/3)}.
255 '''
256 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>
257 # simpler and more accurate than Ken Turkowski's CubeRoot, see
258 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>
259 return _copysign(pow(fabs(x), _1_3rd), x) # to avoid complex
262def cbrt(x):
263 '''Compute the cube root M{x**(1/3)}, preserving C{type(B{x})}.
265 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
267 @return: Cubic root (C{float} or L{Fsum}).
269 @see: Functions L{cbrt2} and L{sqrt3}.
270 '''
271 if _isFsumTuple(x):
272 r = abs(x).fpow(_1_3rd)
273 if x.signOf() < 0:
274 r = -r
275 else:
276 r = _cbrt(x)
277 return r # cbrt(-0.0) == -0.0
280def cbrt2(x): # PYCHOK attr
281 '''Compute the cube root I{squared} M{x**(2/3)}, preserving C{type(B{x})}.
283 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
285 @return: Cube root I{squared} (C{float} or L{Fsum}).
287 @see: Functions L{cbrt} and L{sqrt3}.
288 '''
289 return abs(x).fpow(_2_3rd) if _isFsumTuple(x) else _cbrt(x**2)
292def euclid(x, y):
293 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by
294 M{max(abs(x), abs(y)) + min(abs(x), abs(y)) * 0.4142...}.
296 @arg x: X component (C{scalar} or L{Fsum} instance).
297 @arg y: Y component (C{scalar} or L{Fsum} instance).
299 @return: Appoximate norm (C{float} or L{Fsum}).
301 @see: Function L{euclid_}.
302 '''
303 x, y = abs(x), abs(y) # NOT fabs!
304 if y > x:
305 x, y = y, x
306 return x + y * _0_4142 # XXX * _0_5 before 20.10.02
309def euclid_(*xs):
310 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))} by
311 cascaded L{euclid}.
313 @arg xs: X arguments (each C{scalar} or an L{Fsum}
314 instance), all positional.
316 @return: Appoximate norm (C{float} or L{Fsum}).
318 @see: Function L{euclid}.
319 '''
320 e = _0_0
321 for x in sorted(map(abs, xs)): # NOT fabs, reverse=True!
322 # e = euclid(x, e)
323 if e < x:
324 e, x = x, e
325 if x:
326 e += x * _0_4142
327 return e
330def facos1(x):
331 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}.
333 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/
334 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.
335 '''
336 a = fabs(x)
337 if a < EPS0:
338 r = PI_2
339 elif a < EPS1:
340 H = Fhorner(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)
341 r = float(H * sqrt(_1_0 - a))
342 if x < 0:
343 r = PI - r
344 else:
345 r = PI if x < 0 else _0_0
346 return r
349def fasin1(x): # PYCHOK no cover
350 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}.
352 @see: L{facos1}.
353 '''
354 return PI_2 - facos1(x)
357def fatan(x):
358 '''Fast approximation of C{atan(B{x})}.
359 '''
360 a = fabs(x)
361 if a < _1_0:
362 r = fatan1(a) if a else _0_0
363 elif a > _1_0:
364 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)
365 else:
366 r = PI_4
367 if x < 0: # copysign0(r, x)
368 r = -r
369 return r
372def fatan1(x):
373 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} <= 1}, I{unchecked}.
375 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/
376 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations
377 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/
378 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},
379 IEEE Signal Processing Magazine, 111, May 2006.
380 '''
381 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1
382 # PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x - 1
383 # x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))
384 H = Fhorner(x, _0_0, 1.0300981634, -0.1784, -0.0663)
385 return float(H)
388def fatan2(y, x):
389 '''Fast approximation of C{atan2(B{y}, B{x})}.
391 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/
392 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}
393 and L{fatan1}.
394 '''
395 a, b = fabs(x), fabs(y)
396 if b > a:
397 r = (PI_2 - fatan1(a / b)) if a else PI_2
398 elif a > b:
399 r = fatan1(b / a) if b else _0_0
400 elif a: # a == b != 0
401 r = PI_4
402 else: # a == b == 0
403 return _0_0
404 if x < 0:
405 r = PI - r
406 if y < 0: # copysign0(r, y)
407 r = -r
408 return r
411def favg(a, b, f=_0_5):
412 '''Return the precision average of two values.
414 @arg a: One (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
415 @arg b: Other (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
416 @kwarg f: Optional fraction (C{float}).
418 @return: M{a + f * (b - a)} (C{float}).
419 '''
420# @raise ValueError: Fraction out of range.
421# '''
422# if not 0 <= f <= 1: # XXX restrict fraction?
423# raise _ValueError(fraction=f)
424 # a + f * (b - a) == a * (1 - f) + b * f
425 return fsum1_(a, a * (-f), b * f)
428def fdot(a, *b):
429 '''Return the precision dot product M{sum(a[i] * b[i] for
430 i=0..len(a))}.
432 @arg a: Iterable of values (each C{scalar}).
433 @arg b: Other values (each C{scalar}), all positional.
435 @return: Dot product (C{float}).
437 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.
439 @see: Class L{Fdot} and U{Algorithm 5.10 B{DotK}
440 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.
441 '''
442 return fsum(_map_mul(a, b, fdot))
445def fdot3(xs, ys, zs, start=0):
446 '''Return the precision dot product M{start +
447 sum(a[i] * b[i] * c[i] for i=0..len(a)-1)}.
449 @arg xs: Iterable (each C{scalar} or an L{Fsum} or
450 L{Fsum2Tuple} instance).
451 @arg ys: Iterable (each C{scalar} or an L{Fsum} or
452 L{Fsum2Tuple} instance).
453 @arg zs: Iterable (each C{scalar} or an L{Fsum} or
454 L{Fsum2Tuple} instance).
455 @kwarg start: Optional bias (C{scalar} or an L{Fsum}
456 or L{Fsum2Tuple}).
458 @return: Dot product (C{float}).
460 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})}
461 and/or C{len(B{zs})}.
463 @raise OverflowError: Partial C{2sum} overflow.
464 '''
465 def _mul3(xs, ys, zs, s, p):
466 if s:
467 yield s
468 if p:
469 yield _1_0
470 _F = Fsum
471 for x, y, z in zip(xs, ys, zs):
472 yield (_F(x) * y) * z
473 if p:
474 yield _N_1_0
476 n = len(xs)
477 if not n == len(ys) == len(zs):
478 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))
480 return fsum(_mul3(xs, ys, zs, start, n < 4))
483def fhorner(x, *cs):
484 '''Evaluate the polynomial M{sum(cs[i] * x**i for
485 i=0..len(cs)-1)} using the Horner form.
487 @return: Horner sum (C{float}).
489 @see: Class L{Fhorner} for further details.
490 '''
491 H = Fhorner(x, *cs)
492 return float(H)
495def fidw(xs, ds, beta=2):
496 '''Interpolate using U{Inverse Distance Weighting
497 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).
499 @arg xs: Known values (each C{scalar} or an L{Fsum} or
500 L{Fsum2Tuple} instance).
501 @arg ds: Non-negative distances (each C{scalar} or an L{Fsum}
502 or L{Fsum2Tuple} instance).
503 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).
505 @return: Interpolated value C{x} (C{float}).
507 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.
509 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.
511 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or
512 weighted B{C{ds}} below L{EPS}.
514 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.
515 '''
516 n, xs = len2(xs)
517 if n > 1:
518 b = -Int_(beta=beta, low=0, high=3)
519 if b < 0:
520 try: # weighted
521 _F = Fsum
522 W = _F()
523 X = _F()
524 for i, d in enumerate(ds):
525 x = xs[i]
526 if d < EPS0:
527 if d < 0:
528 raise ValueError(_negative_)
529 x = float(x)
530 i = n
531 break
532 D = _F(d).fpow(b)
533 W += D
534 X += D.fmul(x)
535 else:
536 x = X.fover(W, raiser=False)
537 i += 1 # len(xs) >= len(ds)
538 except IndexError:
539 i += 1 # len(xs) < i < len(ds)
540 except Exception as X:
541 _I = Fmt.INDEX
542 raise _xError(X, _I(ds=i), d, _I(xs=i), x)
543 else: # b == 0
544 x = fsum(xs) / n # fmean(xs)
545 i = n
546 elif n:
547 x = float(xs[0])
548 i = n
549 else:
550 x = _0_0
551 i, _ = len2(ds)
552 if i != n:
553 raise LenError(fidw, xs=n, ds=i)
554 return x
557def fmean(xs):
558 '''Compute the accurate mean M{sum(xs) / len(xs)}.
560 @arg xs: Values (C{scalar} or L{Fsum} instances).
562 @return: Mean value (C{float}).
564 @raise LenError: No B{C{xs}} values.
566 @raise OverflowError: Partial C{2sum} overflow.
567 '''
568 n, xs = len2(xs)
569 if n < 1:
570 raise LenError(fmean, xs=xs)
571 return Fsum(*xs).fover(n) if n > 1 else _2float(index=0, xs=xs[0])
574def fmean_(*xs):
575 '''Compute the accurate mean M{sum(xs) / len(xs)}.
577 @see: Function L{fmean} for further details.
578 '''
579 return fmean(xs)
582def fpolynomial(x, *cs, **over):
583 '''Evaluate the polynomial M{sum(cs[i] * x**i for
584 i=0..len(cs)) [/ over]}.
586 @kwarg over: Optional final, I{non-zero} divisor (C{scalar}).
588 @return: Polynomial value (C{float}).
590 @see: Class L{Fpolynomial} for further details.
591 '''
592 P = Fpolynomial(x, *cs)
593 d = _xkwds_get(over, over=0) if over else 0
594 return P.fover(d) if d else float(P)
597def fpowers(x, n, alts=0):
598 '''Return a series of powers M{[x**i for i=1..n]}.
600 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
601 @arg n: Highest exponent (C{int}).
602 @kwarg alts: Only alternating powers, starting with this
603 exponent (C{int}).
605 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).
607 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.
609 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.
610 '''
611 if not isint(n):
612 raise _IsnotError(int.__name__, n=n)
613 elif n < 1:
614 raise _ValueError(n=n)
616 p = x if isint(x) or _isFsumTuple(x) else _2float(x=x)
617 ps = tuple(_powers(p, n))
619 if alts > 0: # x**2, x**4, ...
620 # ps[alts-1::2] chokes PyChecker
621 ps = ps[slice(alts-1, None, 2)]
623 return ps
626try:
627 from math import prod as fprod # Python 3.8
628except ImportError:
630 def fprod(xs, start=1):
631 '''Iterable product, like C{math.prod} or C{numpy.prod}.
633 @arg xs: Terms to be multiplied, an iterable, list,
634 tuple, etc. (C{scalar}s).
635 @kwarg start: Initial term, also the value returned
636 for an empty B{C{xs}} (C{scalar}).
638 @return: The product (C{float}).
640 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
641 numpy/reference/generated/numpy.prod.html>}.
642 '''
643 return freduce(_operator.mul, xs, start)
646def frandoms(n, seeded=None):
647 '''Generate C{n} (long) lists of random C{floats}.
649 @arg n: Number of lists to generate (C{int}, non-negative).
650 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or
651 if C{True}, seed using today's C{year-day}.
653 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/
654 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.
655 '''
656 from random import gauss, random, seed, shuffle
658 if seeded is None:
659 pass
660 elif seeded and isbool(seeded):
661 from time import localtime
662 seed(localtime().tm_yday)
663 elif isscalar(seeded):
664 seed(seeded)
666 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 7
667 for _ in range(n):
668 s = 0
669 t = list(c)
670 _a = t.append
671 for _ in range(n * 8):
672 v = gauss(0, random())**7 - s
673 _a(v)
674 s += v
675 shuffle(t)
676 yield t
679def frange(start, number, step=1):
680 '''Generate a range of C{float}s.
682 @arg start: First value (C{float}).
683 @arg number: The number of C{float}s to generate (C{int}).
684 @kwarg step: Increment value (C{float}).
686 @return: A generator (C{float}s).
688 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
689 numpy/reference/generated/numpy.arange.html>}.
690 '''
691 if not isint(number):
692 raise _IsnotError(int.__name__, number=number)
693 for i in range(number):
694 yield start + (step * i)
697try:
698 from functools import reduce as freduce
699except ImportError:
700 try:
701 freduce = reduce # PYCHOK expected
702 except NameError: # Python 3+
704 def freduce(f, xs, *start):
705 '''For missing C{functools.reduce}.
706 '''
707 if start:
708 r = v = start[0]
709 else:
710 r, v = 0, MISSING
711 for v in xs:
712 r = f(r, v)
713 if v is MISSING:
714 raise _TypeError(xs=(), start=MISSING)
715 return r
718def fremainder(x, y):
719 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.
721 @arg x: Numerator (C{scalar}).
722 @arg y: Modulus, denominator (C{scalar}).
724 @return: Remainder (C{scalar}, preserving signed
725 0.0) or C{NAN} for any non-finite B{C{x}}.
727 @raise ValueError: Infinite or near-zero B{C{y}}.
729 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/
730 project/geographiclib/>} and Python 3.7+
731 U{math.remainder<https://docs.Python.org/3/
732 library/math.html#math.remainder>}.
733 '''
734 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and
735 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native
736 # fmod( 0, 360) == 0.0
737 # fmod( 360, 360) == 0.0
738 # fmod(-0, 360) == 0.0
739 # fmod(-0.0, 360) == -0.0
740 # fmod(-360, 360) == -0.0
741 # however, using the % operator ...
742 # 0 % 360 == 0
743 # 360 % 360 == 0
744 # 360.0 % 360 == 0.0
745 # -0 % 360 == 0
746 # -360 % 360 == 0 == (-360) % 360
747 # -0.0 % 360 == 0.0 == (-0.0) % 360
748 # -360.0 % 360 == 0.0 == (-360.0) % 360
750 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)
751 # == +0.0. This fixes this bug. See also Math::AngNormalize
752 # in the C++ library, Math.sincosd has a similar fix.
753 if _isfinite(x):
754 try:
755 r = remainder(x, y) if x else x
756 except Exception as e:
757 raise _xError(e, unstr(fremainder, x, y))
758 else: # handle x INF and NINF as NAN
759 r = NAN
760 return r
763if _sys_version_info2 < (3, 8): # PYCHOK no cover
764 from math import hypot # OK in Python 3.7-
766 def hypot_(*xs):
767 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.
769 Similar to Python 3.8+ n-dimension U{math.hypot
770 <https://docs.Python.org/3.8/library/math.html#math.hypot>},
771 but exceptions, C{nan} and C{infinite} values are
772 handled differently.
774 @arg xs: X arguments (C{scalar}s), all positional.
776 @return: Norm (C{float}).
778 @raise OverflowError: Partial C{2sum} overflow.
780 @raise ValueError: Invalid or no B{C{xs}} values.
782 @note: The Python 3.8+ Euclidian distance U{math.dist
783 <https://docs.Python.org/3.8/library/math.html#math.dist>}
784 between 2 I{n}-dimensional points I{p1} and I{p2} can be
785 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},
786 provided I{p1} and I{p2} have the same, non-zero length I{n}.
787 '''
788 return float(Fhypot(*xs, raiser=False))
790elif _sys_version_info2 < (3, 10):
791 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see
792 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},
793 # U{cffk<https://Bugs.Python.org/issue43088>} and module
794 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}
796 def hypot(x, y):
797 '''Compute the norm M{sqrt(x**2 + y**2)}.
799 @arg x: X argument (C{scalar}).
800 @arg y: Y argument (C{scalar}).
802 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).
803 '''
804 return float(Fhypot(x, y, raiser=False))
806 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9
807else:
808 from math import hypot # PYCHOK in Python 3.10+
809 hypot_ = hypot
812def hypot1(x):
813 '''Compute the norm M{sqrt(1 + x**2)}.
815 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
817 @return: Norm (C{float}).
818 '''
819 if _isFsumTuple(x):
820 h = float(Fhypot(_1_0, x)) if x else _1_0
821 else:
822 h = hypot(_1_0, x) if x else _1_0
823 return h
826def hypot2(x, y):
827 '''Compute the I{squared} norm M{x**2 + y**2}.
829 @arg x: X (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
830 @arg y: Y (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
832 @return: C{B{x}**2 + B{y}**2} (C{float}).
833 '''
834 x, y = map1(abs, x, y) # NOT fabs!
835 if y > x:
836 x, y = y, x
837 if x:
838 h2 = x**2
839 if y:
840 h2 *= (y / x)**2 + _1_0
841 h2 = float(h2)
842 else:
843 h2 = _0_0
844 return h2
847def hypot2_(*xs):
848 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.
850 @arg xs: Components (each C{scalar} or an L{Fsum} or
851 L{Fsum2Tuple} instance), all positional.
853 @return: Squared norm (C{float}).
855 @see: Class L{Fpowers} for further details.
856 '''
857 h2 = float(max(map(abs, xs))) if xs else _0_0
858 if h2:
859 _h = _1_0 / h2
860 h2 = Fpowers(2, *((x * _h) for x in xs))
861 h2 = h2.fover(_h**2)
862 return h2
865def _map_mul(xs, ys, where):
866 '''(INTERNAL) Yield each B{C{x * y}}.
867 '''
868 n = len(ys)
869 if len(xs) != n: # PYCHOK no cover
870 raise LenError(where, xs=len(xs), ys=n)
871 return _1map_mul(xs, ys) if n < 4 else map(
872 _operator.mul, map(Fsum, xs), ys)
875def _1map_mul(xs, ys):
876 '''(INTERNAL) Yield each B{C{x * y}}, 1-primed.
877 '''
878 return _1primed(map(_operator.mul, map(Fsum, xs), ys))
881def norm2(x, y):
882 '''Normalize a 2-dimensional vector.
884 @arg x: X component (C{scalar}).
885 @arg y: Y component (C{scalar}).
887 @return: 2-Tuple C{(x, y)}, normalized.
889 @raise ValueError: Invalid B{C{x}} or B{C{y}}
890 or zero norm.
891 '''
892 try:
893 h = hypot(x, y)
894 if h:
895 x, y = (x / h), (y / h)
896 else:
897 x = _copysign_0_0(x) # pass?
898 y = _copysign_0_0(y)
899 except Exception as e:
900 raise _xError(e, x=x, y=y, h=h)
901 return x, y
904def norm_(*xs):
905 '''Normalize all n-dimensional vector components.
907 @arg xs: Components (C{scalar}s), all positional.
909 @return: Yield each component, normalized.
911 @raise ValueError: Invalid or insufficent B{C{xs}}
912 or zero norm.
913 '''
914 try:
915 i = x = h = None
916 h = hypot_(*xs)
917 _h = (_1_0 / h) if h else _0_0
918 for i, x in enumerate(xs):
919 yield x * _h
920 except Exception as X:
921 raise _xError(X, Fmt.SQUARE(xs=i), x, h=h)
924def _powers(x, n):
925 '''(INTERNAL) Yield C{x**i for i=1..n}.
926 '''
927 p = 1 # type(p) == type(x)
928 for _ in range(n):
929 p *= x
930 yield p
933def _root(x, p, where):
934 '''(INTERNAL) Raise C{x} to power C{0 < p < 1}.
935 '''
936 try:
937 if x > 0:
938 return Fsum(x).fpow(p).as_iscalar
939 elif x < 0:
940 raise ValueError(_negative_)
941 except Exception as X:
942 raise _xError(X, unstr(where, x))
943 return _0_0
946def sqrt0(x, Error=None):
947 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},
948 preserving C{type(B{x})}.
950 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
951 @kwarg Error: Error to raise for negative B{C{x}}.
953 @return: Square root (C{float} or L{Fsum}) or C{0.0}.
955 @raise TypeeError: Invalid B{C{x}}.
957 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}
958 returns C{0.0}.
959 '''
960 if Error and x < 0:
961 raise Error(unstr(sqrt0, x))
962 return _root(x, _0_5, sqrt0) if x > EPS02 else (_0_0 if x < EPS02 else EPS0)
965def sqrt3(x):
966 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},
967 preserving C{type(B{x})}.
969 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
971 @return: Square root I{cubed} (C{float} or L{Fsum}).
973 @raise TypeeError: Invalid B{C{x}}.
975 @raise ValueError: Negative B{C{x}}.
977 @see: Functions L{cbrt} and L{cbrt2}.
978 '''
979 return _root(x, _1_5, sqrt3)
982def sqrt_a(h, b):
983 '''Compute C{I{a}} side of a right-angled triangle from
984 C{sqrt(B{h}**2 - B{b}**2)}.
986 @arg h: Hypotenuse or outer annulus radius (C{scalar}).
987 @arg b: Triangle side or inner annulus radius (C{scalar}).
989 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).
991 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.
993 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.
995 @see: Inner tangent chord B{I{d}} of an U{annulus
996 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}
997 and function U{annulus_area<https://People.SC.FSU.edu/
998 ~jburkardt/py_src/geometry/geometry.py>}.
999 '''
1000 try:
1001 if not (_isHeight(h) and _isRadius(b)):
1002 raise TypeError(_not_scalar_)
1003 c = fabs(h)
1004 if c > EPS0:
1005 s = _1_0 - (b / c)**2
1006 if s < 0:
1007 raise ValueError(_h_lt_b_)
1008 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)
1009 else: # PYCHOK no cover
1010 b = fabs(b)
1011 d = c - b
1012 if d < 0:
1013 raise ValueError(_h_lt_b_)
1014 d *= c + b
1015 a = sqrt(d) if d else _0_0
1016 except Exception as x:
1017 raise _xError(x, h=h, b=b)
1018 return copysign0(a, h)
1021def zcrt(x):
1022 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},
1023 preserving C{type(B{x})}.
1025 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
1027 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).
1029 @see: Functions L{bqrt} and L{zqrt}.
1031 @raise TypeeError: Invalid B{C{x}}.
1033 @raise ValueError: Negative B{C{x}}.
1034 '''
1035 return _root(x, _1_6th, zcrt)
1038def zqrt(x):
1039 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,
1040 M{x**(1 / 8)}, preserving C{type(B{x})}.
1042 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).
1044 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).
1046 @see: Functions L{bqrt} and L{zcrt}.
1048 @raise TypeeError: Invalid B{C{x}}.
1050 @raise ValueError: Negative B{C{x}}.
1051 '''
1052 return _root(x, _0_125, zqrt)
1054# **) MIT License
1055#
1056# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1057#
1058# Permission is hereby granted, free of charge, to any person obtaining a
1059# copy of this software and associated documentation files (the "Software"),
1060# to deal in the Software without restriction, including without limitation
1061# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1062# and/or sell copies of the Software, and to permit persons to whom the
1063# Software is furnished to do so, subject to the following conditions:
1064#
1065# The above copyright notice and this permission notice shall be included
1066# in all copies or substantial portions of the Software.
1067#
1068# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1069# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1070# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1071# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1072# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1073# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1074# OTHER DEALINGS IN THE SOFTWARE.