Coverage for pygeodesy/fmath.py: 91%
328 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-09-09 13:03 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2025-09-09 13:03 -0400
2# -*- coding: utf-8 -*-
4u'''Utilities for precision floating point summation, multiplication,
5C{fused-multiply-add}, polynomials, roots, etc.
6'''
7# make sure int/int division yields float quotient, see .basics
8from __future__ import division as _; del _ # noqa: E702 ;
10from pygeodesy.basics import _copysign, copysign0, isbool, isint, isodd, \
11 isscalar, len2, map1, _xiterable, typename
12from pygeodesy.constants import EPS0, EPS02, EPS1, NAN, PI, PI_2, PI_4, \
13 _0_0, _0_125, _1_6th, _0_25, _1_3rd, _0_5, _1_0, \
14 _1_5, _copysign_0_0, isfinite, remainder
15from pygeodesy.errors import _IsnotError, LenError, _TypeError, _ValueError, \
16 _xError, _xkwds, _xkwds_pop2, _xsError
17from pygeodesy.fsums import _2float, Fsum, fsum, _isFsum_2Tuple, Fmt, unstr
18# from pygeodesy.internals import typename # from .basics
19from pygeodesy.interns import MISSING, _negative_, _not_scalar_
20from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS
21# from pygeodesy.streprs import Fmt, unstr # from .fsums
22from pygeodesy.units import Int_, _isHeight, _isRadius
24from math import fabs, sqrt # pow
25import operator as _operator # in .datums, .trf, .utm
27__all__ = _ALL_LAZY.fmath
28__version__ = '25.08.31'
30# sqrt(2) - 1 <https://WikiPedia.org/wiki/Square_root_of_2>
31_0_4142 = 0.41421356237309504880 # ~ 3_730_904_090_310_553 / 9_007_199_254_740_992
32_2_3rd = _1_3rd * 2
33_h_lt_b_ = 'abs(h) < abs(b)'
36class Fdot(Fsum):
37 '''Precision dot product.
38 '''
39 def __init__(self, a, *b, **start_name_f2product_nonfinites_RESIDUAL):
40 '''New L{Fdot} precision dot product M{start + sum(a[i] * b[i] for i=0..len(a)-1)}.
42 @arg a: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
43 @arg b: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
44 positional.
45 @kwarg start_name_f2product_nonfinites_RESIDUAL: Optional bias C{B{start}=0}
46 (C{scalar}, an L{Fsum} or L{Fsum2Tuple}), C{B{name}=NN} (C{str})
47 and other settings, see class 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 s, kwds = _xkwds_pop2(start_name_f2product_nonfinites_RESIDUAL, start=_0_0)
60 Fsum.__init__(self, **kwds)
61 self(s)
63 n = len(b)
64 if len(a) != n: # PYCHOK no cover
65 raise LenError(Fdot, a=len(a), b=n)
66 self._facc_dot(n, a, b, **kwds)
69class Fdot_(Fdot): # in .elliptic
70 '''Precision dot product.
71 '''
72 def __init__(self, *xys, **start_name_f2product_nonfinites_RESIDUAL):
73 '''New L{Fdot_} precision dot product M{start + sum(xys[i] * xys[i+1] for i in
74 range(0, len(xys), B{2}))}.
76 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
77 all positional.
79 @see: Class L{Fdot<Fdot.__init__>} for further details.
80 '''
81 if isodd(len(xys)):
82 raise LenError(Fdot_, xys=len(xys))
83 Fdot.__init__(self, xys[0::2], *xys[1::2], **start_name_f2product_nonfinites_RESIDUAL)
86class Fhorner(Fsum):
87 '''Precision polynomial evaluation using the Horner form.
88 '''
89 def __init__(self, x, *cs, **incx_name_f2product_nonfinites_RESIDUAL):
90 '''New L{Fhorner} form evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)}
91 with in- or decreasing exponent M{sum(... i=n..0)}, where C{n = len(cs) - 1}.
93 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
94 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
95 all positional.
96 @kwarg incx_name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str}),
97 C{B{incx}=True} for in-/decreasing exponents (C{bool}) and other
98 settings, see class L{Fsum<Fsum.__init__>}.
100 @raise OverflowError: Partial C{2sum} overflow.
102 @raise TypeError: Invalid B{C{x}}.
104 @raise ValueError: Non-finite B{C{x}}.
106 @see: Function L{fhorner} and methods L{Fsum.fadd} and L{Fsum.fmul}.
107 '''
108 incx, kwds = _xkwds_pop2(incx_name_f2product_nonfinites_RESIDUAL, incx=True)
109 Fsum.__init__(self, **kwds)
110 self._fhorner(x, cs, Fhorner, incx=incx)
113class Fhypot(Fsum):
114 '''Precision summation and hypotenuse, default C{root=2}.
115 '''
116 def __init__(self, *xs, **root_name_f2product_nonfinites_RESIDUAL_raiser):
117 '''New L{Fhypot} hypotenuse of (the I{root} of) several components (raised
118 to the power I{root}).
120 @arg xs: Components (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
121 positional.
122 @kwarg root_name_f2product_nonfinites_RESIDUAL_raiser: Optional, exponent
123 and C{B{root}=2} order (C{scalar}), C{B{name}=NN} (C{str}),
124 C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s and
125 other settings, see class L{Fsum<Fsum.__init__>} and method
126 L{root<Fsum.root>}.
127 '''
128 def _r_X_kwds(power=None, raiser=True, root=2, **kwds):
129 # DEPRECATED keyword argument C{power=2}, use C{root=2}
130 return (root if power is None else power), raiser, kwds
132 r = None # _xkwds_pop2 error
133 try:
134 r, X, kwds = _r_X_kwds(**root_name_f2product_nonfinites_RESIDUAL_raiser)
135 Fsum.__init__(self, **kwds)
136 self(_0_0)
137 if xs:
138 self._facc_power(r, xs, Fhypot, raiser=X)
139 self._fset(self.root(r, raiser=X))
140 except Exception as X:
141 raise self._ErrorXs(X, xs, root=r)
144class Fpolynomial(Fsum):
145 '''Precision polynomial evaluation.
146 '''
147 def __init__(self, x, *cs, **name_f2product_nonfinites_RESIDUAL):
148 '''New L{Fpolynomial} evaluation of the polynomial M{sum(cs[i] * x**i for
149 i=0..len(cs)-1)}.
151 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
152 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
153 all positional.
154 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str})
155 and other settings, see class L{Fsum<Fsum.__init__>}.
157 @raise OverflowError: Partial C{2sum} overflow.
159 @raise TypeError: Invalid B{C{x}}.
161 @raise ValueError: Non-finite B{C{x}}.
163 @see: Class L{Fhorner}, function L{fpolynomial} and method L{Fsum.fadd}.
164 '''
165 Fsum.__init__(self, **name_f2product_nonfinites_RESIDUAL)
166 n = len(cs) - 1
167 self(_0_0 if n < 0 else cs[0])
168 self._facc_dot(n, cs[1:], _powers(x, n), **name_f2product_nonfinites_RESIDUAL)
171class Fpowers(Fsum):
172 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.
173 '''
174 def __init__(self, power, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
175 '''New L{Fpowers} sum of (the I{power} of) several bases.
177 @arg power: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
178 @arg xs: One or more bases (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
179 positional.
180 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}
181 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s
182 and other settings, see class L{Fsum<Fsum.__init__>} and method
183 L{fpow<Fsum.fpow>}.
184 '''
185 try:
186 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)
187 Fsum.__init__(self, **kwds)
188 self(_0_0)
189 if xs:
190 self._facc_power(power, xs, Fpowers, raiser=X) # x**0 == 1
191 except Exception as X:
192 raise self._ErrorXs(X, xs, power=power)
195class Froot(Fsum):
196 '''The root of a precision summation.
197 '''
198 def __init__(self, root, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
199 '''New L{Froot} root of a precision sum.
201 @arg root: The order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}), non-zero.
202 @arg xs: Items to summate (each a C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
203 positional.
204 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}
205 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s
206 and other settings, see class L{Fsum<Fsum.__init__>} and method
207 L{fpow<Fsum.fpow>}.
208 '''
209 try:
210 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)
211 Fsum.__init__(self, **kwds)
212 self(_0_0)
213 if xs:
214 self.fadd(xs)
215 self(self.root(root, raiser=X))
216 except Exception as X:
217 raise self._ErrorXs(X, xs, root=root)
220class Fcbrt(Froot):
221 '''Cubic root of a precision summation.
222 '''
223 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
224 '''New L{Fcbrt} cubic root of a precision sum.
226 @see: Class L{Froot<Froot.__init__>} for further details.
227 '''
228 Froot.__init__(self, 3, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)
231class Fsqrt(Froot):
232 '''Square root of a precision summation.
233 '''
234 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
235 '''New L{Fsqrt} square root of a precision sum.
237 @see: Class L{Froot<Froot.__init__>} for further details.
238 '''
239 Froot.__init__(self, 2, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)
242def bqrt(x):
243 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)},
244 preserving C{type(B{x})}.
246 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
248 @return: I{Quartic} root (C{float} or an L{Fsum}).
250 @raise TypeeError: Invalid B{C{x}}.
252 @raise ValueError: Negative B{C{x}}.
254 @see: Functions L{zcrt} and L{zqrt}.
255 '''
256 return _root(x, _0_25, bqrt)
259try:
260 from math import cbrt as _cbrt # Python 3.11+
262except ImportError: # Python 3.10-
264 def _cbrt(x):
265 '''(INTERNAL) Compute the I{signed}, cube root M{x**(1/3)}.
266 '''
267 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>
268 # simpler and more accurate than Ken Turkowski's CubeRoot, see
269 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>
270 return _copysign(pow(fabs(x), _1_3rd), x) # to avoid complex
273def cbrt(x):
274 '''Compute the cube root M{x**(1/3)}, preserving C{type(B{x})}.
276 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
278 @return: Cubic root (C{float} or L{Fsum}).
280 @see: Functions L{cbrt2} and L{sqrt3}.
281 '''
282 if _isFsum_2Tuple(x):
283 r = abs(x).fpow(_1_3rd)
284 if x.signOf() < 0:
285 r = -r
286 else:
287 r = _cbrt(x)
288 return r # cbrt(-0.0) == -0.0
291def cbrt2(x): # PYCHOK attr
292 '''Compute the cube root I{squared} M{x**(2/3)}, preserving C{type(B{x})}.
294 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
296 @return: Cube root I{squared} (C{float} or L{Fsum}).
298 @see: Functions L{cbrt} and L{sqrt3}.
299 '''
300 return abs(x).fpow(_2_3rd) if _isFsum_2Tuple(x) else _cbrt(x**2)
303def euclid(x, y):
304 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by M{max(abs(x),
305 abs(y)) + min(abs(x), abs(y)) * 0.4142...}.
307 @arg x: X component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
308 @arg y: Y component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
310 @return: Appoximate norm (C{float} or L{Fsum}).
312 @see: Function L{euclid_}.
313 '''
314 x, y = abs(x), abs(y) # NOT fabs!
315 return (x + y * _0_4142) if x > y else \
316 (y + x * _0_4142) # * _0_5 before 20.10.02
319def euclid_(*xs):
320 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))} by cascaded
321 L{euclid}.
323 @arg xs: X arguments (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
324 all positional.
326 @return: Appoximate norm (C{float} or L{Fsum}).
328 @see: Function L{euclid}.
329 '''
330 e = _0_0
331 for x in sorted(map(abs, xs)): # NOT fabs, reverse=True!
332 # e = euclid(x, e)
333 if e < x:
334 e, x = x, e
335 if x:
336 e += x * _0_4142
337 return e
340def facos1(x):
341 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}, scalar.
343 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/
344 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.
345 '''
346 a = fabs(x)
347 if a < EPS0:
348 r = PI_2
349 elif a < EPS1:
350 r = _fast(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)
351 r *= sqrt(_1_0 - a)
352 if x < 0:
353 r = PI - r
354 else:
355 r = PI if x < 0 else _0_0
356 return r
359def fasin1(x): # PYCHOK no cover
360 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}, scalar.
362 @see: L{facos1}.
363 '''
364 return PI_2 - facos1(x)
367def _fast(x, *cs):
368 '''(INTERNAL) Horner form for C{facos1} and C{fatan1}.
369 '''
370 h = 0
371 for c in reversed(cs):
372 h = _fma(x, h, c) if h else c
373 return h
376def fatan(x):
377 '''Fast approximation of C{atan(B{x})}, scalar.
378 '''
379 a = fabs(x)
380 if a < _1_0:
381 r = fatan1(a) if a else _0_0
382 elif a > _1_0:
383 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)
384 else:
385 r = PI_4
386 if x < 0: # copysign0(r, x)
387 r = -r
388 return r
391def fatan1(x):
392 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} < 1}, I{unchecked}.
394 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/
395 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations
396 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/
397 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},
398 IEEE Signal Processing Magazine, 111, May 2006.
399 '''
400 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1
401 # == PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x < 1
402 # == x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))
403 return _fast(x, _0_0, 1.0300981634, -0.1784, -0.0663)
406def fatan2(y, x):
407 '''Fast approximation of C{atan2(B{y}, B{x})}, scalar.
409 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/
410 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}
411 and L{fatan1}.
412 '''
413 a, b = fabs(x), fabs(y)
414 if b > a:
415 r = (PI_2 - fatan1(a / b)) if a else PI_2
416 elif a > b:
417 r = fatan1(b / a) if b else _0_0
418 elif a: # a == b != 0
419 r = PI_4
420 else: # a == b == 0
421 return _0_0
422 if x < 0:
423 r = PI - r
424 if y < 0: # copysign0(r, y)
425 r = -r
426 return r
429def favg(a, b, f=_0_5, nonfinites=True):
430 '''Return the precise average of two values.
432 @arg a: One (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
433 @arg b: Other (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
434 @kwarg f: Optional fraction (C{float}).
435 @kwarg nonfinites: Optional setting, see function L{fma}.
437 @return: M{a + f * (b - a)} (C{float}).
438 '''
439 F = fma(f, (b - a), a, nonfinites=nonfinites)
440 return float(F)
443def fdot(xs, *ys, **start_f2product_nonfinites):
444 '''Return the precision dot product M{start + sum(xs[i] * ys[i] for i in range(len(xs)))}.
446 @arg xs: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
447 @arg ys: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
448 @kwarg start_f2product_nonfinites: Optional bias C{B{start}=0} (C{scalar}, an
449 L{Fsum} or L{Fsum2Tuple}) and settings C{B{f2product}=None} (C{bool})
450 and C{B{nonfinites=True}} (C{bool}), see class L{Fsum<Fsum.__init__>}.
452 @return: Dot product (C{float}).
454 @raise LenError: Unequal C{len(B{xs})} and C{len(B{ys})}.
456 @see: Class L{Fdot}, U{Algorithm 5.10 B{DotK}
457 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} and function
458 C{math.sumprod} in Python 3.12 and later.
459 '''
460 D = Fdot(xs, *ys, **_xkwds(start_f2product_nonfinites, nonfinites=True))
461 return float(D)
464def fdot_(*xys, **start_f2product_nonfinites):
465 '''Return the (precision) dot product M{start + sum(xys[i] * xys[i+1] for i in range(0, len(xys), B{2}))}.
467 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
469 @see: Function L{fdot} for further details.
471 @return: Dot product (C{float}).
472 '''
473 D = Fdot_(*xys, **_xkwds(start_f2product_nonfinites, nonfinites=True))
474 return float(D)
477def fdot3(xs, ys, zs, **start_f2product_nonfinites):
478 '''Return the (precision) dot product M{start + sum(xs[i] * ys[i] * zs[i] for i in range(len(xs)))}.
480 @arg xs: X values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
481 @arg ys: Y values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
482 @arg zs: Z values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
484 @see: Function L{fdot} for further details.
486 @return: Dot product (C{float}).
488 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})} and/or C{len(B{zs})}.
489 '''
490 n = len(xs)
491 if not n == len(ys) == len(zs):
492 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))
494 D = Fdot((), **_xkwds(start_f2product_nonfinites, nonfinites=True))
495 kwds = dict(f2product=D.f2product(), nonfinites=D.nonfinites())
496 _f = Fsum(**kwds)
497 D = D._facc(_f(x).f2mul_(y, z, **kwds) for x, y, z in zip(xs, ys, zs))
498 return float(D)
501def fhorner(x, *cs, **incx):
502 '''Horner form evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)} as
503 in- or decreasing exponent M{sum(... i=n..0)}, where C{n = len(cs) - 1}.
505 @return: Horner sum (C{float}).
507 @see: Class L{Fhorner<Fhorner.__init__>} for further details.
508 '''
509 H = Fhorner(x, *cs, **incx)
510 return float(H)
513def fidw(xs, ds, beta=2):
514 '''Interpolate using U{Inverse Distance Weighting
515 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).
517 @arg xs: Known values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
518 @arg ds: Non-negative distances (each C{scalar}, an L{Fsum} or
519 L{Fsum2Tuple}).
520 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).
522 @return: Interpolated value C{x} (C{float}).
524 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.
526 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.
528 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or
529 weighted B{C{ds}} below L{EPS}.
531 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.
532 '''
533 n, xs = len2(xs)
534 if n > 1:
535 b = -Int_(beta=beta, low=0, high=3)
536 if b < 0:
537 try: # weighted
538 _d, W, X = (Fsum() for _ in range(3))
539 for i, d in enumerate(_xiterable(ds)):
540 x = xs[i]
541 D = _d(d)
542 if D < EPS0:
543 if D < 0:
544 raise ValueError(_negative_)
545 x = float(x)
546 i = n
547 break
548 if D.fpow(b):
549 W += D
550 X += D.fmul(x)
551 else:
552 x = X.fover(W, raiser=False)
553 i += 1 # len(xs) >= len(ds)
554 except IndexError:
555 i += 1 # len(xs) < i < len(ds)
556 except Exception as X:
557 _I = Fmt.INDEX
558 raise _xError(X, _I(xs=i), x,
559 _I(ds=i), d)
560 else: # b == 0
561 x = fsum(xs) / n # fmean(xs)
562 i = n
563 elif n:
564 x = float(xs[0])
565 i = n
566 else:
567 x = _0_0
568 i, _ = len2(ds)
569 if i != n:
570 raise LenError(fidw, xs=n, ds=i)
571 return x
574try:
575 from math import fma as _fma # in .resections
576except ImportError: # PYCHOK DSPACE!
578 def _fma(x, y, z): # no need for accuracy
579 return x * y + z
582def fma(x, y, z, **nonfinites): # **raiser
583 '''Fused-multiply-add, using C{math.fma(x, y, z)} in Python 3.13+
584 or an equivalent implementation.
586 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
587 @arg y: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
588 @arg z: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
589 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False},
590 to override default L{nonfiniterrors}
591 (C{bool}), see method L{Fsum.fma}.
593 @return: C{(x * y) + z} (C{float} or L{Fsum}).
594 '''
595 F, raiser = _Fm2(x, **nonfinites)
596 return F.fma(y, z, **raiser).as_iscalar
599def _Fm2(x, nonfinites=None, **raiser):
600 '''(INTERNAL) Handle C{fma} and C{f2mul} DEPRECATED C{raiser=False}.
601 '''
602 return Fsum(x, nonfinites=nonfinites), raiser
605def fmean(xs):
606 '''Compute the accurate mean M{sum(xs) / len(xs)}.
608 @arg xs: Values (each C{scalar}, or L{Fsum} or L{Fsum2Tuple}).
610 @return: Mean value (C{float}).
612 @raise LenError: No B{C{xs}} values.
614 @raise OverflowError: Partial C{2sum} overflow.
615 '''
616 n, xs = len2(xs)
617 if n < 1:
618 raise LenError(fmean, xs=xs)
619 M = Fsum(*xs, nonfinites=True)
620 return M.fover(n) if n > 1 else float(M)
623def fmean_(*xs, **nonfinites):
624 '''Compute the accurate mean M{sum(xs) / len(xs)}.
626 @see: Function L{fmean} for further details.
627 '''
628 return fmean(xs, **nonfinites)
631def f2mul_(x, *ys, **nonfinites): # **raiser
632 '''Cascaded, accurate multiplication C{B{x} * B{y} * B{y} ...} for all B{C{ys}}.
634 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
635 @arg ys: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
636 positional.
637 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False}, to override default
638 L{nonfiniterrors} (C{bool}), see method L{Fsum.f2mul_}.
640 @return: The cascaded I{TwoProduct} (C{float}, C{int} or L{Fsum}).
642 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
643 '''
644 F, raiser = _Fm2(x, **nonfinites)
645 return F.f2mul_(*ys, **raiser).as_iscalar
648def fpolynomial(x, *cs, **over_f2product_nonfinites):
649 '''Evaluate the polynomial M{sum(cs[i] * x**i for i=0..len(cs)) [/ over]}.
651 @kwarg over_f2product_nonfinites: Optional final divisor C{B{over}=None}
652 (I{non-zero} C{scalar}) and other settings, see class
653 L{Fpolynomial<Fpolynomial.__init__>}.
655 @return: Polynomial value (C{float} or L{Fpolynomial}).
656 '''
657 d, kwds = _xkwds_pop2(over_f2product_nonfinites, over=0)
658 P = Fpolynomial(x, *cs, **kwds)
659 return P.fover(d) if d else float(P)
662def fpowers(x, n, alts=0):
663 '''Return a series of powers M{[x**i for i=1..n]}, note I{1..!}
665 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
666 @arg n: Highest exponent (C{int}).
667 @kwarg alts: Only alternating powers, starting with this
668 exponent (C{int}).
670 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).
672 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.
674 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.
675 '''
676 if not isint(n):
677 raise _IsnotError(typename(int), n=n)
678 elif n < 1:
679 raise _ValueError(n=n)
681 p = x if isscalar(x) or _isFsum_2Tuple(x) else _2float(x=x)
682 ps = tuple(_powers(p, n))
684 if alts > 0: # x**2, x**4, ...
685 # ps[alts-1::2] chokes PyChecker
686 ps = ps[slice(alts-1, None, 2)]
688 return ps
691try:
692 from math import prod as fprod # Python 3.8
693except ImportError:
695 def fprod(xs, start=1):
696 '''Iterable product, like C{math.prod} or C{numpy.prod}.
698 @arg xs: Iterable of values to be multiplied (each
699 C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
700 @kwarg start: Initial value, also the value returned
701 for an empty B{C{xs}} (C{scalar}).
703 @return: The product (C{float} or L{Fsum}).
705 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
706 numpy/reference/generated/numpy.prod.html>}.
707 '''
708 return freduce(_operator.mul, xs, start)
711def frandoms(n, seeded=None):
712 '''Generate C{n} (long) lists of random C{floats}.
714 @arg n: Number of lists to generate (C{int}, non-negative).
715 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or
716 if C{True}, seed using today's C{year-day}.
718 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/
719 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.
720 '''
721 from random import gauss, random, seed, shuffle
723 if seeded is None:
724 pass
725 elif seeded and isbool(seeded):
726 from time import localtime
727 seed(localtime().tm_yday)
728 elif isscalar(seeded):
729 seed(seeded)
731 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 7
732 for _ in range(n):
733 s = 0
734 t = list(c)
735 _a = t.append
736 for _ in range(n * 8):
737 v = gauss(0, random())**7 - s
738 _a(v)
739 s += v
740 shuffle(t)
741 yield t
744def frange(start, number, step=1):
745 '''Generate a range of C{float}s.
747 @arg start: First value (C{float}).
748 @arg number: The number of C{float}s to generate (C{int}).
749 @kwarg step: Increment value (C{float}).
751 @return: A generator (C{float}s).
753 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
754 numpy/reference/generated/numpy.arange.html>}.
755 '''
756 if not isint(number):
757 raise _IsnotError(typename(int), number=number)
758 for i in range(number):
759 yield start + (step * i)
762try:
763 from functools import reduce as freduce
764except ImportError:
765 try:
766 freduce = reduce # PYCHOK expected
767 except NameError: # Python 3+
769 def freduce(f, xs, *start):
770 '''For missing C{functools.reduce}.
771 '''
772 if start:
773 r = v = start[0]
774 else:
775 r, v = 0, MISSING
776 for v in xs:
777 r = f(r, v)
778 if v is MISSING:
779 raise _TypeError(xs=(), start=MISSING)
780 return r
783def fremainder(x, y):
784 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.
786 @arg x: Numerator (C{scalar}).
787 @arg y: Modulus, denominator (C{scalar}).
789 @return: Remainder (C{scalar}, preserving signed
790 0.0) or C{NAN} for any non-finite B{C{x}}.
792 @raise ValueError: Infinite or near-zero B{C{y}}.
794 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/
795 project/geographiclib/>} and Python 3.7+
796 U{math.remainder<https://docs.Python.org/3/
797 library/math.html#math.remainder>}.
798 '''
799 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and
800 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native
801 # fmod( 0, 360) == 0.0
802 # fmod( 360, 360) == 0.0
803 # fmod(-0, 360) == 0.0
804 # fmod(-0.0, 360) == -0.0
805 # fmod(-360, 360) == -0.0
806 # however, using the % operator ...
807 # 0 % 360 == 0
808 # 360 % 360 == 0
809 # 360.0 % 360 == 0.0
810 # -0 % 360 == 0
811 # -360 % 360 == 0 == (-360) % 360
812 # -0.0 % 360 == 0.0 == (-0.0) % 360
813 # -360.0 % 360 == 0.0 == (-360.0) % 360
815 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)
816 # == +0.0. This fixes this bug. See also Math::AngNormalize
817 # in the C++ library, Math.sincosd has a similar fix.
818 if isfinite(x):
819 try:
820 r = remainder(x, y) if x else x
821 except Exception as e:
822 raise _xError(e, unstr(fremainder, x, y))
823 else: # handle x INF and NINF as NAN
824 r = NAN
825 return r
828if _MODS.sys_version_info2 < (3, 8): # PYCHOK no cover
829 from math import hypot # OK in Python 3.7-
831 def hypot_(*xs):
832 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.
834 Similar to Python 3.8+ n-dimension U{math.hypot
835 <https://docs.Python.org/3.8/library/math.html#math.hypot>},
836 but exceptions, C{nan} and C{infinite} values are
837 handled differently.
839 @arg xs: X arguments (C{scalar}s), all positional.
841 @return: Norm (C{float}).
843 @raise OverflowError: Partial C{2sum} overflow.
845 @raise ValueError: Invalid or no B{C{xs}} values.
847 @note: The Python 3.8+ Euclidian distance U{math.dist
848 <https://docs.Python.org/3.8/library/math.html#math.dist>}
849 between 2 I{n}-dimensional points I{p1} and I{p2} can be
850 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},
851 provided I{p1} and I{p2} have the same, non-zero length I{n}.
852 '''
853 return float(_Hypot(*xs))
855elif _MODS.sys_version_info2 < (3, 10): # PYCHOK no cover
856 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see
857 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},
858 # U{cffk<https://Bugs.Python.org/issue43088>} and module
859 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}
861 def hypot(x, y):
862 '''Compute the norm M{sqrt(x**2 + y**2)}.
864 @arg x: X argument (C{scalar}).
865 @arg y: Y argument (C{scalar}).
867 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).
868 '''
869 return float(_Hypot(x, y))
871 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9
872else:
873 from math import hypot # PYCHOK in Python 3.10+
874 hypot_ = hypot
877def _Hypot(*xs):
878 '''(INTERNAL) Substitute for inaccurate C{math.hypot}.
879 '''
880 return Fhypot(*xs, nonfinites=True, raiser=False) # f2product=True
883def hypot1(x):
884 '''Compute the norm M{sqrt(1 + x**2)}.
886 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
888 @return: Norm (C{float} or L{Fhypot}).
889 '''
890 h = _1_0
891 if x:
892 if _isFsum_2Tuple(x):
893 h = _Hypot(h, x)
894 h = float(h)
895 else:
896 h = hypot(h, x)
897 return h
900def hypot2(x, y):
901 '''Compute the I{squared} norm M{x**2 + y**2}.
903 @arg x: X (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
904 @arg y: Y (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
906 @return: C{B{x}**2 + B{y}**2} (C{float}).
907 '''
908 x, y = map1(abs, x, y) # NOT fabs!
909 if y > x:
910 x, y = y, x
911 h2 = x**2
912 if h2 and y:
913 h2 *= (y / x)**2 + _1_0
914 return float(h2)
917def hypot2_(*xs):
918 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.
920 @arg xs: Components (each C{scalar}, an L{Fsum} or
921 L{Fsum2Tuple}), all positional.
923 @return: Squared norm (C{float}).
925 @see: Class L{Fpowers} for further details.
926 '''
927 h2 = float(max(map(abs, xs))) if xs else _0_0
928 if h2: # and isfinite(h2)
929 _h = _1_0 / h2
930 xs = ((x * _h) for x in xs)
931 H2 = Fpowers(2, *xs, nonfinites=True) # f2product=True
932 h2 = H2.fover(_h**2)
933 return h2
936def norm2(x, y):
937 '''Normalize a 2-dimensional vector.
939 @arg x: X component (C{scalar}).
940 @arg y: Y component (C{scalar}).
942 @return: 2-Tuple C{(x, y)}, normalized.
944 @raise ValueError: Invalid B{C{x}} or B{C{y}}
945 or zero norm.
946 '''
947 try:
948 h = None
949 h = hypot(x, y)
950 if h:
951 x, y = (x / h), (y / h)
952 else:
953 x = _copysign_0_0(x) # pass?
954 y = _copysign_0_0(y)
955 except Exception as e:
956 raise _xError(e, x=x, y=y, h=h)
957 return x, y
960def norm_(*xs):
961 '''Normalize the components of an n-dimensional vector.
963 @arg xs: Components (each C{scalar}, an L{Fsum} or
964 L{Fsum2Tuple}), all positional.
966 @return: Yield each component, normalized.
968 @raise ValueError: Invalid or insufficent B{C{xs}}
969 or zero norm.
970 '''
971 try:
972 i = h = None
973 x = xs
974 h = hypot_(*xs)
975 _h = (_1_0 / h) if h else _0_0
976 for i, x in enumerate(xs):
977 yield x * _h
978 except Exception as X:
979 raise _xsError(X, xs, i, x, h=h)
982def _powers(x, n):
983 '''(INTERNAL) Yield C{x**i for i=1..n}.
984 '''
985 p = 1 # type(p) == type(x)
986 for _ in range(n):
987 p *= x
988 yield p
991def _root(x, p, where):
992 '''(INTERNAL) Raise C{x} to power C{0 <= p < 1}.
993 '''
994 try:
995 if x > 0:
996 r = Fsum(f2product=True, nonfinites=True)(x)
997 return r.fpow(p).as_iscalar
998 elif x < 0:
999 raise ValueError(_negative_)
1000 except Exception as X:
1001 raise _xError(X, unstr(where, x))
1002 return _0_0 if p else _1_0 # x == 0
1005def sqrt0(x, Error=None):
1006 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},
1007 preserving C{type(B{x})}.
1009 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1010 @kwarg Error: Error to raise for negative B{C{x}}.
1012 @return: Square root (C{float} or L{Fsum}) or C{0.0}.
1014 @raise TypeeError: Invalid B{C{x}}.
1016 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}
1017 returns C{0.0}.
1018 '''
1019 if Error and x < 0:
1020 raise Error(unstr(sqrt0, x))
1021 return _root(x, _0_5, sqrt0) if x > EPS02 else (
1022 _0_0 if x < EPS02 else EPS0)
1025def sqrt3(x):
1026 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},
1027 preserving C{type(B{x})}.
1029 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1031 @return: Square root I{cubed} (C{float} or L{Fsum}).
1033 @raise TypeeError: Invalid B{C{x}}.
1035 @raise ValueError: Negative B{C{x}}.
1037 @see: Functions L{cbrt} and L{cbrt2}.
1038 '''
1039 return _root(x, _1_5, sqrt3)
1042def sqrt_a(h, b):
1043 '''Compute C{I{a}} side of a right-angled triangle from
1044 C{sqrt(B{h}**2 - B{b}**2)}.
1046 @arg h: Hypotenuse or outer annulus radius (C{scalar}).
1047 @arg b: Triangle side or inner annulus radius (C{scalar}).
1049 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).
1051 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.
1053 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.
1055 @see: Inner tangent chord B{I{d}} of an U{annulus
1056 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}
1057 and function U{annulus_area<https://People.SC.FSU.edu/
1058 ~jburkardt/py_src/geometry/geometry.py>}.
1059 '''
1060 try:
1061 if not (_isHeight(h) and _isRadius(b)):
1062 raise TypeError(_not_scalar_)
1063 c = fabs(h)
1064 if c > EPS0:
1065 s = _1_0 - (b / c)**2
1066 if s < 0:
1067 raise ValueError(_h_lt_b_)
1068 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)
1069 else: # PYCHOK no cover
1070 b = fabs(b)
1071 d = c - b
1072 if d < 0:
1073 raise ValueError(_h_lt_b_)
1074 d *= c + b
1075 a = sqrt(d) if d else _0_0
1076 except Exception as x:
1077 raise _xError(x, h=h, b=b)
1078 return copysign0(a, h)
1081def zcrt(x):
1082 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},
1083 preserving C{type(B{x})}.
1085 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1087 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).
1089 @see: Functions L{bqrt} and L{zqrt}.
1091 @raise TypeeError: Invalid B{C{x}}.
1093 @raise ValueError: Negative B{C{x}}.
1094 '''
1095 return _root(x, _1_6th, zcrt)
1098def zqrt(x):
1099 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,
1100 M{x**(1 / 8)}, preserving C{type(B{x})}.
1102 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1104 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).
1106 @see: Functions L{bqrt} and L{zcrt}.
1108 @raise TypeeError: Invalid B{C{x}}.
1110 @raise ValueError: Negative B{C{x}}.
1111 '''
1112 return _root(x, _0_125, zqrt)
1114# **) MIT License
1115#
1116# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1117#
1118# Permission is hereby granted, free of charge, to any person obtaining a
1119# copy of this software and associated documentation files (the "Software"),
1120# to deal in the Software without restriction, including without limitation
1121# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1122# and/or sell copies of the Software, and to permit persons to whom the
1123# Software is furnished to do so, subject to the following conditions:
1124#
1125# The above copyright notice and this permission notice shall be included
1126# in all copies or substantial portions of the Software.
1127#
1128# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1129# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1130# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1131# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1132# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1133# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1134# OTHER DEALINGS IN THE SOFTWARE.