Coverage for pygeodesy/fmath.py: 91%
331 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-02-15 15:48 -0500
« prev ^ index » next coverage.py v7.10.7, created at 2026-02-15 15:48 -0500
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, _0_25, _1_3rd, _0_5, _2_3rd, \
14 _1_0, _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, .elliptic, .trf, .utm
27__all__ = _ALL_LAZY.fmath
28__version__ = '26.01.06'
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_1_6th = 1 / 6
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+
261except ImportError: # Python 3.10-
263 def _cbrt(x):
264 '''(INTERNAL) Compute the I{signed}, cube root M{x**(1/3)}.
265 '''
266 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>
267 # simpler and more accurate than Ken Turkowski's CubeRoot, see
268 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>
269 return _copysign(pow(fabs(x), _1_3rd), x) # to avoid complex
272def cbrt(x):
273 '''Compute the cube root M{x**(1/3)}, preserving C{type(B{x})}.
275 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
277 @return: Cubic root (C{float} or L{Fsum}).
279 @see: Functions L{cbrt2} and L{sqrt3}.
280 '''
281 if _isFsum_2Tuple(x):
282 r = abs(x).fpow(_1_3rd)
283 if x.signOf() < 0:
284 r = -r
285 else:
286 r = _cbrt(x)
287 return r # cbrt(-0.0) == -0.0
290def cbrt2(x): # PYCHOK attr
291 '''Compute the cube root I{squared} M{x**(2/3)}, preserving C{type(B{x})}.
293 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
295 @return: Cube root I{squared} (C{float} or L{Fsum}).
297 @see: Functions L{cbrt} and L{sqrt3}.
298 '''
299 return abs(x).fpow(_2_3rd) if _isFsum_2Tuple(x) else _cbrt(x**2)
302def euclid(x, y):
303 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by M{max(abs(x),
304 abs(y)) + min(abs(x), abs(y)) * 0.4142...}.
306 @arg x: X component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
307 @arg y: Y component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
309 @return: Appoximate norm (C{float} or L{Fsum}).
311 @see: Function L{euclid_}.
312 '''
313 x, y = abs(x), abs(y) # NOT fabs!
314 if x < y:
315 x, y = y, x
316 return x + y * _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 x:
334 if e < x:
335 e, x = x, e
336 x *= _0_4142
337# s = e + x
338# if e < x: # like .fsums._2sum
339# x -= s # e = (x - s) + e
340# else:
341# e -= s # e = (e - s) + x
342 e += x
343# e += s
344 return e
347def facos1(x):
348 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}, scalar.
350 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/
351 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.
352 '''
353 a = fabs(x)
354 if a < EPS0:
355 r = PI_2
356 elif a < EPS1:
357 r = _fast(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)
358 r *= sqrt(_1_0 - a)
359 if x < 0:
360 r = PI - r
361 else:
362 r = PI if x < 0 else _0_0
363 return r
366def fasin1(x): # PYCHOK no cover
367 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}, scalar.
369 @see: L{facos1}.
370 '''
371 return PI_2 - facos1(x)
374def _fast(x, *cs):
375 '''(INTERNAL) Horner form for C{facos1} and C{fatan1}.
376 '''
377 h = 0
378 for c in reversed(cs):
379 h = _fma(x, h, c) if h else c
380 return h
383def fatan(x):
384 '''Fast approximation of C{atan(B{x})}, scalar.
385 '''
386 a = fabs(x)
387 if a < _1_0:
388 r = fatan1(a) if a else _0_0
389 elif a > _1_0:
390 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)
391 else:
392 r = PI_4
393 if x < 0: # copysign0(r, x)
394 r = -r
395 return r
398def fatan1(x):
399 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} < 1}, I{unchecked}.
401 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/
402 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations
403 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/
404 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},
405 IEEE Signal Processing Magazine, 111, May 2006.
406 '''
407 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1
408 # == PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x < 1
409 # == x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))
410 return _fast(x, _0_0, 1.0300981634, -0.1784, -0.0663)
413def fatan2(y, x):
414 '''Fast approximation of C{atan2(B{y}, B{x})}, scalar.
416 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/
417 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}
418 and L{fatan1}.
419 '''
420 a, b = fabs(x), fabs(y)
421 if b > a:
422 r = (PI_2 - fatan1(a / b)) if a else PI_2
423 elif a > b:
424 r = fatan1(b / a) if b else _0_0
425 elif a: # a == b != 0
426 r = PI_4
427 else: # a == b == 0
428 return _0_0
429 if x < 0:
430 r = PI - r
431 if y < 0: # copysign0(r, y)
432 r = -r
433 return r
436def favg(a, b, f=_0_5, nonfinites=True):
437 '''Return the precise average of two values.
439 @arg a: One (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
440 @arg b: Other (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
441 @kwarg f: Optional fraction (C{float}).
442 @kwarg nonfinites: Optional setting, see function L{fma}.
444 @return: M{a + f * (b - a)} (C{float}).
445 '''
446 F = fma(f, (b - a), a, nonfinites=nonfinites)
447 return float(F)
450def fdot(xs, *ys, **start_f2product_nonfinites):
451 '''Return the precision dot product M{start + sum(xs[i] * ys[i] for i in range(len(xs)))}.
453 @arg xs: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
454 @arg ys: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
455 @kwarg start_f2product_nonfinites: Optional bias C{B{start}=0} (C{scalar}, an
456 L{Fsum} or L{Fsum2Tuple}) and settings C{B{f2product}=None} (C{bool})
457 and C{B{nonfinites=True}} (C{bool}), see class L{Fsum<Fsum.__init__>}.
459 @return: Dot product (C{float}).
461 @raise LenError: Unequal C{len(B{xs})} and C{len(B{ys})}.
463 @see: Class L{Fdot}, U{Algorithm 5.10 B{DotK}
464 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} and function
465 C{math.sumprod} in Python 3.12 and later.
466 '''
467 D = Fdot(xs, *ys, **_xkwds(start_f2product_nonfinites, nonfinites=True))
468 return float(D)
471def fdot_(*xys, **start_f2product_nonfinites):
472 '''Return the (precision) dot product M{start + sum(xys[i] * xys[i+1] for i in range(0, len(xys), B{2}))}.
474 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
476 @see: Function L{fdot} for further details.
478 @return: Dot product (C{float}).
479 '''
480 D = Fdot_(*xys, **_xkwds(start_f2product_nonfinites, nonfinites=True))
481 return float(D)
484def fdot3(xs, ys, zs, **start_f2product_nonfinites):
485 '''Return the (precision) dot product M{start + sum(xs[i] * ys[i] * zs[i] for i in range(len(xs)))}.
487 @arg xs: X values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
488 @arg ys: Y values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
489 @arg zs: Z values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
491 @see: Function L{fdot} for further details.
493 @return: Dot product (C{float}).
495 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})} and/or C{len(B{zs})}.
496 '''
497 n = len(xs)
498 if not n == len(ys) == len(zs):
499 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))
501 D = Fdot((), **_xkwds(start_f2product_nonfinites, nonfinites=True))
502 kwds = dict(f2product=D.f2product(), nonfinites=D.nonfinites())
503 _f = Fsum(**kwds)
504 D = D._facc(_f(x).f2mul_(y, z, **kwds) for x, y, z in zip(xs, ys, zs))
505 return float(D)
508def fhorner(x, *cs, **incx):
509 '''Horner form evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)} as
510 in- or decreasing exponent M{sum(... i=n..0)}, where C{n = len(cs) - 1}.
512 @return: Horner sum (C{float}).
514 @see: Class L{Fhorner<Fhorner.__init__>} for further details.
515 '''
516 H = Fhorner(x, *cs, **incx)
517 return float(H)
520def fidw(xs, ds, beta=2):
521 '''Interpolate using U{Inverse Distance Weighting
522 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).
524 @arg xs: Known values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
525 @arg ds: Non-negative distances (each C{scalar}, an L{Fsum} or
526 L{Fsum2Tuple}).
527 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).
529 @return: Interpolated value C{x} (C{float}).
531 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.
533 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.
535 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or
536 weighted B{C{ds}} below L{EPS}.
538 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.
539 '''
540 n, xs = len2(xs)
541 if n > 1:
542 b = -Int_(beta=beta, low=0, high=3)
543 if b < 0:
544 try: # weighted
545 _d, W, X = (Fsum() for _ in range(3))
546 for i, d in enumerate(_xiterable(ds)):
547 x = xs[i]
548 D = _d(d)
549 if D < EPS0:
550 if D < 0:
551 raise ValueError(_negative_)
552 x = float(x)
553 i = n
554 break
555 if D.fpow(b):
556 W += D
557 X += D.fmul(x)
558 else:
559 x = X.fover(W, raiser=False)
560 i += 1 # len(xs) >= len(ds)
561 except IndexError:
562 i += 1 # len(xs) < i < len(ds)
563 except Exception as X:
564 _I = Fmt.INDEX
565 raise _xError(X, _I(xs=i), x,
566 _I(ds=i), d)
567 else: # b == 0
568 x = fsum(xs) / n # fmean(xs)
569 i = n
570 elif n:
571 x = float(xs[0])
572 i = n
573 else:
574 x = _0_0
575 i, _ = len2(ds)
576 if i != n:
577 raise LenError(fidw, xs=n, ds=i)
578 return x
581try:
582 from math import fma as _fma # in .resections
583except ImportError: # PYCHOK DSPACE!
585 def _fma(x, y, z): # no need for accuracy
586 return x * y + z
589def fma(x, y, z, **nonfinites): # **raiser
590 '''Fused-multiply-add, using C{math.fma(x, y, z)} in Python 3.13+
591 or an equivalent implementation.
593 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
594 @arg y: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
595 @arg z: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
596 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False},
597 to override default L{nonfiniterrors}
598 (C{bool}), see method L{Fsum.fma}.
600 @return: C{(x * y) + z} (C{float} or L{Fsum}).
601 '''
602 F, raiser = _Fm2(x, **nonfinites)
603 return F.fma(y, z, **raiser).as_iscalar
606def _Fm2(x, nonfinites=None, **raiser):
607 '''(INTERNAL) Handle C{fma} and C{f2mul} DEPRECATED C{raiser=False}.
608 '''
609 return Fsum(x, nonfinites=nonfinites), raiser
612def fmean(xs):
613 '''Compute the accurate mean M{sum(xs) / len(xs)}.
615 @arg xs: Values (each C{scalar}, or L{Fsum} or L{Fsum2Tuple}).
617 @return: Mean value (C{float}).
619 @raise LenError: No B{C{xs}} values.
621 @raise OverflowError: Partial C{2sum} overflow.
622 '''
623 n, xs = len2(xs)
624 if n < 1:
625 raise LenError(fmean, xs=xs)
626 M = Fsum(*xs, nonfinites=True)
627 return M.fover(n) if n > 1 else float(M)
630def fmean_(*xs, **nonfinites):
631 '''Compute the accurate mean M{sum(xs) / len(xs)}.
633 @see: Function L{fmean} for further details.
634 '''
635 return fmean(xs, **nonfinites)
638def f2mul_(x, *ys, **nonfinites): # **raiser
639 '''Cascaded, accurate multiplication C{B{x} * B{y} * B{y} ...} for all B{C{ys}}.
641 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
642 @arg ys: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
643 positional.
644 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False}, to override default
645 L{nonfiniterrors} (C{bool}), see method L{Fsum.f2mul_}.
647 @return: The cascaded I{TwoProduct} (C{float}, C{int} or L{Fsum}).
649 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
650 '''
651 F, raiser = _Fm2(x, **nonfinites)
652 return F.f2mul_(*ys, **raiser).as_iscalar
655def fpolynomial(x, *cs, **over_f2product_nonfinites):
656 '''Evaluate the polynomial M{sum(cs[i] * x**i for i=0..len(cs)) [/ over]}.
658 @kwarg over_f2product_nonfinites: Optional final divisor C{B{over}=None}
659 (I{non-zero} C{scalar}) and other settings, see class
660 L{Fpolynomial<Fpolynomial.__init__>}.
662 @return: Polynomial value (C{float} or L{Fpolynomial}).
663 '''
664 d, kwds = _xkwds_pop2(over_f2product_nonfinites, over=0)
665 P = Fpolynomial(x, *cs, **kwds)
666 return P.fover(d) if d else float(P)
669def fpowers(x, n, alts=0):
670 '''Return a series of powers M{[x**i for i=1..n]}, note I{1..!}
672 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
673 @arg n: Highest exponent (C{int}).
674 @kwarg alts: Only alternating powers, starting with this
675 exponent (C{int}).
677 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).
679 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.
681 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.
682 '''
683 if not isint(n):
684 raise _IsnotError(typename(int), n=n)
685 elif n < 1:
686 raise _ValueError(n=n)
688 p = x if isscalar(x) or _isFsum_2Tuple(x) else _2float(x=x)
689 ps = tuple(_powers(p, n))
691 if alts > 0: # x**2, x**4, ...
692 # ps[alts-1::2] chokes PyChecker
693 ps = ps[slice(alts-1, None, 2)]
695 return ps
698try:
699 from math import prod as fprod # Python 3.8
700except ImportError:
702 def fprod(xs, start=1):
703 '''Iterable product, like C{math.prod} or C{numpy.prod}.
705 @arg xs: Iterable of values to be multiplied (each
706 C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
707 @kwarg start: Initial value, also the value returned
708 for an empty B{C{xs}} (C{scalar}).
710 @return: The product (C{float} or L{Fsum}).
712 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
713 numpy/reference/generated/numpy.prod.html>}.
714 '''
715 return freduce(_operator.mul, xs, start)
718def frandoms(n, seeded=None):
719 '''Generate C{n} (long) lists of random C{floats}.
721 @arg n: Number of lists to generate (C{int}, non-negative).
722 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or
723 if C{True}, seed using today's C{year-day}.
725 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/
726 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.
727 '''
728 from random import gauss, random, seed, shuffle
730 if seeded is None:
731 pass
732 elif seeded and isbool(seeded):
733 from time import localtime
734 seed(localtime().tm_yday)
735 elif isscalar(seeded):
736 seed(seeded)
738 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 7
739 for _ in range(n):
740 s = 0
741 t = list(c)
742 _a = t.append
743 for _ in range(n * 8):
744 v = gauss(0, random())**7 - s
745 _a(v)
746 s += v
747 shuffle(t)
748 yield t
751def frange(start, number, step=1):
752 '''Generate a range of C{float}s.
754 @arg start: First value (C{float}).
755 @arg number: The number of C{float}s to generate (C{int}).
756 @kwarg step: Increment value (C{float}).
758 @return: A generator (C{float}s).
760 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
761 numpy/reference/generated/numpy.arange.html>}.
762 '''
763 if not isint(number):
764 raise _IsnotError(typename(int), number=number)
765 for i in range(number):
766 yield start + (step * i)
769try:
770 from functools import reduce as freduce
771except ImportError:
772 try:
773 freduce = reduce # PYCHOK expected
774 except NameError: # Python 3+
776 def freduce(f, xs, *start):
777 '''For missing C{functools.reduce}.
778 '''
779 if start:
780 r = v = start[0]
781 else:
782 r, v = 0, MISSING
783 for v in xs:
784 r = f(r, v)
785 if v is MISSING:
786 raise _TypeError(xs=(), start=MISSING)
787 return r
790def fremainder(x, y):
791 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.
793 @arg x: Numerator (C{scalar}).
794 @arg y: Modulus, denominator (C{scalar}).
796 @return: Remainder (C{scalar}, preserving signed
797 0.0) or C{NAN} for any non-finite B{C{x}}.
799 @raise ValueError: Infinite or near-zero B{C{y}}.
801 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/
802 project/geographiclib/>} and Python 3.7+
803 U{math.remainder<https://docs.Python.org/3/
804 library/math.html#math.remainder>}.
805 '''
806 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and
807 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native
808 # fmod( 0, 360) == 0.0
809 # fmod( 360, 360) == 0.0
810 # fmod(-0, 360) == 0.0
811 # fmod(-0.0, 360) == -0.0
812 # fmod(-360, 360) == -0.0
813 # however, using the % operator ...
814 # 0 % 360 == 0
815 # 360 % 360 == 0
816 # 360.0 % 360 == 0.0
817 # -0 % 360 == 0
818 # -360 % 360 == 0 == (-360) % 360
819 # -0.0 % 360 == 0.0 == (-0.0) % 360
820 # -360.0 % 360 == 0.0 == (-360.0) % 360
822 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)
823 # == +0.0. This fixes this bug. See also Math::AngNormalize
824 # in the C++ library, Math.sincosd has a similar fix.
825 if isfinite(x):
826 try:
827 r = remainder(x, y) if x else x
828 except Exception as e:
829 raise _xError(e, unstr(fremainder, x, y))
830 else: # handle x INF and NINF as NAN
831 r = NAN
832 return r
835if _MODS.sys_version_info2 < (3, 8): # PYCHOK no cover
836 from math import hypot # OK in Python 3.7-
838 def hypot_(*xs):
839 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.
841 Similar to Python 3.8+ n-dimension U{math.hypot
842 <https://docs.Python.org/3.8/library/math.html#math.hypot>},
843 but exceptions, C{nan} and C{infinite} values are
844 handled differently.
846 @arg xs: X arguments (C{scalar}s), all positional.
848 @return: Norm (C{float}).
850 @raise OverflowError: Partial C{2sum} overflow.
852 @raise ValueError: Invalid or no B{C{xs}} values.
854 @note: The Python 3.8+ Euclidian distance U{math.dist
855 <https://docs.Python.org/3.8/library/math.html#math.dist>}
856 between 2 I{n}-dimensional points I{p1} and I{p2} can be
857 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},
858 provided I{p1} and I{p2} have the same, non-zero length I{n}.
859 '''
860 return float(_Hypot(*xs))
862elif _MODS.sys_version_info2 < (3, 10): # PYCHOK no cover
863 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see
864 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},
865 # U{cffk<https://Bugs.Python.org/issue43088>} and module
866 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}
868 def hypot(x, y):
869 '''Compute the norm M{sqrt(x**2 + y**2)}.
871 @arg x: X argument (C{scalar}).
872 @arg y: Y argument (C{scalar}).
874 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).
875 '''
876 return float(_Hypot(x, y))
878 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9
879else:
880 from math import hypot # PYCHOK in Python 3.10+
881 hypot_ = hypot
884def _Hypot(*xs):
885 '''(INTERNAL) Substitute for inaccurate C{math.hypot}.
886 '''
887 return Fhypot(*xs, nonfinites=True, raiser=False) # f2product=True
890def hypot1(x):
891 '''Compute the norm M{sqrt(1 + x**2)}.
893 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
895 @return: Norm (C{float} or L{Fhypot}).
896 '''
897 h = _1_0
898 if x:
899 if _isFsum_2Tuple(x):
900 h = _Hypot(h, x)
901 h = float(h)
902 else:
903 h = hypot(h, x)
904 return h
907def hypot2(x, y):
908 '''Compute the I{squared} norm M{x**2 + y**2}.
910 @arg x: X (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
911 @arg y: Y (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
913 @return: C{B{x}**2 + B{y}**2} (C{float}).
914 '''
915 x, y = map1(abs, x, y) # NOT fabs!
916 if y > x:
917 x, y = y, x
918 h2 = x**2
919 if h2 and y:
920 h2 *= (y / x)**2 + _1_0
921 return float(h2)
924def hypot2_(*xs):
925 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.
927 @arg xs: Components (each C{scalar}, an L{Fsum} or
928 L{Fsum2Tuple}), all positional.
930 @return: Squared norm (C{float}).
932 @see: Class L{Fpowers} for further details.
933 '''
934 h2 = float(max(map(abs, xs))) if xs else _0_0
935 if h2: # and isfinite(h2)
936 _h = _1_0 / h2
937 xs = ((x * _h) for x in xs)
938 H2 = Fpowers(2, *xs, nonfinites=True) # f2product=True
939 h2 = H2.fover(_h**2)
940 return h2
943def norm2(x, y):
944 '''Normalize a 2-dimensional vector.
946 @arg x: X component (C{scalar}).
947 @arg y: Y component (C{scalar}).
949 @return: 2-Tuple C{(x, y)}, normalized.
951 @raise ValueError: Invalid B{C{x}} or B{C{y}}
952 or zero norm.
953 '''
954 try:
955 h = None
956 h = hypot(x, y)
957 if h:
958 x, y = (x / h), (y / h)
959 else:
960 x = _copysign_0_0(x) # pass?
961 y = _copysign_0_0(y)
962 except Exception as e:
963 raise _xError(e, x=x, y=y, h=h)
964 return x, y
967def norm_(*xs):
968 '''Normalize the components of an n-dimensional vector.
970 @arg xs: Components (each C{scalar}, an L{Fsum} or
971 L{Fsum2Tuple}), all positional.
973 @return: Yield each component, normalized.
975 @raise ValueError: Invalid or insufficent B{C{xs}}
976 or zero norm.
977 '''
978 try:
979 i = h = None
980 x = xs
981 h = hypot_(*xs)
982 _h = (_1_0 / h) if h else _0_0
983 for i, x in enumerate(xs):
984 yield x * _h
985 except Exception as X:
986 raise _xsError(X, xs, i, x, h=h)
989def _powers(x, n):
990 '''(INTERNAL) Yield C{x**i for i=1..n}.
991 '''
992 p = 1 # type(p) == type(x)
993 for _ in range(n):
994 p *= x
995 yield p
998def _root(x, p, where):
999 '''(INTERNAL) Raise C{x} to power C{0 <= p < 1}.
1000 '''
1001 try:
1002 if x > 0:
1003 r = Fsum(f2product=True, nonfinites=True)(x)
1004 return r.fpow(p).as_iscalar
1005 elif x < 0:
1006 raise ValueError(_negative_)
1007 except Exception as X:
1008 raise _xError(X, unstr(where, x))
1009 return _0_0 if p else _1_0 # x == 0
1012def sqrt0(x, Error=None):
1013 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},
1014 preserving C{type(B{x})}.
1016 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1017 @kwarg Error: Error to raise for negative B{C{x}}.
1019 @return: Square root (C{float} or L{Fsum}) or C{0.0}.
1021 @raise TypeeError: Invalid B{C{x}}.
1023 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}
1024 returns C{0.0}.
1025 '''
1026 if Error and x < 0:
1027 raise Error(unstr(sqrt0, x))
1028 return _root(x, _0_5, sqrt0) if x > EPS02 else (
1029 _0_0 if x < EPS02 else EPS0)
1032def sqrt3(x):
1033 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},
1034 preserving C{type(B{x})}.
1036 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1038 @return: Square root I{cubed} (C{float} or L{Fsum}).
1040 @raise TypeeError: Invalid B{C{x}}.
1042 @raise ValueError: Negative B{C{x}}.
1044 @see: Functions L{cbrt} and L{cbrt2}.
1045 '''
1046 return _root(x, _1_5, sqrt3)
1049def sqrt_a(h, b):
1050 '''Compute the C{I{a}} side of a right-angled triangle from
1051 C{sqrt(B{h}**2 - B{b}**2)}.
1053 @arg h: Hypotenuse or outer annulus radius (C{scalar}).
1054 @arg b: Triangle side or inner annulus radius (C{scalar}).
1056 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).
1058 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.
1060 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.
1062 @see: Inner tangent chord B{I{d}} of an U{annulus
1063 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}
1064 and function U{annulus_area<https://People.SC.FSU.edu/
1065 ~jburkardt/py_src/geometry/geometry.py>}.
1066 '''
1067 try:
1068 if not (_isHeight(h) and _isRadius(b)):
1069 raise TypeError(_not_scalar_)
1070 c = fabs(h)
1071 if c > EPS0:
1072 s = _1_0 - (b / c)**2
1073 if s < 0:
1074 raise ValueError(_h_lt_b_)
1075 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)
1076 else: # PYCHOK no cover
1077 b = fabs(b)
1078 d = c - b
1079 if d < 0:
1080 raise ValueError(_h_lt_b_)
1081 d *= c + b
1082 a = sqrt(d) if d else _0_0
1083 except Exception as x:
1084 raise _xError(x, h=h, b=b)
1085 return copysign0(a, h)
1088def zcrt(x):
1089 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},
1090 preserving C{type(B{x})}.
1092 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1094 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).
1096 @see: Functions L{bqrt} and L{zqrt}.
1098 @raise TypeeError: Invalid B{C{x}}.
1100 @raise ValueError: Negative B{C{x}}.
1101 '''
1102 return _root(x, _1_6th, zcrt)
1105def zqrt(x):
1106 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,
1107 M{x**(1 / 8)}, preserving C{type(B{x})}.
1109 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1111 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).
1113 @see: Functions L{bqrt} and L{zcrt}.
1115 @raise TypeeError: Invalid B{C{x}}.
1117 @raise ValueError: Negative B{C{x}}.
1118 '''
1119 return _root(x, _0_125, zqrt)
1121# **) MIT License
1122#
1123# Copyright (C) 2016-2026 -- mrJean1 at Gmail -- All Rights Reserved.
1124#
1125# Permission is hereby granted, free of charge, to any person obtaining a
1126# copy of this software and associated documentation files (the "Software"),
1127# to deal in the Software without restriction, including without limitation
1128# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1129# and/or sell copies of the Software, and to permit persons to whom the
1130# Software is furnished to do so, subject to the following conditions:
1131#
1132# The above copyright notice and this permission notice shall be included
1133# in all copies or substantial portions of the Software.
1134#
1135# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1136# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1137# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1138# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1139# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1140# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1141# OTHER DEALINGS IN THE SOFTWARE.