Coverage for pygeodesy/fmath.py: 91%
323 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-25 13:15 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-25 13:15 -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 _ # PYCHOK semicolon
10from pygeodesy.basics import _copysign, copysign0, isbool, isint, isscalar, \
11 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, Float_ # PYCHOK for .heights
24from math import fabs, sqrt # pow
25import operator as _operator # in .datums, .trf, .utm
27__all__ = _ALL_LAZY.fmath
28__version__ = '25.04.18'
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{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 Fhorner(Fsum):
70 '''Precision polynomial evaluation using the Horner form.
71 '''
72 def __init__(self, x, *cs, **incx_name_f2product_nonfinites_RESIDUAL):
73 '''New L{Fhorner} form evaluation of polynomial M{sum(cs[i] * x**i for
74 i=0..n)} with in- or decreasing exponent M{sum(... i=n..0)}, where C{n
75 = len(cs) - 1}.
77 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
78 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
79 all positional.
80 @kwarg incx_name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str}),
81 C{B{incx}=True} for in-/decreasing exponents (C{bool}) and other
82 settings, see class L{Fsum<Fsum.__init__>}.
84 @raise OverflowError: Partial C{2sum} overflow.
86 @raise TypeError: Invalid B{C{x}}.
88 @raise ValueError: Non-finite B{C{x}}.
90 @see: Function L{fhorner} and methods L{Fsum.fadd} and L{Fsum.fmul}.
91 '''
92 incx, kwds = _xkwds_pop2(incx_name_f2product_nonfinites_RESIDUAL, incx=True)
93 Fsum.__init__(self, **kwds)
94 self._fhorner(x, cs, Fhorner, incx=incx)
97class Fhypot(Fsum):
98 '''Precision summation and hypotenuse, default C{root=2}.
99 '''
100 def __init__(self, *xs, **root_name_f2product_nonfinites_RESIDUAL_raiser):
101 '''New L{Fhypot} hypotenuse of (the I{root} of) several components (raised
102 to the power I{root}).
104 @arg xs: Components (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
105 positional.
106 @kwarg root_name_f2product_nonfinites_RESIDUAL_raiser: Optional, exponent
107 and C{B{root}=2} order (C{scalar}), C{B{name}=NN} (C{str}),
108 C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s and
109 other settings, see class L{Fsum<Fsum.__init__>} and method
110 L{root<Fsum.root>}.
111 '''
112 def _r_X_kwds(power=None, raiser=True, root=2, **kwds):
113 # DEPRECATED keyword argument C{power=2}, use C{root=2}
114 return (root if power is None else power), raiser, kwds
116 r = None # _xkwds_pop2 error
117 try:
118 r, X, kwds = _r_X_kwds(**root_name_f2product_nonfinites_RESIDUAL_raiser)
119 Fsum.__init__(self, **kwds)
120 self(_0_0)
121 if xs:
122 self._facc_power(r, xs, Fhypot, raiser=X)
123 self._fset(self.root(r, raiser=X))
124 except Exception as X:
125 raise self._ErrorXs(X, xs, root=r)
128class Fpolynomial(Fsum):
129 '''Precision polynomial evaluation.
130 '''
131 def __init__(self, x, *cs, **name_f2product_nonfinites_RESIDUAL):
132 '''New L{Fpolynomial} evaluation of the polynomial M{sum(cs[i] * x**i for
133 i=0..len(cs)-1)}.
135 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
136 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
137 all positional.
138 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str})
139 and other settings, see class L{Fsum<Fsum.__init__>}.
141 @raise OverflowError: Partial C{2sum} overflow.
143 @raise TypeError: Invalid B{C{x}}.
145 @raise ValueError: Non-finite B{C{x}}.
147 @see: Class L{Fhorner}, function L{fpolynomial} and method L{Fsum.fadd}.
148 '''
149 Fsum.__init__(self, **name_f2product_nonfinites_RESIDUAL)
150 n = len(cs) - 1
151 self(_0_0 if n < 0 else cs[0])
152 self._facc_dot(n, cs[1:], _powers(x, n), **name_f2product_nonfinites_RESIDUAL)
155class Fpowers(Fsum):
156 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.
157 '''
158 def __init__(self, power, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
159 '''New L{Fpowers} sum of (the I{power} of) several bases.
161 @arg power: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
162 @arg xs: One or more bases (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
163 positional.
164 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}
165 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s
166 and other settings, see class L{Fsum<Fsum.__init__>} and method
167 L{fpow<Fsum.fpow>}.
168 '''
169 try:
170 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)
171 Fsum.__init__(self, **kwds)
172 self(_0_0)
173 if xs:
174 self._facc_power(power, xs, Fpowers, raiser=X) # x**0 == 1
175 except Exception as X:
176 raise self._ErrorXs(X, xs, power=power)
179class Froot(Fsum):
180 '''The root of a precision summation.
181 '''
182 def __init__(self, root, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
183 '''New L{Froot} root of a precision sum.
185 @arg root: The order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}), non-zero.
186 @arg xs: Items to summate (each a C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
187 positional.
188 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}
189 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s
190 and other settings, see class L{Fsum<Fsum.__init__>} and method
191 L{fpow<Fsum.fpow>}.
192 '''
193 try:
194 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)
195 Fsum.__init__(self, **kwds)
196 self(_0_0)
197 if xs:
198 self.fadd(xs)
199 self(self.root(root, raiser=X))
200 except Exception as X:
201 raise self._ErrorXs(X, xs, root=root)
204class Fcbrt(Froot):
205 '''Cubic root of a precision summation.
206 '''
207 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
208 '''New L{Fcbrt} cubic root of a precision sum.
210 @see: Class L{Froot<Froot.__init__>} for further details.
211 '''
212 Froot.__init__(self, 3, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)
215class Fsqrt(Froot):
216 '''Square root of a precision summation.
217 '''
218 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):
219 '''New L{Fsqrt} square root of a precision sum.
221 @see: Class L{Froot<Froot.__init__>} for further details.
222 '''
223 Froot.__init__(self, 2, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)
226def bqrt(x):
227 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)},
228 preserving C{type(B{x})}.
230 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
232 @return: I{Quartic} root (C{float} or an L{Fsum}).
234 @raise TypeeError: Invalid B{C{x}}.
236 @raise ValueError: Negative B{C{x}}.
238 @see: Functions L{zcrt} and L{zqrt}.
239 '''
240 return _root(x, _0_25, bqrt)
243try:
244 from math import cbrt as _cbrt # Python 3.11+
246except ImportError: # Python 3.10-
248 def _cbrt(x):
249 '''(INTERNAL) Compute the I{signed}, cube root M{x**(1/3)}.
250 '''
251 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>
252 # simpler and more accurate than Ken Turkowski's CubeRoot, see
253 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>
254 return _copysign(pow(fabs(x), _1_3rd), x) # to avoid complex
257def cbrt(x):
258 '''Compute the cube root M{x**(1/3)}, preserving C{type(B{x})}.
260 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
262 @return: Cubic root (C{float} or L{Fsum}).
264 @see: Functions L{cbrt2} and L{sqrt3}.
265 '''
266 if _isFsum_2Tuple(x):
267 r = abs(x).fpow(_1_3rd)
268 if x.signOf() < 0:
269 r = -r
270 else:
271 r = _cbrt(x)
272 return r # cbrt(-0.0) == -0.0
275def cbrt2(x): # PYCHOK attr
276 '''Compute the cube root I{squared} M{x**(2/3)}, preserving C{type(B{x})}.
278 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
280 @return: Cube root I{squared} (C{float} or L{Fsum}).
282 @see: Functions L{cbrt} and L{sqrt3}.
283 '''
284 return abs(x).fpow(_2_3rd) if _isFsum_2Tuple(x) else _cbrt(x**2)
287def euclid(x, y):
288 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by M{max(abs(x),
289 abs(y)) + min(abs(x), abs(y)) * 0.4142...}.
291 @arg x: X component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
292 @arg y: Y component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
294 @return: Appoximate norm (C{float} or L{Fsum}).
296 @see: Function L{euclid_}.
297 '''
298 x, y = abs(x), abs(y) # NOT fabs!
299 return (x + y * _0_4142) if x > y else \
300 (y + x * _0_4142) # * _0_5 before 20.10.02
303def euclid_(*xs):
304 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))} by cascaded
305 L{euclid}.
307 @arg xs: X arguments (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
308 all positional.
310 @return: Appoximate norm (C{float} or L{Fsum}).
312 @see: Function L{euclid}.
313 '''
314 e = _0_0
315 for x in sorted(map(abs, xs)): # NOT fabs, reverse=True!
316 # e = euclid(x, e)
317 if e < x:
318 e, x = x, e
319 if x:
320 e += x * _0_4142
321 return e
324def facos1(x):
325 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}, scalar.
327 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/
328 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.
329 '''
330 a = fabs(x)
331 if a < EPS0:
332 r = PI_2
333 elif a < EPS1:
334 r = _fast(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)
335 r *= sqrt(_1_0 - a)
336 if x < 0:
337 r = PI - r
338 else:
339 r = PI if x < 0 else _0_0
340 return r
343def fasin1(x): # PYCHOK no cover
344 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}, scalar.
346 @see: L{facos1}.
347 '''
348 return PI_2 - facos1(x)
351def _fast(x, *cs):
352 '''(INTERNAL) Horner form for C{facos1} and C{fatan1}.
353 '''
354 h = 0
355 for c in reversed(cs):
356 h = _fma(x, h, c) if h else c
357 return h
360def fatan(x):
361 '''Fast approximation of C{atan(B{x})}, scalar.
362 '''
363 a = fabs(x)
364 if a < _1_0:
365 r = fatan1(a) if a else _0_0
366 elif a > _1_0:
367 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)
368 else:
369 r = PI_4
370 if x < 0: # copysign0(r, x)
371 r = -r
372 return r
375def fatan1(x):
376 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} < 1}, I{unchecked}.
378 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/
379 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations
380 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/
381 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},
382 IEEE Signal Processing Magazine, 111, May 2006.
383 '''
384 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1
385 # == PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x < 1
386 # == x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))
387 return _fast(x, _0_0, 1.0300981634, -0.1784, -0.0663)
390def fatan2(y, x):
391 '''Fast approximation of C{atan2(B{y}, B{x})}, scalar.
393 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/
394 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}
395 and L{fatan1}.
396 '''
397 a, b = fabs(x), fabs(y)
398 if b > a:
399 r = (PI_2 - fatan1(a / b)) if a else PI_2
400 elif a > b:
401 r = fatan1(b / a) if b else _0_0
402 elif a: # a == b != 0
403 r = PI_4
404 else: # a == b == 0
405 return _0_0
406 if x < 0:
407 r = PI - r
408 if y < 0: # copysign0(r, y)
409 r = -r
410 return r
413def favg(a, b, f=_0_5, nonfinites=True):
414 '''Return the precise average of two values.
416 @arg a: One (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
417 @arg b: Other (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
418 @kwarg f: Optional fraction (C{float}).
419 @kwarg nonfinites: Optional setting, see function L{fma}.
421 @return: M{a + f * (b - a)} (C{float}).
422 '''
423 F = fma(f, (b - a), a, nonfinites=nonfinites)
424 return float(F)
427def fdot(xs, *ys, **start_f2product_nonfinites):
428 '''Return the precision dot product M{sum(xs[i] * ys[i] for i in range(len(xs)))}.
430 @arg xs: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
431 @arg ys: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
432 @kwarg start_f2product_nonfinites: Optional bias C{B{start}=0} (C{scalar}, an
433 L{Fsum} or L{Fsum2Tuple}) and settings C{B{f2product}=None} (C{bool})
434 and C{B{nonfinites=True}} (C{bool}), see class L{Fsum<Fsum.__init__>}.
436 @return: Dot product (C{float}).
438 @raise LenError: Unequal C{len(B{xs})} and C{len(B{ys})}.
440 @see: Class L{Fdot}, U{Algorithm 5.10 B{DotK}
441 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} and function
442 C{math.sumprod} in Python 3.12 and later.
443 '''
444 D = Fdot(xs, *ys, **_xkwds(start_f2product_nonfinites, nonfinites=True))
445 return float(D)
448def fdot_(*xys, **start_f2product_nonfinites):
449 '''Return the (precision) dot product M{sum(xys[i] * xys[i+1] for i in range(0, len(xys), B{2}))}.
451 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
453 @see: Function L{fdot} for further details.
455 @return: Dot product (C{float}).
456 '''
457 return fdot(xys[0::2], *xys[1::2], **start_f2product_nonfinites)
460def fdot3(xs, ys, zs, **start_f2product_nonfinites):
461 '''Return the (precision) dot product M{start + sum(xs[i] * ys[i] * zs[i] for i in range(len(xs)))}.
463 @arg xs: X values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
464 @arg ys: Y values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
465 @arg zs: Z values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
467 @see: Function L{fdot} for further details.
469 @return: Dot product (C{float}).
471 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})} and/or C{len(B{zs})}.
472 '''
473 n = len(xs)
474 if not n == len(ys) == len(zs):
475 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))
477 D = Fdot((), **_xkwds(start_f2product_nonfinites, nonfinites=True))
478 kwds = dict(f2product=D.f2product(), nonfinites=D.nonfinites())
479 _f = Fsum(**kwds)
480 D = D._facc(_f(x).f2mul_(y, z, **kwds) for x, y, z in zip(xs, ys, zs))
481 return float(D)
484def fhorner(x, *cs, **incx):
485 '''Horner form evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)} as
486 in- or decreasing exponent M{sum(... i=n..0)}, where C{n = len(cs) - 1}.
488 @return: Horner sum (C{float}).
490 @see: Class L{Fhorner<Fhorner.__init__>} for further details.
491 '''
492 H = Fhorner(x, *cs, **incx)
493 return float(H)
496def fidw(xs, ds, beta=2):
497 '''Interpolate using U{Inverse Distance Weighting
498 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).
500 @arg xs: Known values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
501 @arg ds: Non-negative distances (each C{scalar}, an L{Fsum} or
502 L{Fsum2Tuple}).
503 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).
505 @return: Interpolated value C{x} (C{float}).
507 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.
509 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.
511 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or
512 weighted B{C{ds}} below L{EPS}.
514 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.
515 '''
516 n, xs = len2(xs)
517 if n > 1:
518 b = -Int_(beta=beta, low=0, high=3)
519 if b < 0:
520 try: # weighted
521 _d, W, X = (Fsum() for _ in range(3))
522 for i, d in enumerate(_xiterable(ds)):
523 x = xs[i]
524 D = _d(d)
525 if D < EPS0:
526 if D < 0:
527 raise ValueError(_negative_)
528 x = float(x)
529 i = n
530 break
531 if D.fpow(b):
532 W += D
533 X += D.fmul(x)
534 else:
535 x = X.fover(W, raiser=False)
536 i += 1 # len(xs) >= len(ds)
537 except IndexError:
538 i += 1 # len(xs) < i < len(ds)
539 except Exception as X:
540 _I = Fmt.INDEX
541 raise _xError(X, _I(xs=i), x,
542 _I(ds=i), d)
543 else: # b == 0
544 x = fsum(xs) / n # fmean(xs)
545 i = n
546 elif n:
547 x = float(xs[0])
548 i = n
549 else:
550 x = _0_0
551 i, _ = len2(ds)
552 if i != n:
553 raise LenError(fidw, xs=n, ds=i)
554 return x
557try:
558 from math import fma as _fma
559except ImportError: # PYCHOK DSPACE!
561 def _fma(x, y, z): # no need for accuracy
562 return x * y + z
565def fma(x, y, z, **nonfinites): # **raiser
566 '''Fused-multiply-add, using C{math.fma(x, y, z)} in Python 3.13+
567 or an equivalent implementation.
569 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
570 @arg y: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
571 @arg z: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
572 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False},
573 to override default L{nonfiniterrors}
574 (C{bool}), see method L{Fsum.fma}.
576 @return: C{(x * y) + z} (C{float} or L{Fsum}).
577 '''
578 F, raiser = _Fm2(x, **nonfinites)
579 return F.fma(y, z, **raiser).as_iscalar
582def _Fm2(x, nonfinites=None, **raiser):
583 '''(INTERNAL) Handle C{fma} and C{f2mul} DEPRECATED C{raiser=False}.
584 '''
585 return Fsum(x, nonfinites=nonfinites), raiser
588def fmean(xs):
589 '''Compute the accurate mean M{sum(xs) / len(xs)}.
591 @arg xs: Values (each C{scalar}, or L{Fsum} or L{Fsum2Tuple}).
593 @return: Mean value (C{float}).
595 @raise LenError: No B{C{xs}} values.
597 @raise OverflowError: Partial C{2sum} overflow.
598 '''
599 n, xs = len2(xs)
600 if n < 1:
601 raise LenError(fmean, xs=xs)
602 M = Fsum(*xs, nonfinites=True)
603 return M.fover(n) if n > 1 else float(M)
606def fmean_(*xs, **nonfinites):
607 '''Compute the accurate mean M{sum(xs) / len(xs)}.
609 @see: Function L{fmean} for further details.
610 '''
611 return fmean(xs, **nonfinites)
614def f2mul_(x, *ys, **nonfinites): # **raiser
615 '''Cascaded, accurate multiplication C{B{x} * B{y} * B{y} ...} for all B{C{ys}}.
617 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
618 @arg ys: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
619 positional.
620 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False}, to override default
621 L{nonfiniterrors} (C{bool}), see method L{Fsum.f2mul_}.
623 @return: The cascaded I{TwoProduct} (C{float}, C{int} or L{Fsum}).
625 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
626 '''
627 F, raiser = _Fm2(x, **nonfinites)
628 return F.f2mul_(*ys, **raiser).as_iscalar
631def fpolynomial(x, *cs, **over_f2product_nonfinites):
632 '''Evaluate the polynomial M{sum(cs[i] * x**i for i=0..len(cs)) [/ over]}.
634 @kwarg over_f2product_nonfinites: Optional final divisor C{B{over}=None}
635 (I{non-zero} C{scalar}) and other settings, see class
636 L{Fpolynomial<Fpolynomial.__init__>}.
638 @return: Polynomial value (C{float} or L{Fpolynomial}).
639 '''
640 d, kwds = _xkwds_pop2(over_f2product_nonfinites, over=0)
641 P = Fpolynomial(x, *cs, **kwds)
642 return P.fover(d) if d else float(P)
645def fpowers(x, n, alts=0):
646 '''Return a series of powers M{[x**i for i=1..n]}, note I{1..!}
648 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
649 @arg n: Highest exponent (C{int}).
650 @kwarg alts: Only alternating powers, starting with this
651 exponent (C{int}).
653 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).
655 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.
657 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.
658 '''
659 if not isint(n):
660 raise _IsnotError(typename(int), n=n)
661 elif n < 1:
662 raise _ValueError(n=n)
664 p = x if isscalar(x) or _isFsum_2Tuple(x) else _2float(x=x)
665 ps = tuple(_powers(p, n))
667 if alts > 0: # x**2, x**4, ...
668 # ps[alts-1::2] chokes PyChecker
669 ps = ps[slice(alts-1, None, 2)]
671 return ps
674try:
675 from math import prod as fprod # Python 3.8
676except ImportError:
678 def fprod(xs, start=1):
679 '''Iterable product, like C{math.prod} or C{numpy.prod}.
681 @arg xs: Iterable of values to be multiplied (each
682 C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
683 @kwarg start: Initial value, also the value returned
684 for an empty B{C{xs}} (C{scalar}).
686 @return: The product (C{float} or L{Fsum}).
688 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
689 numpy/reference/generated/numpy.prod.html>}.
690 '''
691 return freduce(_operator.mul, xs, start)
694def frandoms(n, seeded=None):
695 '''Generate C{n} (long) lists of random C{floats}.
697 @arg n: Number of lists to generate (C{int}, non-negative).
698 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or
699 if C{True}, seed using today's C{year-day}.
701 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/
702 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.
703 '''
704 from random import gauss, random, seed, shuffle
706 if seeded is None:
707 pass
708 elif seeded and isbool(seeded):
709 from time import localtime
710 seed(localtime().tm_yday)
711 elif isscalar(seeded):
712 seed(seeded)
714 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 7
715 for _ in range(n):
716 s = 0
717 t = list(c)
718 _a = t.append
719 for _ in range(n * 8):
720 v = gauss(0, random())**7 - s
721 _a(v)
722 s += v
723 shuffle(t)
724 yield t
727def frange(start, number, step=1):
728 '''Generate a range of C{float}s.
730 @arg start: First value (C{float}).
731 @arg number: The number of C{float}s to generate (C{int}).
732 @kwarg step: Increment value (C{float}).
734 @return: A generator (C{float}s).
736 @see: U{NumPy.prod<https://docs.SciPy.org/doc/
737 numpy/reference/generated/numpy.arange.html>}.
738 '''
739 if not isint(number):
740 raise _IsnotError(typename(int), number=number)
741 for i in range(number):
742 yield start + (step * i)
745try:
746 from functools import reduce as freduce
747except ImportError:
748 try:
749 freduce = reduce # PYCHOK expected
750 except NameError: # Python 3+
752 def freduce(f, xs, *start):
753 '''For missing C{functools.reduce}.
754 '''
755 if start:
756 r = v = start[0]
757 else:
758 r, v = 0, MISSING
759 for v in xs:
760 r = f(r, v)
761 if v is MISSING:
762 raise _TypeError(xs=(), start=MISSING)
763 return r
766def fremainder(x, y):
767 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.
769 @arg x: Numerator (C{scalar}).
770 @arg y: Modulus, denominator (C{scalar}).
772 @return: Remainder (C{scalar}, preserving signed
773 0.0) or C{NAN} for any non-finite B{C{x}}.
775 @raise ValueError: Infinite or near-zero B{C{y}}.
777 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/
778 project/geographiclib/>} and Python 3.7+
779 U{math.remainder<https://docs.Python.org/3/
780 library/math.html#math.remainder>}.
781 '''
782 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and
783 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native
784 # fmod( 0, 360) == 0.0
785 # fmod( 360, 360) == 0.0
786 # fmod(-0, 360) == 0.0
787 # fmod(-0.0, 360) == -0.0
788 # fmod(-360, 360) == -0.0
789 # however, using the % operator ...
790 # 0 % 360 == 0
791 # 360 % 360 == 0
792 # 360.0 % 360 == 0.0
793 # -0 % 360 == 0
794 # -360 % 360 == 0 == (-360) % 360
795 # -0.0 % 360 == 0.0 == (-0.0) % 360
796 # -360.0 % 360 == 0.0 == (-360.0) % 360
798 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)
799 # == +0.0. This fixes this bug. See also Math::AngNormalize
800 # in the C++ library, Math.sincosd has a similar fix.
801 if isfinite(x):
802 try:
803 r = remainder(x, y) if x else x
804 except Exception as e:
805 raise _xError(e, unstr(fremainder, x, y))
806 else: # handle x INF and NINF as NAN
807 r = NAN
808 return r
811if _MODS.sys_version_info2 < (3, 8): # PYCHOK no cover
812 from math import hypot # OK in Python 3.7-
814 def hypot_(*xs):
815 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.
817 Similar to Python 3.8+ n-dimension U{math.hypot
818 <https://docs.Python.org/3.8/library/math.html#math.hypot>},
819 but exceptions, C{nan} and C{infinite} values are
820 handled differently.
822 @arg xs: X arguments (C{scalar}s), all positional.
824 @return: Norm (C{float}).
826 @raise OverflowError: Partial C{2sum} overflow.
828 @raise ValueError: Invalid or no B{C{xs}} values.
830 @note: The Python 3.8+ Euclidian distance U{math.dist
831 <https://docs.Python.org/3.8/library/math.html#math.dist>}
832 between 2 I{n}-dimensional points I{p1} and I{p2} can be
833 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},
834 provided I{p1} and I{p2} have the same, non-zero length I{n}.
835 '''
836 return float(_Hypot(*xs))
838elif _MODS.sys_version_info2 < (3, 10): # PYCHOK no cover
839 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see
840 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},
841 # U{cffk<https://Bugs.Python.org/issue43088>} and module
842 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}
844 def hypot(x, y):
845 '''Compute the norm M{sqrt(x**2 + y**2)}.
847 @arg x: X argument (C{scalar}).
848 @arg y: Y argument (C{scalar}).
850 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).
851 '''
852 return float(_Hypot(x, y))
854 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9
855else:
856 from math import hypot # PYCHOK in Python 3.10+
857 hypot_ = hypot
860def _Hypot(*xs):
861 '''(INTERNAL) Substitute for inaccurate C{math.hypot}.
862 '''
863 return Fhypot(*xs, nonfinites=True, raiser=False) # f2product=True
866def hypot1(x):
867 '''Compute the norm M{sqrt(1 + x**2)}.
869 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).
871 @return: Norm (C{float} or L{Fhypot}).
872 '''
873 h = _1_0
874 if x:
875 if _isFsum_2Tuple(x):
876 h = _Hypot(h, x)
877 h = float(h)
878 else:
879 h = hypot(h, x)
880 return h
883def hypot2(x, y):
884 '''Compute the I{squared} norm M{x**2 + y**2}.
886 @arg x: X (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
887 @arg y: Y (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
889 @return: C{B{x}**2 + B{y}**2} (C{float}).
890 '''
891 x, y = map1(abs, x, y) # NOT fabs!
892 if y > x:
893 x, y = y, x
894 h2 = x**2
895 if h2 and y:
896 h2 *= (y / x)**2 + _1_0
897 return float(h2)
900def hypot2_(*xs):
901 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.
903 @arg xs: Components (each C{scalar}, an L{Fsum} or
904 L{Fsum2Tuple}), all positional.
906 @return: Squared norm (C{float}).
908 @see: Class L{Fpowers} for further details.
909 '''
910 h2 = float(max(map(abs, xs))) if xs else _0_0
911 if h2: # and isfinite(h2)
912 _h = _1_0 / h2
913 xs = ((x * _h) for x in xs)
914 H2 = Fpowers(2, *xs, nonfinites=True) # f2product=True
915 h2 = H2.fover(_h**2)
916 return h2
919def norm2(x, y):
920 '''Normalize a 2-dimensional vector.
922 @arg x: X component (C{scalar}).
923 @arg y: Y component (C{scalar}).
925 @return: 2-Tuple C{(x, y)}, normalized.
927 @raise ValueError: Invalid B{C{x}} or B{C{y}}
928 or zero norm.
929 '''
930 try:
931 h = None
932 h = hypot(x, y)
933 if h:
934 x, y = (x / h), (y / h)
935 else:
936 x = _copysign_0_0(x) # pass?
937 y = _copysign_0_0(y)
938 except Exception as e:
939 raise _xError(e, x=x, y=y, h=h)
940 return x, y
943def norm_(*xs):
944 '''Normalize the components of an n-dimensional vector.
946 @arg xs: Components (each C{scalar}, an L{Fsum} or
947 L{Fsum2Tuple}), all positional.
949 @return: Yield each component, normalized.
951 @raise ValueError: Invalid or insufficent B{C{xs}}
952 or zero norm.
953 '''
954 try:
955 i = h = None
956 x = xs
957 h = hypot_(*xs)
958 _h = (_1_0 / h) if h else _0_0
959 for i, x in enumerate(xs):
960 yield x * _h
961 except Exception as X:
962 raise _xsError(X, xs, i, x, h=h)
965def _powers(x, n):
966 '''(INTERNAL) Yield C{x**i for i=1..n}.
967 '''
968 p = 1 # type(p) == type(x)
969 for _ in range(n):
970 p *= x
971 yield p
974def _root(x, p, where):
975 '''(INTERNAL) Raise C{x} to power C{0 < p < 1}.
976 '''
977 try:
978 if x > 0:
979 r = Fsum(f2product=True, nonfinites=True)(x)
980 return r.fpow(p).as_iscalar
981 elif x < 0:
982 raise ValueError(_negative_)
983 except Exception as X:
984 raise _xError(X, unstr(where, x))
985 return _0_0 if p else _1_0
988def sqrt0(x, Error=None):
989 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},
990 preserving C{type(B{x})}.
992 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
993 @kwarg Error: Error to raise for negative B{C{x}}.
995 @return: Square root (C{float} or L{Fsum}) or C{0.0}.
997 @raise TypeeError: Invalid B{C{x}}.
999 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}
1000 returns C{0.0}.
1001 '''
1002 if Error and x < 0:
1003 raise Error(unstr(sqrt0, x))
1004 return _root(x, _0_5, sqrt0) if x > EPS02 else (
1005 _0_0 if x < EPS02 else EPS0)
1008def sqrt3(x):
1009 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},
1010 preserving C{type(B{x})}.
1012 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1014 @return: Square root I{cubed} (C{float} or L{Fsum}).
1016 @raise TypeeError: Invalid B{C{x}}.
1018 @raise ValueError: Negative B{C{x}}.
1020 @see: Functions L{cbrt} and L{cbrt2}.
1021 '''
1022 return _root(x, _1_5, sqrt3)
1025def sqrt_a(h, b):
1026 '''Compute C{I{a}} side of a right-angled triangle from
1027 C{sqrt(B{h}**2 - B{b}**2)}.
1029 @arg h: Hypotenuse or outer annulus radius (C{scalar}).
1030 @arg b: Triangle side or inner annulus radius (C{scalar}).
1032 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).
1034 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.
1036 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.
1038 @see: Inner tangent chord B{I{d}} of an U{annulus
1039 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}
1040 and function U{annulus_area<https://People.SC.FSU.edu/
1041 ~jburkardt/py_src/geometry/geometry.py>}.
1042 '''
1043 try:
1044 if not (_isHeight(h) and _isRadius(b)):
1045 raise TypeError(_not_scalar_)
1046 c = fabs(h)
1047 if c > EPS0:
1048 s = _1_0 - (b / c)**2
1049 if s < 0:
1050 raise ValueError(_h_lt_b_)
1051 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)
1052 else: # PYCHOK no cover
1053 b = fabs(b)
1054 d = c - b
1055 if d < 0:
1056 raise ValueError(_h_lt_b_)
1057 d *= c + b
1058 a = sqrt(d) if d else _0_0
1059 except Exception as x:
1060 raise _xError(x, h=h, b=b)
1061 return copysign0(a, h)
1064def zcrt(x):
1065 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},
1066 preserving C{type(B{x})}.
1068 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1070 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).
1072 @see: Functions L{bqrt} and L{zqrt}.
1074 @raise TypeeError: Invalid B{C{x}}.
1076 @raise ValueError: Negative B{C{x}}.
1077 '''
1078 return _root(x, _1_6th, zcrt)
1081def zqrt(x):
1082 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,
1083 M{x**(1 / 8)}, preserving C{type(B{x})}.
1085 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1087 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).
1089 @see: Functions L{bqrt} and L{zcrt}.
1091 @raise TypeeError: Invalid B{C{x}}.
1093 @raise ValueError: Negative B{C{x}}.
1094 '''
1095 return _root(x, _0_125, zqrt)
1097# **) MIT License
1098#
1099# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1100#
1101# Permission is hereby granted, free of charge, to any person obtaining a
1102# copy of this software and associated documentation files (the "Software"),
1103# to deal in the Software without restriction, including without limitation
1104# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1105# and/or sell copies of the Software, and to permit persons to whom the
1106# Software is furnished to do so, subject to the following conditions:
1107#
1108# The above copyright notice and this permission notice shall be included
1109# in all copies or substantial portions of the Software.
1110#
1111# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1112# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1113# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1114# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1115# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1116# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1117# OTHER DEALINGS IN THE SOFTWARE.