Coverage for pygeodesy/fmath.py: 91%
339 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-03-25 15:01 -0400
« prev ^ index » next coverage.py v7.10.7, created at 2026-03-25 15:01 -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, _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
23# from utily import atan2b, atan2p # _MODS, circular import!
25from math import fabs, sqrt # pow
26import operator as _operator # in .datums, .elliptic, .trf, .utm
28__all__ = _ALL_LAZY.fmath
29__version__ = '26.03.25'
31# sqrt(2) - 1 <https://WikiPedia.org/wiki/Square_root_of_2>
32_0_4142 = 0.41421356237309504880 # ~ 3_730_904_090_310_553 / 9_007_199_254_740_992
33_1_6th = 1 / 6
34_h_lt_b_ = 'abs(h) < abs(b)'
37class Fdot(Fsum):
38 '''Precision dot product.
39 '''
40 def __init__(self, a, *b, **start_name_f2product_nonfinites_RESIDUAL):
41 '''New L{Fdot} precision dot product M{start + sum(a[i] * b[i] for i=0..len(a)-1)}.
43 @arg a: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
44 @arg b: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
45 positional.
46 @kwarg start_name_f2product_nonfinites_RESIDUAL: Optional bias C{B{start}=0}
47 (C{scalar}, an L{Fsum} or L{Fsum2Tuple}), C{B{name}=NN} (C{str})
48 and other settings, see class L{Fsum<Fsum.__init__>}.
50 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.
52 @raise OverflowError: Partial C{2sum} overflow.
54 @raise TypeError: Invalid B{C{x}}.
56 @raise ValueError: Non-finite B{C{x}}.
58 @see: Function L{fdot} and method L{Fsum.fadd}.
59 '''
60 s, kwds = _xkwds_pop2(start_name_f2product_nonfinites_RESIDUAL, start=_0_0)
61 Fsum.__init__(self, **kwds)
62 self(s)
64 n = len(b)
65 if len(a) != n: # PYCHOK no cover
66 raise LenError(Fdot, a=len(a), b=n)
67 self._facc_dot(n, a, b, **kwds)
70class Fdot_(Fdot): # in .elliptic
71 '''Precision dot product.
72 '''
73 def __init__(self, *xys, **start_name_f2product_nonfinites_RESIDUAL):
74 '''New L{Fdot_} precision dot product M{start + sum(xys[i] * xys[i+1] for i in
75 range(0, len(xys), B{2}))}.
77 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
78 all positional.
80 @see: Class L{Fdot<Fdot.__init__>} for further details.
81 '''
82 if isodd(len(xys)):
83 raise LenError(Fdot_, xys=len(xys))
84 Fdot.__init__(self, xys[0::2], *xys[1::2], **start_name_f2product_nonfinites_RESIDUAL)
87class Fhorner(Fsum):
88 '''Precision polynomial evaluation using the Horner form.
89 '''
90 def __init__(self, x, *cs, **incx_name_f2product_nonfinites_RESIDUAL):
91 '''New L{Fhorner} form evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)}
92 with in- or decreasing exponent M{sum(... i=n..0)}, where C{n = len(cs) - 1}.
94 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
95 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
96 all positional.
97 @kwarg incx_name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str}),
98 C{B{incx}=True} for in-/decreasing exponents (C{bool}) and other
99 settings, see class L{Fsum<Fsum.__init__>}.
101 @raise OverflowError: Partial C{2sum} overflow.
103 @raise TypeError: Invalid B{C{x}}.
105 @raise ValueError: Non-finite B{C{x}}.
107 @see: Function L{fhorner} and methods L{Fsum.fadd} and L{Fsum.fmul}.
108 '''
109 incx, kwds = _xkwds_pop2(incx_name_f2product_nonfinites_RESIDUAL, incx=True)
110 Fsum.__init__(self, **kwds)
111 self._fhorner(x, cs, Fhorner, incx=incx)
114class Fhypot(Fsum):
115 '''Precision summation and hypotenuse, default C{root=2}.
116 '''
117 def __init__(self, *xs, **root_name_f2product_nonfinites_RESIDUAL_raiser):
118 '''New L{Fhypot} hypotenuse of (the I{root} of) several components (raised
119 to the power I{root}).
121 @arg xs: Components (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
122 positional.
123 @kwarg root_name_f2product_nonfinites_RESIDUAL_raiser: Optional, exponent
124 and C{B{root}=2} order (C{scalar}), C{B{name}=NN} (C{str}),
125 C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s and
126 other settings, see class L{Fsum<Fsum.__init__>} and method
127 L{root<Fsum.root>}.
128 '''
129 def _r_X_kwds(power=None, raiser=True, root=2, **kwds):
130 # DEPRECATED keyword argument C{power=2}, use C{root=2}
131 return (root if power is None else power), raiser, kwds
133 r = None # _xkwds_pop2 error
134 try:
135 r, X, kwds = _r_X_kwds(**root_name_f2product_nonfinites_RESIDUAL_raiser)
136 Fsum.__init__(self, **kwds)
137 self(_0_0)
138 if xs:
139 self._facc_power(r, xs, Fhypot, raiser=X)
140 self._fset(self.root(r, raiser=X))
141 except Exception as X:
142 raise self._ErrorXs(X, xs, root=r)
145class Fpolynomial(Fsum):
146 '''Precision polynomial evaluation.
147 '''
148 def __init__(self, x, *cs, **name_f2product_nonfinites_RESIDUAL):
149 '''New L{Fpolynomial} evaluation of the polynomial M{sum(cs[i] * x**i for
150 i=0..len(cs)-1)}.
152 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
153 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
154 all positional.
155 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str})
156 and other settings, see class L{Fsum<Fsum.__init__>}.
158 @raise OverflowError: Partial C{2sum} overflow.
160 @raise TypeError: Invalid B{C{x}}.
162 @raise ValueError: Non-finite B{C{x}}.
164 @see: Class L{Fhorner}, function L{fpolynomial} and method L{Fsum.fadd}.
165 '''
166 Fsum.__init__(self, **name_f2product_nonfinites_RESIDUAL)
167 n = len(cs) - 1
168 self(_0_0 if n < 0 else cs[0])
169 self._facc_dot(n, cs[1:], _powers(x, n), **name_f2product_nonfinites_RESIDUAL)
172class Fpowers(Fsum):
173 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.
174 '''
175 def __init__(self, power, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
176 '''New L{Fpowers} sum of (the I{power} of) several bases.
178 @arg power: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
179 @arg xs: One or more bases (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
180 positional.
181 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}
182 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s
183 and other settings, see class L{Fsum<Fsum.__init__>} and method
184 L{fpow<Fsum.fpow>}.
185 '''
186 try:
187 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)
188 Fsum.__init__(self, **kwds)
189 self(_0_0)
190 if xs:
191 self._facc_power(power, xs, Fpowers, raiser=X) # x**0 == 1
192 except Exception as X:
193 raise self._ErrorXs(X, xs, power=power)
196class Froot(Fsum):
197 '''The root of a precision summation.
198 '''
199 def __init__(self, root, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
200 '''New L{Froot} root of a precision sum.
202 @arg root: The order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}), non-zero.
203 @arg xs: Items to summate (each a C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
204 positional.
205 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}
206 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s
207 and other settings, see class L{Fsum<Fsum.__init__>} and method
208 L{fpow<Fsum.fpow>}.
209 '''
210 try:
211 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)
212 Fsum.__init__(self, **kwds)
213 self(_0_0)
214 if xs:
215 self.fadd(xs)
216 self(self.root(root, raiser=X))
217 except Exception as X:
218 raise self._ErrorXs(X, xs, root=root)
221class Fcbrt(Froot):
222 '''Cubic root of a precision summation.
223 '''
224 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
225 '''New L{Fcbrt} cubic root of a precision sum.
227 @see: Class L{Froot<Froot.__init__>} for further details.
228 '''
229 Froot.__init__(self, 3, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)
232class Fsqrt(Froot):
233 '''Square root of a precision summation.
234 '''
235 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
236 '''New L{Fsqrt} square root of a precision sum.
238 @see: Class L{Froot<Froot.__init__>} for further details.
239 '''
240 Froot.__init__(self, 2, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)
243def bqrt(x):
244 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)},
245 preserving C{type(B{x})}.
247 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
249 @return: I{Quartic} root (C{float} or an L{Fsum}).
251 @raise TypeeError: Invalid B{C{x}}.
253 @raise ValueError: Negative B{C{x}}.
255 @see: Functions L{zcrt} and L{zqrt}.
256 '''
257 return _root(x, _0_25, bqrt)
260try:
261 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, *xy0):
304 '''I{Appoximate} the norm M{hypot(B{x}, B{y})} by M{max(abs(B{x}),
305 abs(B{y})) + min(abs(B{x}), abs(B{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}).
309 @arg xy0: Optional reference C{(x0, y0)} (each C{scalar}, an
310 L{Fsum} or L{Fsum2Tuple}).
312 @return: Appoximate norm (C{float} or L{Fsum}).
313 '''
314 x, y = _map0(abs, x, y, *xy0) # NOT fabs!
315 if x < y:
316 x, y = y, x
317 return x + y * _0_4142 # _0_5 before 20.10.02
320def euclid_(*xs):
321 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))} by cascaded
322 L{euclid}.
324 @arg xs: X values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
325 all positional.
327 @return: Appoximate norm (C{float} or L{Fsum}).
329 @see: Function L{euclid}.
330 '''
331 e = _0_0
332 for x in sorted(map(abs, xs)): # NOT fabs, reverse=True!
333 # e = euclid(x, e)
334 if x:
335 if e < x:
336 e, x = x, e
337 x *= _0_4142
338# s = e + x
339# if e < x: # like .fsums._2sum
340# x -= s # e = (x - s) + e
341# else:
342# e -= s # e = (e - s) + x
343 e += x
344# e += s
345 return e
348def facos1(x):
349 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}, scalar.
351 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/
352 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.
353 '''
354 a = fabs(x)
355 if a < EPS0:
356 r = PI_2
357 elif a < EPS1:
358 r = _fast(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)
359 r *= sqrt(_1_0 - a)
360 if x < 0:
361 r = PI - r
362 else:
363 r = PI if x < 0 else _0_0
364 return r
367def fasin1(x): # PYCHOK no cover
368 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}, scalar.
370 @see: L{facos1}.
371 '''
372 return PI_2 - facos1(x)
375def _fast(x, *cs):
376 '''(INTERNAL) Horner form for C{facos1} and C{fatan1}.
377 '''
378 h = 0
379 for c in reversed(cs):
380 h = _fma(x, h, c) if h else c
381 return h
384def fatan(x):
385 '''Fast approximation of C{atan(B{x})}, scalar.
386 '''
387 a = fabs(x)
388 if a < _1_0:
389 r = fatan1(a) if a else _0_0
390 elif a > _1_0:
391 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)
392 else:
393 r = PI_4
394 if x < 0: # copysign0(r, x)
395 r = -r
396 return r
399def fatan1(x):
400 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} < 1}, I{unchecked}.
402 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/
403 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations
404 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/
405 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},
406 IEEE Signal Processing Magazine, 111, May 2006.
407 '''
408 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1
409 # == PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x < 1
410 # == x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))
411 return _fast(x, _0_0, 1.0300981634, -0.1784, -0.0663)
414def fatan2(y, x):
415 '''Fast approximation of C{atan2(B{y}, B{x})}, scalar.
417 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/
418 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}
419 and L{fatan1}.
420 '''
421 a, b = fabs(x), fabs(y)
422 if b > a:
423 r = (PI_2 - fatan1(a / b)) if a else PI_2
424 elif a > b:
425 r = fatan1(b / a) if b else _0_0
426 elif a: # a == b != 0
427 r = PI_4
428 else: # a == b == 0
429 return _0_0
430 if x < 0:
431 r = PI - r
432 if y < 0: # copysign0(r, y)
433 r = -r
434 return r
437def favg(a, b, f=_0_5, nonfinites=True):
438 '''Return the precise average of two values.
440 @arg a: One (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
441 @arg b: Other (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
442 @kwarg f: Optional fraction (C{float}).
443 @kwarg nonfinites: Optional setting, see function L{fma}.
445 @return: M{a + f * (b - a)} (C{float}).
446 '''
447 F = fma(f, (b - a), a, nonfinites=nonfinites)
448 return float(F)
451def fdot(xs, *ys, **start_f2product_nonfinites):
452 '''Return the precision dot product M{start + sum(xs[i] * ys[i] for i in range(len(xs)))}.
454 @arg xs: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
455 @arg ys: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
456 @kwarg start_f2product_nonfinites: Optional bias C{B{start}=0} (C{scalar}, an
457 L{Fsum} or L{Fsum2Tuple}) and settings C{B{f2product}=None} (C{bool})
458 and C{B{nonfinites=True}} (C{bool}), see class L{Fsum<Fsum.__init__>}.
460 @return: Dot product (C{float}).
462 @raise LenError: Unequal C{len(B{xs})} and C{len(B{ys})}.
464 @see: Class L{Fdot}, U{Algorithm 5.10 B{DotK}
465 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} and function
466 C{math.sumprod} in Python 3.12 and later.
467 '''
468 D = Fdot(xs, *ys, **_xkwds(start_f2product_nonfinites, nonfinites=True))
469 return float(D)
472def fdot_(*xys, **start_f2product_nonfinites):
473 '''Return the (precision) dot product M{start + sum(xys[i] * xys[i+1] for i in range(0, len(xys), B{2}))}.
475 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
477 @see: Function L{fdot} for further details.
479 @return: Dot product (C{float}).
480 '''
481 D = Fdot_(*xys, **_xkwds(start_f2product_nonfinites, nonfinites=True))
482 return float(D)
485def fdot3(xs, ys, zs, **start_f2product_nonfinites):
486 '''Return the (precision) dot product M{start + sum(xs[i] * ys[i] * zs[i] for i in range(len(xs)))}.
488 @arg xs: X values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
489 @arg ys: Y values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
490 @arg zs: Z values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
492 @see: Function L{fdot} for further details.
494 @return: Dot product (C{float}).
496 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})} and/or C{len(B{zs})}.
497 '''
498 n = len(xs)
499 if not n == len(ys) == len(zs):
500 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))
502 D = Fdot((), **_xkwds(start_f2product_nonfinites, nonfinites=True))
503 kwds = dict(f2product=D.f2product(), nonfinites=D.nonfinites())
504 _f = Fsum(**kwds)
505 D = D._facc(_f(x).f2mul_(y, z, **kwds) for x, y, z in zip(xs, ys, zs))
506 return float(D)
509def fhorner(x, *cs, **incx):
510 '''Horner form evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)} as
511 in- or decreasing exponent M{sum(... i=n..0)}, where C{n = len(cs) - 1}.
513 @return: Horner sum (C{float}).
515 @see: Class L{Fhorner<Fhorner.__init__>} for further details.
516 '''
517 H = Fhorner(x, *cs, **incx)
518 return float(H)
521def fidw(xs, ds, beta=2):
522 '''Interpolate using U{Inverse Distance Weighting
523 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).
525 @arg xs: Known values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
526 @arg ds: Non-negative distances (each C{scalar}, an L{Fsum} or
527 L{Fsum2Tuple}).
528 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).
530 @return: Interpolated value C{x} (C{float}).
532 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.
534 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.
536 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or
537 weighted B{C{ds}} below L{EPS}.
539 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.
540 '''
541 n, xs = len2(xs)
542 if n > 1:
543 b = -Int_(beta=beta, low=0, high=3)
544 if b < 0:
545 try: # weighted
546 _d, W, X = (Fsum() for _ in range(3))
547 for i, d in enumerate(_xiterable(ds)):
548 x = xs[i]
549 D = _d(d)
550 if D < EPS0:
551 if D < 0:
552 raise ValueError(_negative_)
553 x = float(x)
554 i = n
555 break
556 if D.fpow(b):
557 W += D
558 X += D.fmul(x)
559 else:
560 x = X.fover(W, raiser=False)
561 i += 1 # len(xs) >= len(ds)
562 except IndexError:
563 i += 1 # len(xs) < i < len(ds)
564 except Exception as X:
565 _I = Fmt.INDEX
566 raise _xError(X, _I(xs=i), x,
567 _I(ds=i), d)
568 else: # b == 0
569 x = fsum(xs) / n # fmean(xs)
570 i = n
571 elif n:
572 x = float(xs[0])
573 i = n
574 else:
575 x = _0_0
576 i, _ = len2(ds)
577 if i != n:
578 raise LenError(fidw, xs=n, ds=i)
579 return x
582try:
583 from math import fma as _fma # in .resections
584except ImportError: # PYCHOK DSPACE!
586 def _fma(x, y, z): # no need for accuracy
587 return x * y + z
590def fma(x, y, z, **nonfinites): # **raiser
591 '''Fused-multiply-add, using C{math.fma(x, y, z)} in Python 3.13+
592 or an equivalent implementation.
594 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
595 @arg y: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
596 @arg z: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
597 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False},
598 to override default L{nonfiniterrors}
599 (C{bool}), see method L{Fsum.fma}.
601 @return: C{(x * y) + z} (C{float} or L{Fsum}).
602 '''
603 F, raiser = _Fm2(x, **nonfinites)
604 return F.fma(y, z, **raiser).as_iscalar
607def _Fm2(x, nonfinites=None, **raiser):
608 '''(INTERNAL) Handle C{fma} and C{f2mul} DEPRECATED C{raiser=False}.
609 '''
610 return Fsum(x, nonfinites=nonfinites), raiser
613def fmean(xs, nonfinites=True):
614 '''Compute the accurate mean M{sum(xs) / len(xs)}.
616 @arg xs: Values (each C{scalar}, or L{Fsum} or L{Fsum2Tuple}).
618 @return: Mean value (C{float}).
620 @raise LenError: No B{C{xs}} values.
622 @raise OverflowError: Partial C{2sum} overflow.
623 '''
624 n, xs = len2(xs)
625 if n < 1:
626 raise LenError(fmean, xs=xs)
627 M = Fsum(*xs, nonfinites=nonfinites)
628 return M.fover(n) if n > 1 else float(M)
631def fmean_(*xs, **nonfinites):
632 '''Compute the accurate mean M{sum(xs) / len(xs)}.
634 @see: Function L{fmean} for further details.
635 '''
636 return fmean(xs, **nonfinites)
639def f2mul_(x, *ys, **nonfinites): # **raiser
640 '''Cascaded, accurate multiplication C{B{x} * B{y} * B{y} ...} for all B{C{ys}}.
642 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
643 @arg ys: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
644 positional.
645 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False}, to override default
646 L{nonfiniterrors} (C{bool}), see method L{Fsum.f2mul_}.
648 @return: The cascaded I{TwoProduct} (C{float}, C{int} or L{Fsum}).
650 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
651 '''
652 F, raiser = _Fm2(x, **nonfinites)
653 return F.f2mul_(*ys, **raiser).as_iscalar
656def fpolynomial(x, *cs, **over_f2product_nonfinites):
657 '''Evaluate the polynomial M{sum(cs[i] * x**i for i=0..len(cs)) [/ over]}.
659 @kwarg over_f2product_nonfinites: Optional final divisor C{B{over}=None}
660 (I{non-zero} C{scalar}) and other settings, see class
661 L{Fpolynomial<Fpolynomial.__init__>}.
663 @return: Polynomial value (C{float} or L{Fpolynomial}).
664 '''
665 d, kwds = _xkwds_pop2(over_f2product_nonfinites, over=0)
666 P = Fpolynomial(x, *cs, **kwds)
667 return P.fover(d) if d else float(P)
670def fpowers(x, n, alts=0):
671 '''Return a series of powers M{[x**i for i=1..n]}, note I{1..!}
673 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
674 @arg n: Highest exponent (C{int}).
675 @kwarg alts: Only alternating powers, starting with this
676 exponent (C{int}).
678 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).
680 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.
682 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.
683 '''
684 if not isint(n):
685 raise _IsnotError(typename(int), n=n)
686 elif n < 1:
687 raise _ValueError(n=n)
689 p = x if isscalar(x) or _isFsum_2Tuple(x) else _2float(x=x)
690 ps = tuple(_powers(p, n))
692 if alts > 0: # x**2, x**4, ...
693 # ps[alts-1::2] chokes PyChecker
694 ps = ps[slice(alts-1, None, 2)]
696 return ps
699try:
700 from math import prod as fprod # Python 3.8
701except ImportError:
703 def fprod(xs, start=1):
704 '''Iterable product, like C{math.prod} or C{numpy.prod}.
706 @arg xs: Iterable of values to be multiplied (each
707 C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
708 @kwarg start: Initial value, also the value returned
709 for an empty B{C{xs}} (C{scalar}).
711 @return: The product (C{float} or L{Fsum}).
713 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
714 numpy/reference/generated/numpy.prod.html>}.
715 '''
716 return freduce(_operator.mul, xs, start)
719def frandoms(n, seeded=None):
720 '''Generate C{n} (long) lists of random C{floats}.
722 @arg n: Number of lists to generate (C{int}, non-negative).
723 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or
724 if C{True}, seed using today's C{year-day}.
726 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/
727 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.
728 '''
729 from random import gauss, random, seed, shuffle
731 if seeded is None:
732 pass
733 elif seeded and isbool(seeded):
734 from time import localtime
735 seed(localtime().tm_yday)
736 elif isscalar(seeded):
737 seed(seeded)
739 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 7
740 for _ in range(n):
741 s = 0
742 t = list(c)
743 _a = t.append
744 for _ in range(n * 8):
745 v = gauss(0, random())**7 - s
746 _a(v)
747 s += v
748 shuffle(t)
749 yield t
752def frange(start, number, step=1):
753 '''Generate a range of C{float}s.
755 @arg start: First value (C{float}).
756 @arg number: The number of C{float}s to generate (C{int}).
757 @kwarg step: Increment value (C{float}).
759 @return: A generator (C{float}s).
761 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
762 numpy/reference/generated/numpy.arange.html>}.
763 '''
764 if not isint(number):
765 raise _IsnotError(typename(int), number=number)
766 for i in range(number):
767 yield start + (step * i)
770try:
771 from functools import reduce as freduce
772except ImportError:
773 try:
774 freduce = reduce # PYCHOK expected
775 except NameError: # Python 3+
777 def freduce(f, xs, *start):
778 '''For missing C{functools.reduce}.
779 '''
780 if start:
781 r = v = start[0]
782 else:
783 r, v = 0, MISSING
784 for v in xs:
785 r = f(r, v)
786 if v is MISSING:
787 raise _TypeError(xs=(), start=MISSING)
788 return r
791def fremainder(x, y):
792 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.
794 @arg x: Numerator (C{scalar}).
795 @arg y: Modulus, denominator (C{scalar}).
797 @return: Remainder (C{scalar}, preserving signed
798 0.0) or C{NAN} for any non-finite B{C{x}}.
800 @raise ValueError: Infinite or near-zero B{C{y}}.
802 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/
803 project/geographiclib/>} and Python 3.7+
804 U{math.remainder<https://docs.Python.org/3/
805 library/math.html#math.remainder>}.
806 '''
807 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and
808 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native
809 # fmod( 0, 360) == 0.0
810 # fmod( 360, 360) == 0.0
811 # fmod(-0, 360) == 0.0
812 # fmod(-0.0, 360) == -0.0
813 # fmod(-360, 360) == -0.0
814 # however, using the % operator ...
815 # 0 % 360 == 0
816 # 360 % 360 == 0
817 # 360.0 % 360 == 0.0
818 # -0 % 360 == 0
819 # -360 % 360 == 0 == (-360) % 360
820 # -0.0 % 360 == 0.0 == (-0.0) % 360
821 # -360.0 % 360 == 0.0 == (-360.0) % 360
823 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)
824 # == +0.0. This fixes this bug. See also Math::AngNormalize
825 # in the C++ library, Math.sincosd has a similar fix.
826 if isfinite(x):
827 try:
828 r = remainder(x, y) if x else x
829 except Exception as e:
830 raise _xError(e, unstr(fremainder, x, y))
831 else: # handle x INF and NINF as NAN
832 r = NAN
833 return r
836if _MODS.sys_version_info2 < (3, 8): # PYCHOK no cover
837 from math import hypot # OK in Python 3.7-
839 def hypot_(*xs):
840 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.
842 Similar to Python 3.8+ n-dimension U{math.hypot
843 <https://docs.Python.org/3.8/library/math.html#math.hypot>},
844 but exceptions, C{nan} and C{infinite} values are
845 handled differently.
847 @arg xs: X arguments (C{scalar}s), all positional.
849 @return: Norm (C{float}).
851 @raise OverflowError: Partial C{2sum} overflow.
853 @raise ValueError: Invalid or no B{C{xs}} values.
855 @note: The Python 3.8+ Euclidian distance U{math.dist
856 <https://docs.Python.org/3.8/library/math.html#math.dist>}
857 between 2 I{n}-dimensional points I{p1} and I{p2} can be
858 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},
859 provided I{p1} and I{p2} have the same, non-zero length I{n}.
860 '''
861 return float(_Hypot(*xs))
863elif _MODS.sys_version_info2 < (3, 10): # PYCHOK no cover
864 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see
865 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},
866 # U{cffk<https://Bugs.Python.org/issue43088>} and module
867 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}
869 def hypot(x, y):
870 '''Compute the norm M{sqrt(x**2 + y**2)}.
872 @arg x: X argument (C{scalar}).
873 @arg y: Y argument (C{scalar}).
875 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).
876 '''
877 return float(_Hypot(x, y))
879 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9
880else:
881 from math import hypot # PYCHOK in Python 3.10+
882 hypot_ = hypot
885def _Hypot(*xs):
886 '''(INTERNAL) Substitute for inaccurate C{math.hypot}.
887 '''
888 return Fhypot(*xs, nonfinites=True, raiser=False) # f2product=True
891def hypot1(x):
892 '''Compute the norm M{sqrt(1 + x**2)}.
894 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
896 @return: Norm (C{float} or L{Fhypot}).
897 '''
898 h = _1_0
899 if x:
900 if _isFsum_2Tuple(x):
901 h = _Hypot(h, x)
902 h = float(h)
903 else:
904 h = hypot(h, x)
905 return h
908def hypot2(x, y, *xy0):
909 '''Compute the I{squared} norm M{x**2 + y**2}.
911 @arg x: X (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
912 @arg y: Y (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
913 @arg xy0: Optional reference C{(x0, y0)} (each C{scalar},
914 an L{Fsum} or L{Fsum2Tuple}).
916 @return: C{B{x}**2 + B{y}**2} (C{float}).
917 '''
918 x, y = _map0(abs, x, y, *xy0) # NOT fabs!
919 if y > x:
920 x, y = y, x
921 h2 = x**2
922 if h2 and y:
923 h2 *= (y / x)**2 + _1_0
924 return float(h2)
927def hypot2_(*xs):
928 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.
930 @arg xs: Components (each C{scalar}, an L{Fsum} or
931 L{Fsum2Tuple}), all positional.
933 @return: Squared norm (C{float}).
935 @see: Class L{Fpowers} for further details.
936 '''
937 h2 = float(max(map(abs, xs))) if xs else _0_0
938 if h2: # and isfinite(h2)
939 _h = _1_0 / h2
940 xs = ((x * _h) for x in xs)
941 H2 = Fpowers(2, *xs, nonfinites=True) # f2product=True
942 h2 = H2.fover(_h**2)
943 return h2
946def _map0(_f, x, y, x0=_0_0, y0=_0_0, *unused):
947 return _f(x - x0), _f(y - y0)
950def norm2(x, y, *xy0):
951 '''Normalize a 2-dimensional vector.
953 @arg x: X component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
954 @arg y: Y component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
955 @arg xy0: Optional reference C{(x0, y0)} (each C{scalar}, an
956 L{Fsum} or L{Fsum2Tuple}).
958 @return: 2-Tuple C{(x, y)}, normalized.
960 @raise ValueError: Invalid B{C{x}} or B{C{y}}.
961 '''
962 try:
963 h = None
964 x, y = _map0(float, x, y, *xy0)
965 h = hypot(x, y)
966 if h:
967 t = (x / h), (y / h)
968 else:
969 t = (_copysign_0_0(x), # pass?
970 _copysign_0_0(y))
971 except Exception as X:
972 raise _xError(X, x=x, y=y, h=h)
973 return t
976def norm_(*xs):
977 '''Normalize the components of an n-dimensional vector.
979 @arg xs: Components (each C{scalar}, an L{Fsum} or
980 L{Fsum2Tuple}), all positional.
982 @return: Yield each component, normalized.
984 @raise ValueError: Invalid or insufficent B{C{xs}}
985 or zero norm.
986 '''
987 try:
988 i = h = None
989 x = xs
990 h = hypot_(*xs)
991 _h = (_1_0 / h) if h else _0_0
992 for i, x in enumerate(xs):
993 yield x * _h
994 except Exception as X:
995 raise _xsError(X, xs, i, x, h=h)
998def polar2(x, y, *xy0):
999 '''Return 2-tuple C{(length, angle)} with C{angle} in radians M{[0..+PI2)}.
1001 @arg x: X (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1002 @arg y: Y (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1003 @arg xy0: Optional reference C{(x0, y0)} (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1005 @note: Use C{polar(B{y}, B{x}, *B{yx0})} to get the angle as C{bearing} from North.
1006 '''
1007 x, y = _map0(float, x, y, *xy0)
1008 return hypot(x, y), _MODS.utily.atan2p(y, x)
1011def polar2d(x, y, *xy0):
1012 '''Return 2-tuple C{(length, angle)} with C{angle} in degrees M{[0..+360)}.
1014 @arg x: X (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1015 @arg y: Y (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1016 @arg xy0: Optional reference C{(x0, y0)} (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1018 @note: Use C{polar2d(B{y}, B{x}, *B{yx0})} to get the angle as C{bearing} from North.
1019 '''
1020 x, y = _map0(float, x, y, *xy0)
1021 return hypot(x, y), _MODS.utily.atan2b(y, x)
1024def _powers(x, n):
1025 '''(INTERNAL) Yield C{x**i for i=1..n}.
1026 '''
1027 p = 1 # type(p) == type(x)
1028 for _ in range(n):
1029 p *= x
1030 yield p
1033def _root(x, p, where):
1034 '''(INTERNAL) Raise C{x} to power C{0 <= p < 1}.
1035 '''
1036 try:
1037 if x > 0:
1038 r = Fsum(f2product=True, nonfinites=True)(x)
1039 return r.fpow(p).as_iscalar
1040 elif x < 0:
1041 raise ValueError(_negative_)
1042 except Exception as X:
1043 raise _xError(X, unstr(where, x))
1044 return _0_0 if p else _1_0 # x == 0
1047def sqrt0(x, Error=None):
1048 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},
1049 preserving C{type(B{x})}.
1051 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1052 @kwarg Error: Error to raise for negative B{C{x}}.
1054 @return: Square root (C{float} or L{Fsum}) or C{0.0}.
1056 @raise TypeeError: Invalid B{C{x}}.
1058 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}
1059 returns C{0.0}.
1060 '''
1061 if Error and x < 0:
1062 raise Error(unstr(sqrt0, x))
1063 return _root(x, _0_5, sqrt0) if x > EPS02 else (
1064 _0_0 if x < EPS02 else EPS0)
1067def sqrt3(x):
1068 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},
1069 preserving C{type(B{x})}.
1071 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1073 @return: Square root I{cubed} (C{float} or L{Fsum}).
1075 @raise TypeeError: Invalid B{C{x}}.
1077 @raise ValueError: Negative B{C{x}}.
1079 @see: Functions L{cbrt} and L{cbrt2}.
1080 '''
1081 return _root(x, _1_5, sqrt3)
1084def sqrt_a(h, b):
1085 '''Compute the C{I{a}} side of a right-angled triangle from
1086 C{sqrt(B{h}**2 - B{b}**2)}.
1088 @arg h: Hypotenuse or outer annulus radius (C{scalar}).
1089 @arg b: Triangle side or inner annulus radius (C{scalar}).
1091 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).
1093 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.
1095 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.
1097 @see: Inner tangent chord B{I{d}} of an U{annulus
1098 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}
1099 and function U{annulus_area<https://People.SC.FSU.edu/
1100 ~jburkardt/py_src/geometry/geometry.py>}.
1101 '''
1102 try:
1103 if not (_isHeight(h) and _isRadius(b)):
1104 raise TypeError(_not_scalar_)
1105 c = fabs(h)
1106 if c > EPS0:
1107 s = _1_0 - (b / c)**2
1108 if s < 0:
1109 raise ValueError(_h_lt_b_)
1110 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)
1111 else: # PYCHOK no cover
1112 b = fabs(b)
1113 d = c - b
1114 if d < 0:
1115 raise ValueError(_h_lt_b_)
1116 d *= c + b
1117 a = sqrt(d) if d else _0_0
1118 except Exception as x:
1119 raise _xError(x, h=h, b=b)
1120 return copysign0(a, h)
1123def zcrt(x):
1124 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},
1125 preserving C{type(B{x})}.
1127 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1129 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).
1131 @see: Functions L{bqrt} and L{zqrt}.
1133 @raise TypeeError: Invalid B{C{x}}.
1135 @raise ValueError: Negative B{C{x}}.
1136 '''
1137 return _root(x, _1_6th, zcrt)
1140def zqrt(x):
1141 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,
1142 M{x**(1 / 8)}, preserving C{type(B{x})}.
1144 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1146 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).
1148 @see: Functions L{bqrt} and L{zcrt}.
1150 @raise TypeeError: Invalid B{C{x}}.
1152 @raise ValueError: Negative B{C{x}}.
1153 '''
1154 return _root(x, _0_125, zqrt)
1156# **) MIT License
1157#
1158# Copyright (C) 2016-2026 -- mrJean1 at Gmail -- All Rights Reserved.
1159#
1160# Permission is hereby granted, free of charge, to any person obtaining a
1161# copy of this software and associated documentation files (the "Software"),
1162# to deal in the Software without restriction, including without limitation
1163# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1164# and/or sell copies of the Software, and to permit persons to whom the
1165# Software is furnished to do so, subject to the following conditions:
1166#
1167# The above copyright notice and this permission notice shall be included
1168# in all copies or substantial portions of the Software.
1169#
1170# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1171# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1172# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1173# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1174# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1175# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1176# OTHER DEALINGS IN THE SOFTWARE.