Coverage for pygeodesy/fsums.py: 96%
726 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-04-02 13:52 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-04-02 13:52 -0400
2# -*- coding: utf-8 -*-
4u'''Class L{Fsum} for precision floating point summation and I{running}
5summation based on, respectively similar to Python's C{math.fsum}.
7Generally, an L{Fsum} instance is considered a C{float} plus a small or zero
8C{residual} value, see property L{Fsum.residual}. However, there are several
9C{integer} L{Fsum} cases, for example the result of C{ceil}, C{floor},
10C{Fsum.__floordiv__} and methods L{Fsum.fint} and L{Fsum.fint2}.
12Also, L{Fsum} methods L{Fsum.pow}, L{Fsum.__ipow__}, L{Fsum.__pow__} and
13L{Fsum.__rpow__} return a (very long) C{int} if invoked with optional argument
14C{mod} set to C{None}. The C{residual} of an C{integer} L{Fsum} may be between
15C{-1.0} and C{+1.0}, including C{INT0} if considered to be I{exact}.
17Set env variable C{PYGEODESY_FSUM_PARTIALS} to an empty string (or anything
18other than C{"fsum"}) for backward compatible summation of L{Fsum} partials.
20Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater
21than C{"0.0"} as the threshold to throw a L{ResidualError} in division or
22exponention of an L{Fsum} instance with a I{relative} C{residual} exceeding
23the threshold, see methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
24and L{Fsum.__itruediv__}.
25'''
26# make sure int/int division yields float quotient, see .basics
27from __future__ import division as _; del _ # PYCHOK semicolon
29from pygeodesy.basics import iscomplex, isint, isscalar, itemsorted, \
30 signOf, _signOf
31from pygeodesy.constants import INT0, _isfinite, isinf, isnan, NEG0, _pos_self, \
32 _0_0, _1_0, _N_1_0, Float, Int
33from pygeodesy.errors import _OverflowError, _TypeError, _ValueError, _xError, \
34 _xError2, _xkwds_get, _ZeroDivisionError
35from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _DOT_, _EQUAL_, \
36 _exceeds_, _from_, _iadd_op_, _LANGLE_, _negative_, \
37 _NOTEQUAL_, _not_finite_, _not_scalar_, _PERCENT_, \
38 _PLUS_, _R_, _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_
39from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
40from pygeodesy.named import _Named, _NamedTuple, _NotImplemented, Fmt, unstr
41from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \
42 Property_RO, property_RO
43# from pygeodesy.streprs import Fmt, unstr # from .named
44# from pygeodesy.units import Float, Int # from .constants
46from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp
48__all__ = _ALL_LAZY.fsums
49__version__ = '24.04.02'
51_add_op_ = _PLUS_ # in .auxilats.auxAngle
52_eq_op_ = _EQUAL_ * 2 # _DEQUAL_
53_COMMASPACE_R_ = _COMMASPACE_ + _R_
54_div_ = 'div'
55_exceeds_R_ = _SPACE_ + _exceeds_(_R_)
56_floordiv_op_ = _SLASH_ * 2 # _DSLASH_
57_fset_op_ = _EQUAL_
58_ge_op_ = _RANGLE_ + _EQUAL_
59_gt_op_ = _RANGLE_
60_integer_ = 'integer'
61_le_op_ = _LANGLE_ + _EQUAL_
62_lt_op_ = _LANGLE_
63_mod_ = 'mod'
64_mod_op_ = _PERCENT_
65_mul_op_ = _STAR_
66_ne_op_ = _NOTEQUAL_
67_non_zero_ = 'non-zero'
68_pow_op_ = _STAR_ * 2 # _DSTAR_, in .fmath
69_sub_op_ = _DASH_ # in .auxilats.auxAngle, .fsums
70_truediv_op_ = _SLASH_
71_divmod_op_ = _floordiv_op_ + _mod_op_
72_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle, .fsums
75def _2float(index=None, **name_value): # in .fmath, .fstats
76 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.
77 '''
78 n, v = name_value.popitem() # _xkwds_item2(name_value)
79 try:
80 v = float(v)
81 if _isfinite(v):
82 return v
83 raise ValueError(_not_finite_)
84 except Exception as e:
85 raise _xError(e, Fmt.INDEX(n, index), v)
88def _2floats(xs, origin=0, neg=False):
89 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
90 '''
91 if neg:
92 def _X(X):
93 return X._ps_neg
95 def _x(x):
96 return -float(x)
97 else:
98 def _X(X): # PYCHOK re-def
99 return X._ps
101 _x = float
103 return _2yield(xs, origin, _X, _x)
106def _1primed(xs): # in .fmath
107 '''(INTERNAL) 1-Prime the summation of C{xs}
108 arguments I{known} to be C{finite float}.
109 '''
110 yield _1_0
111 for x in xs:
112 if x:
113 yield x
114 yield _N_1_0
117def _2ps(s, r):
118 '''(INTERNAL) Return a C{s} and C{r} pair, I{ps-ordered}.
119 '''
120 if fabs(s) < fabs(r):
121 s, r = r, s
122 return ((r, s) if s else (r,)) if r else (s,)
125def _psum(ps): # PYCHOK used!
126 '''(INTERNAL) Partials summation updating C{ps}, I{overridden below}.
127 '''
128 # assert isinstance(ps, list)
129 i = len(ps) - 1 # len(ps) > 2
130 if i < 0:
131 return _0_0
132 s = ps[i]
133 _2s = _2sum
134 while i > 0:
135 i -= 1
136 s, r = _2s(s, ps[i])
137 if r: # sum(ps) became inexact
138 ps[i:] = (s, r) if s else (r,)
139 if i > 0:
140 p = ps[i-1] # round half-even
141 if (p > 0 and r > 0) or \
142 (p < 0 and r < 0): # signs match
143 r *= 2
144 t = s + r
145 if r == (t - s):
146 s = t
147 break
148 ps[i:] = s,
149 return s
152def _2scalar(other, _raiser=None):
153 '''(INTERNAL) Return B{C{other}} as C{int}, C{float} or C{as-is}.
154 '''
155 if isinstance(other, Fsum):
156 s, r = other._fint2
157 if r:
158 s, r = other._fprs2
159 if r: # PYCHOK no cover
160 if _raiser and _raiser(r, s):
161 raise ValueError(_stresidual(_non_zero_, r))
162 s = other # L{Fsum} as-is
163 else:
164 s = other # C{type} as-is
165 if isint(s, both=True):
166 s = int(s)
167 return s
170def _strcomplex(s, *args):
171 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error C{str}.
172 '''
173 c = iscomplex.__name__[2:]
174 n = _DASH_(len(args), _arg_)
175 t = _SPACE_(c, s, _from_, n, pow.__name__)
176 return unstr(t, *args)
179def _stresidual(prefix, residual, **name_values):
180 '''(INTERNAL) Residual error C{str}.
181 '''
182 p = _SPACE_(prefix, Fsum.residual.name)
183 t = Fmt.PARENSPACED(p, Fmt(residual))
184 for n, v in itemsorted(name_values):
185 n = n.replace(_UNDER_, _SPACE_)
186 p = Fmt.PARENSPACED(n, Fmt(v))
187 t = _COMMASPACE_(t, p)
188 return t
191def _2sum(a, b): # by .testFmath
192 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual).
193 '''
194 s = a + b
195 if not _isfinite(s):
196 u = unstr(_2sum.__name__, a, b)
197 t = Fmt.PARENSPACED(_not_finite_, s)
198 raise _OverflowError(u, txt=t)
199 if fabs(a) < fabs(b):
200 a, b = b, a
201 return s, (b - (s - a))
204def _2yield(xs, i, _X_ps, _x):
205 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
206 '''
207 x = None
208 try:
209 _fin = _isfinite
210 _Fs = Fsum
211 for x in xs:
212 if isinstance(x, _Fs):
213 for p in _X_ps(x):
214 yield p
215 else:
216 f = _x(x)
217 if f:
218 if not _fin(f):
219 raise ValueError(_not_finite_)
220 yield f
221 i += 1
222 except Exception as e:
223 raise _xError(e, Fmt.INDEX(xs=i), x)
226class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase
227 '''Precision floating point summation and I{running} summation.
229 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
230 I{running}, precision floating point summations. Accumulation may continue after any
231 intermediate, I{running} summuation.
233 @note: Accumulated values may be L{Fsum} or C{scalar} instances, any C{type} having
234 method C{__float__} to convert the C{scalar} to a single C{float}.
236 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from
237 Python's C{math.fsum}.
239 @see: U{Hettinger<https://GitHub.com/ActiveState/code/blob/master/recipes/Python/
240 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}, U{Kahan
241 <https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
242 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
243 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
244 <https://Bugs.Python.org/issue2819>}.
245 '''
246 _math_fsum = None
247 _n = 0
248# _ps = [] # partial sums
249# _px = 0 # max(Fsum._px, len(Fsum._ps))
250 _ratio = None
251 _RESIDUAL = max(float(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)), _0_0)
253 def __init__(self, *xs, **name_RESIDUAL):
254 '''New L{Fsum} for I{running} precision floating point summation.
256 @arg xs: No, one or more initial values, all positional (each C{scalar}
257 or an L{Fsum} instance).
258 @kwarg name_RESIDUAL: Optional C{B{name}=NN} for this L{Fsum} and
259 C{B{RESIDUAL}=None} for the L{ResidualError} threshold.
261 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.
262 '''
263 if name_RESIDUAL:
264 n = _xkwds_get(name_RESIDUAL, name=NN)
265 if n: # set name before ...
266 self.name = n
267 r = _xkwds_get(name_RESIDUAL, RESIDUAL=None)
268 if r is not None:
269 self.RESIDUAL(r) # ... ResidualError
270# self._n = 0
271 self._ps = [] # [_0_0], see L{Fsum._fprs}
272 if len(xs) > 1:
273 self._facc(_2floats(xs, origin=1), up=False) # PYCHOK yield
274 elif xs: # len(xs) == 1
275 self._n = 1
276 self._ps[:] = _2float(x=xs[0]),
278 def __abs__(self):
279 '''Return this instance' absolute value as an L{Fsum}.
280 '''
281 s = _fsum(self._ps_1()) # == self._cmp_0(0, ...)
282 return (-self) if s < 0 else self._copy_2(self.__abs__)
284 def __add__(self, other):
285 '''Return the C{Fsum(B{self}, B{other})}.
287 @arg other: An L{Fsum} or C{scalar}.
289 @return: The sum (L{Fsum}).
291 @see: Method L{Fsum.__iadd__}.
292 '''
293 f = self._copy_2(self.__add__)
294 return f._fadd(other, _add_op_)
296 def __bool__(self): # PYCHOK not special in Python 2-
297 '''Return C{True} if this instance is I{exactly} non-zero.
298 '''
299 s, r = self._fprs2
300 return bool(s or r) and s != -r # == self != 0
302 def __ceil__(self): # PYCHOK not special in Python 2-
303 '''Return this instance' C{math.ceil} as C{int} or C{float}.
305 @return: An C{int} in Python 3+, but C{float} in Python 2-.
307 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
308 '''
309 return self.ceil
311 def __cmp__(self, other): # Python 2-
312 '''Compare this with an other instance or C{scalar}.
314 @return: -1, 0 or +1 (C{int}).
316 @raise TypeError: Incompatible B{C{other}} C{type}.
317 '''
318 s = self._cmp_0(other, self.cmp.__name__)
319 return _signOf(s, 0)
321 cmp = __cmp__
323 def __divmod__(self, other):
324 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
325 with quotient C{div} an C{int} in Python 3+ or C{float}
326 in Python 2- and remainder C{mod} an L{Fsum}.
328 @arg other: An L{Fsum} or C{scalar} modulus.
330 @see: Method L{Fsum.__itruediv__}.
331 '''
332 f = self._copy_2(self.__divmod__)
333 return f._fdivmod2(other, _divmod_op_)
335 def __eq__(self, other):
336 '''Compare this with an other instance or C{scalar}.
337 '''
338 return self._cmp_0(other, _eq_op_) == 0
340 def __float__(self):
341 '''Return this instance' current precision running sum as C{float}.
343 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
344 '''
345 return float(self._fprs)
347 def __floor__(self): # PYCHOK not special in Python 2-
348 '''Return this instance' C{math.floor} as C{int} or C{float}.
350 @return: An C{int} in Python 3+, but C{float} in Python 2-.
352 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
353 '''
354 return self.floor
356 def __floordiv__(self, other):
357 '''Return C{B{self} // B{other}} as an L{Fsum}.
359 @arg other: An L{Fsum} or C{scalar} divisor.
361 @return: The C{floor} quotient (L{Fsum}).
363 @see: Methods L{Fsum.__ifloordiv__}.
364 '''
365 f = self._copy_2(self.__floordiv__)
366 return f._floordiv(other, _floordiv_op_)
368 def __format__(self, *other): # PYCHOK no cover
369 '''Not implemented.'''
370 return _NotImplemented(self, *other)
372 def __ge__(self, other):
373 '''Compare this with an other instance or C{scalar}.
374 '''
375 return self._cmp_0(other, _ge_op_) >= 0
377 def __gt__(self, other):
378 '''Compare this with an other instance or C{scalar}.
379 '''
380 return self._cmp_0(other, _gt_op_) > 0
382 def __hash__(self): # PYCHOK no cover
383 '''Return this instance' C{hash}.
384 '''
385 return hash(self._ps) # XXX id(self)?
387 def __iadd__(self, other):
388 '''Apply C{B{self} += B{other}} to this instance.
390 @arg other: An L{Fsum} or C{scalar} instance.
392 @return: This instance, updated (L{Fsum}).
394 @raise TypeError: Invalid B{C{other}}, not
395 C{scalar} nor L{Fsum}.
397 @see: Methods L{Fsum.fadd} and L{Fsum.fadd_}.
398 '''
399 return self._fadd(other, _iadd_op_)
401 def __ifloordiv__(self, other):
402 '''Apply C{B{self} //= B{other}} to this instance.
404 @arg other: An L{Fsum} or C{scalar} divisor.
406 @return: This instance, updated (L{Fsum}).
408 @raise ResidualError: Non-zero residual in B{C{other}}.
410 @raise TypeError: Invalid B{C{other}} type.
412 @raise ValueError: Invalid or non-finite B{C{other}}.
414 @raise ZeroDivisionError: Zero B{C{other}}.
416 @see: Methods L{Fsum.__itruediv__}.
417 '''
418 return self._floordiv(other, _floordiv_op_ + _fset_op_)
420 def __imatmul__(self, other): # PYCHOK no cover
421 '''Not implemented.'''
422 return _NotImplemented(self, other)
424 def __imod__(self, other):
425 '''Apply C{B{self} %= B{other}} to this instance.
427 @arg other: An L{Fsum} or C{scalar} modulus.
429 @return: This instance, updated (L{Fsum}).
431 @see: Method L{Fsum.__divmod__}.
432 '''
433 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
435 def __imul__(self, other):
436 '''Apply C{B{self} *= B{other}} to this instance.
438 @arg other: An L{Fsum} or C{scalar} factor.
440 @return: This instance, updated (L{Fsum}).
442 @raise OverflowError: Partial C{2sum} overflow.
444 @raise TypeError: Invalid B{C{other}} type.
446 @raise ValueError: Invalid or non-finite B{C{other}}.
447 '''
448 return self._fmul(other, _mul_op_ + _fset_op_)
450 def __int__(self):
451 '''Return this instance as an C{int}.
453 @see: Methods L{Fsum.int_float}, L{Fsum.__ceil__}
454 and L{Fsum.__floor__} and properties
455 L{Fsum.ceil} and L{Fsum.floor}.
456 '''
457 i, _ = self._fint2
458 return i
460 def __invert__(self): # PYCHOK no cover
461 '''Not implemented.'''
462 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
463 return _NotImplemented(self)
465 def __ipow__(self, other, *mod): # PYCHOK 2 vs 3 args
466 '''Apply C{B{self} **= B{other}} to this instance.
468 @arg other: The exponent (L{Fsum} or C{scalar}).
469 @arg mod: Optional modulus (C{int} or C{None}) for the
470 3-argument C{pow(B{self}, B{other}, B{mod})}
471 version.
473 @return: This instance, updated (L{Fsum}).
475 @note: If B{C{mod}} is given, the result will be an C{integer}
476 L{Fsum} in Python 3+ if this instance C{is_integer} or
477 set to C{as_integer} if B{C{mod}} given as C{None}.
479 @raise OverflowError: Partial C{2sum} overflow.
481 @raise ResidualError: Non-zero residual in B{C{other}} and
482 env var C{PYGEODESY_FSUM_RESIDUAL}
483 set or this instance has a non-zero
484 residual and either B{C{mod}} is
485 given and non-C{None} or B{C{other}}
486 is a negative or fractional C{scalar}.
488 @raise TypeError: Invalid B{C{other}} type or 3-argument
489 C{pow} invocation failed.
491 @raise ValueError: If B{C{other}} is a negative C{scalar}
492 and this instance is C{0} or B{C{other}}
493 is a fractional C{scalar} and this
494 instance is negative or has a non-zero
495 residual or B{C{mod}} is given and C{0}.
497 @see: CPython function U{float_pow<https://GitHub.com/
498 python/cpython/blob/main/Objects/floatobject.c>}.
499 '''
500 return self._fpow(other, _pow_op_ + _fset_op_, *mod)
502 def __isub__(self, other):
503 '''Apply C{B{self} -= B{other}} to this instance.
505 @arg other: An L{Fsum} or C{scalar}.
507 @return: This instance, updated (L{Fsum}).
509 @raise TypeError: Invalid B{C{other}} type.
511 @see: Method L{Fsum.fadd}.
512 '''
513 return self._fsub(other, _isub_op_)
515 def __iter__(self):
516 '''Return an C{iter}ator over a C{partials} duplicate.
517 '''
518 return iter(self.partials)
520 def __itruediv__(self, other):
521 '''Apply C{B{self} /= B{other}} to this instance.
523 @arg other: An L{Fsum} or C{scalar} divisor.
525 @return: This instance, updated (L{Fsum}).
527 @raise OverflowError: Partial C{2sum} overflow.
529 @raise ResidualError: Non-zero residual in B{C{other}} and
530 env var C{PYGEODESY_FSUM_RESIDUAL} set.
532 @raise TypeError: Invalid B{C{other}} type.
534 @raise ValueError: Invalid or non-finite B{C{other}}.
536 @raise ZeroDivisionError: Zero B{C{other}}.
538 @see: Method L{Fsum.__ifloordiv__}.
539 '''
540 return self._ftruediv(other, _truediv_op_ + _fset_op_)
542 def __le__(self, other):
543 '''Compare this with an other instance or C{scalar}.
544 '''
545 return self._cmp_0(other, _le_op_) <= 0
547 def __len__(self):
548 '''Return the number of values accumulated (C{int}).
549 '''
550 return self._n
552 def __lt__(self, other):
553 '''Compare this with an other instance or C{scalar}.
554 '''
555 return self._cmp_0(other, _lt_op_) < 0
557 def __matmul__(self, other): # PYCHOK no cover
558 '''Not implemented.'''
559 return _NotImplemented(self, other)
561 def __mod__(self, other):
562 '''Return C{B{self} % B{other}} as an L{Fsum}.
564 @see: Method L{Fsum.__imod__}.
565 '''
566 f = self._copy_2(self.__mod__)
567 return f._fdivmod2(other, _mod_op_).mod
569 def __mul__(self, other):
570 '''Return C{B{self} * B{other}} as an L{Fsum}.
572 @see: Method L{Fsum.__imul__}.
573 '''
574 f = self._copy_2(self.__mul__)
575 return f._fmul(other, _mul_op_)
577 def __ne__(self, other):
578 '''Compare this with an other instance or C{scalar}.
579 '''
580 return self._cmp_0(other, _ne_op_) != 0
582 def __neg__(self):
583 '''Return I{a copy of} this instance, I{negated}.
584 '''
585 f = self._copy_2(self.__neg__)
586 return f._fset(self._neg)
588 def __pos__(self):
589 '''Return this instance I{as-is}, like C{float.__pos__()}.
590 '''
591 return self if _pos_self else self._copy_2(self.__pos__)
593 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
594 '''Return C{B{self}**B{other}} as an L{Fsum}.
596 @see: Method L{Fsum.__ipow__}.
597 '''
598 f = self._copy_2(self.__pow__)
599 return f._fpow(other, _pow_op_, *mod)
601 def __radd__(self, other):
602 '''Return C{B{other} + B{self}} as an L{Fsum}.
604 @see: Method L{Fsum.__iadd__}.
605 '''
606 f = self._copy_2r(other, self.__radd__)
607 return f._fadd(self, _add_op_)
609 def __rdivmod__(self, other):
610 '''Return C{divmod(B{other}, B{self})} as 2-tuple C{(quotient,
611 remainder)}.
613 @see: Method L{Fsum.__divmod__}.
614 '''
615 f = self._copy_2r(other, self.__rdivmod__)
616 return f._fdivmod2(self, _divmod_op_)
618# def __repr__(self):
619# '''Return the default C{repr(this)}.
620# '''
621# return self.toRepr(lenc=True)
623 def __rfloordiv__(self, other):
624 '''Return C{B{other} // B{self}} as an L{Fsum}.
626 @see: Method L{Fsum.__ifloordiv__}.
627 '''
628 f = self._copy_2r(other, self.__rfloordiv__)
629 return f._floordiv(self, _floordiv_op_)
631 def __rmatmul__(self, other): # PYCHOK no cover
632 '''Not implemented.'''
633 return _NotImplemented(self, other)
635 def __rmod__(self, other):
636 '''Return C{B{other} % B{self}} as an L{Fsum}.
638 @see: Method L{Fsum.__imod__}.
639 '''
640 f = self._copy_2r(other, self.__rmod__)
641 return f._fdivmod2(self, _mod_op_).mod
643 def __rmul__(self, other):
644 '''Return C{B{other} * B{self}} as an L{Fsum}.
646 @see: Method L{Fsum.__imul__}.
647 '''
648 f = self._copy_2r(other, self.__rmul__)
649 return f._fmul(self, _mul_op_)
651 def __round__(self, *ndigits): # PYCHOK no cover
652 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
654 @arg ndigits: Optional number of digits (C{int}).
655 '''
656 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
657 return _Fsum_ps(round(float(self), *ndigits), # can be C{int}
658 name=self.__round__.__name__)
660 def __rpow__(self, other, *mod):
661 '''Return C{B{other}**B{self}} as an L{Fsum}.
663 @see: Method L{Fsum.__ipow__}.
664 '''
665 f = self._copy_2r(other, self.__rpow__)
666 return f._fpow(self, _pow_op_, *mod)
668 def __rsub__(self, other):
669 '''Return C{B{other} - B{self}} as L{Fsum}.
671 @see: Method L{Fsum.__isub__}.
672 '''
673 f = self._copy_2r(other, self.__rsub__)
674 return f._fsub(self, _sub_op_)
676 def __rtruediv__(self, other):
677 '''Return C{B{other} / B{self}} as an L{Fsum}.
679 @see: Method L{Fsum.__itruediv__}.
680 '''
681 f = self._copy_2r(other, self.__rtruediv__)
682 return f._ftruediv(self, _truediv_op_)
684 def __str__(self):
685 '''Return the default C{str(self)}.
686 '''
687 return self.toStr(lenc=True)
689 def __sub__(self, other):
690 '''Return C{B{self} - B{other}} as an L{Fsum}.
692 @arg other: An L{Fsum} or C{scalar}.
694 @return: The difference (L{Fsum}).
696 @see: Method L{Fsum.__isub__}.
697 '''
698 f = self._copy_2(self.__sub__)
699 return f._fsub(other, _sub_op_)
701 def __truediv__(self, other):
702 '''Return C{B{self} / B{other}} as an L{Fsum}.
704 @arg other: An L{Fsum} or C{scalar} divisor.
706 @return: The quotient (L{Fsum}).
708 @see: Method L{Fsum.__itruediv__}.
709 '''
710 f = self._copy_2(self.__truediv__)
711 return f._ftruediv(other, _truediv_op_)
713 __trunc__ = __int__
715 if _sys_version_info2 < (3, 0): # PYCHOK no cover
716 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
717 __div__ = __truediv__
718 __idiv__ = __itruediv__
719 __long__ = __int__
720 __nonzero__ = __bool__
721 __rdiv__ = __rtruediv__
723 def as_integer_ratio(self):
724 '''Return this instance as the ratio of 2 integers.
726 @return: 2-Tuple C{(numerator, denominator)} both
727 C{int} and with positive C{denominator}.
729 @see: Standard C{float.as_integer_ratio} in Python 3+.
730 '''
731 n, r = self._fint2
732 if r:
733 i, d = r.as_integer_ratio()
734 n *= d
735 n += i
736 else: # PYCHOK no cover
737 d = 1
738 return n, d
740 @property_RO
741 def ceil(self):
742 '''Get this instance' C{ceil} value (C{int} in Python 3+,
743 but C{float} in Python 2-).
745 @note: The C{ceil} takes the C{residual} into account.
747 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
748 L{Fsum.imag} and L{Fsum.real}.
749 '''
750 s, r = self._fprs2
751 c = _ceil(s) + int(r) - 1
752 while r > (c - s): # (s + r) > c
753 c += 1
754 return c
756 def _cmp_0(self, other, op):
757 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
758 '''
759 if isscalar(other):
760 if other:
761 s = _fsum(self._ps_1(other))
762 else:
763 s, r = self._fprs2
764 s = _signOf(s, -r)
765 elif isinstance(other, Fsum):
766 s = _fsum(self._ps_1(*other._ps))
767 else:
768 raise self._TypeError(op, other) # txt=_invalid_
769 return s
771 def copy(self, deep=False, name=NN):
772 '''Copy this instance, C{shallow} or B{C{deep}}.
774 @return: The copy (L{Fsum}).
775 '''
776 f = _Named.copy(self, deep=deep, name=name)
777 f._n = self._n if deep else 1
778 f._ps = list(self._ps) # separate list
779 return f
781 def _copy_2(self, which, name=NN):
782 '''(INTERNAL) Copy for I{dyadic} operators.
783 '''
784 n = name or which.__name__
785 # NOT .classof due to .Fdot(a, *b) args, etc.
786 f = _Named.copy(self, deep=False, name=n)
787 # assert f._n == self._n
788 f._ps = list(self._ps) # separate list
789 return f
791 def _copy_2r(self, other, which):
792 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
793 '''
794 return other._copy_2(which) if isinstance(other, Fsum) else \
795 Fsum(other, name=which.__name__)
797# def _copy_RESIDUAL(self, other):
798# '''(INTERNAL) Copy C{other._RESIDUAL}.
799# '''
800# R = other._RESIDUAL
801# if R is not Fsum._RESIDUAL:
802# self._RESIDUAL = R
804 def divmod(self, other):
805 '''Return C{divmod(B{self}, B{other})} as 2-tuple C{(quotient,
806 remainder)}.
808 @arg other: An L{Fsum} or C{scalar} divisor.
810 @return: A L{DivMod2Tuple}C{(div, mod)}, with quotient C{div}
811 an C{int} in Python 3+ or C{float} in Python 2- and
812 remainder C{mod} an L{Fsum} instance.
814 @see: Method L{Fsum.__itruediv__}.
815 '''
816 f = self._copy_2(self.divmod)
817 return f._fdivmod2(other, _divmod_op_)
819 def _Error(self, op, other, Error, **txt):
820 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
821 '''
822 return Error(_SPACE_(self.toRepr(), op, repr(other)), **txt)
824 def _ErrorX(self, X, xs, **kwds): # in .fmath
825 '''(INTERNAL) Format a caught exception.
826 '''
827 E, t = _xError2(X)
828 n = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
829 return E(n, txt=t, cause=X)
831 def _facc(self, xs, up=True): # from .elliptic._Defer.Fsum
832 '''(INTERNAL) Accumulate more known C{scalar}s.
833 '''
834 n, ps, _2s = 0, self._ps, _2sum
835 for x in xs: # _iter()
836 # assert isscalar(x) and isfinite(x)
837 i = 0
838 for p in ps:
839 x, p = _2s(x, p)
840 if p:
841 ps[i] = p
842 i += 1
843 ps[i:] = x,
844 n += 1
845 # assert self._ps is ps
846 if n:
847 self._n += n
848 # Fsum._px = max(Fsum._px, len(ps))
849 if up:
850 self._update()
851 return self
853 def _facc_(self, *xs, **up):
854 '''(INTERNAL) Accumulate all positional C{scalar}s.
855 '''
856 return self._facc(xs, **up) if xs else self
858 def _facc_power(self, power, xs, which): # in .fmath
859 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
860 '''
861 if isinstance(power, Fsum):
862 if power.is_exact:
863 return self._facc_power(power._fprs, xs, which)
864 _Pow = Fsum._pow_any
865 elif isint(power, both=True) and power >= 0:
866 _Pow = Fsum._pow_int
867 power = int(power)
868 else:
869 _Pow = Fsum._pow_scalar
870 power = _2float(power=power)
872 if power:
873 from math import pow as _pow
874 op = which.__name__
876 def _X(X):
877 f = _Pow(X, power, power, op)
878 try: # isinstance(f, Fsum)
879 return f._ps
880 except AttributeError: # scalar
881 return f,
883 def _x(x):
884 return _pow(float(x), power)
886 self._facc(_2yield(xs, 1, _X, _x)) # PYCHOK yield
887 else:
888 self._facc_(float(len(xs))) # x**0 == 1
889 return self
891# def _facc_up(self, up=True):
892# '''(INTERNAL) Update the C{partials}, by removing
893# and re-accumulating the final C{partial}.
894# '''
895# while len(self._ps) > 1:
896# p = self._ps.pop()
897# if p:
898# n = self._n
899# self._facc_(p, up=False)
900# self._n = n
901# break
902# return self._update() if up else self # ._fpsqz()
904 def fadd(self, xs=()):
905 '''Add an iterable of C{scalar} or L{Fsum} instances
906 to this instance.
908 @arg xs: Iterable, list, tuple, etc. (C{scalar} or
909 L{Fsum} instances).
911 @return: This instance (L{Fsum}).
913 @raise OverflowError: Partial C{2sum} overflow.
915 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}
916 nor L{Fsum}.
918 @raise ValueError: Invalid or non-finite B{C{xs}} value.
919 '''
920 if isinstance(xs, Fsum):
921 self._facc(xs._ps)
922 elif isscalar(xs): # for backward compatibility
923 self._facc_(_2float(x=xs)) # PYCHOK no cover
924 elif xs:
925 self._facc(_2floats(xs)) # PYCHOK yield
926 return self
928 def fadd_(self, *xs):
929 '''Add all positional C{scalar} or L{Fsum} instances
930 to this instance.
932 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
933 all positional.
935 @return: This instance (L{Fsum}).
937 @raise OverflowError: Partial C{2sum} overflow.
939 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}
940 nor L{Fsum}.
942 @raise ValueError: Invalid or non-finite B{C{xs}} value.
943 '''
944 return self._facc(_2floats(xs, origin=1)) # PYCHOK yield
946 def _fadd(self, other, op, **up): # in .fmath.Fhorner
947 '''(INTERNAL) Apply C{B{self} += B{other}}.
948 '''
949 if isinstance(other, Fsum):
950 if other is self:
951 self._facc_(*other._ps, **up) # == ._facc(tuple(other._ps))
952 elif other._ps:
953 self._facc(other._ps, **up)
954 elif not isscalar(other):
955 raise self._TypeError(op, other) # txt=_invalid_
956 elif other:
957 self._facc_(other, **up)
958 return self
960 fcopy = copy # for backward compatibility
961 fdiv = __itruediv__ # for backward compatibility
962 fdivmod = __divmod__ # for backward compatibility
964 def _fdivmod2(self, other, op):
965 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
966 '''
967 # result mostly follows CPython function U{float_divmod
968 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
969 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
970 q = self._copy_2(self._fdivmod2)._ftruediv(other, op).floor
971 if q: # == float // other == floor(float / other)
972 self -= other * q
974 s = signOf(other) # make signOf(self) == signOf(other)
975 if s and self.signOf() == -s: # PYCHOK no cover
976 self += other
977 q -= 1
978# t = self.signOf()
979# if t and t != s:
980# raise self._Error(op, other, _AssertionError, txt=signOf.__name__)
981 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
983 def _finite(self, other, op=None):
984 '''(INTERNAL) Return B{C{other}} if C{finite}.
985 '''
986 if _isfinite(other):
987 return other
988 raise ValueError(_not_finite_) if not op else \
989 self._ValueError(op, other, txt=_not_finite_)
991 def fint(self, raiser=True, **name):
992 '''Return this instance' current running sum as C{integer}.
994 @kwarg raiser: If C{True} throw a L{ResidualError} if the
995 I{integer} residual is non-zero.
996 @kwarg name: Optional name (C{str}), overriding C{"fint"}.
998 @return: The C{integer} (L{Fsum}).
1000 @raise ResidualError: Non-zero I{integer} residual.
1002 @see: Methods L{Fsum.int_float} and L{Fsum.is_integer}.
1003 '''
1004 i, r = self._fint2
1005 if r and raiser:
1006 t = _stresidual(_integer_, r)
1007 raise ResidualError(_integer_, i, txt=t)
1008 f = self._copy_2(self.fint, **name)
1009 return f._fset(i)
1011 def fint2(self, **name):
1012 '''Return this instance' current running sum as C{int} and
1013 the I{integer} residual.
1015 @kwarg name: Optional name (C{str}).
1017 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1018 an C{int} and I{integer} C{residual} a C{float} or
1019 C{INT0} if the C{fsum} is considered to be I{exact}.
1020 '''
1021 return Fsum2Tuple(*self._fint2, **name)
1023 @Property_RO
1024 def _fint2(self): # see ._fset
1025 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1026 '''
1027 s, r = self._fprs2
1028 i = int(s)
1029 r = _fsum(self._ps_1(i)) if r else float(s - i)
1030 return i, (r or INT0)
1032 @deprecated_property_RO
1033 def float_int(self): # PYCHOK no cover
1034 '''DEPRECATED, use method C{Fsum.int_float}.'''
1035 return self.int_float() # raiser=False
1037 @property_RO
1038 def floor(self):
1039 '''Get this instance' C{floor} (C{int} in Python 3+, but
1040 C{float} in Python 2-).
1042 @note: The C{floor} takes the C{residual} into account.
1044 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1045 L{Fsum.imag} and L{Fsum.real}.
1046 '''
1047 s, r = self._fprs2
1048 f = _floor(s) + _floor(r) + 1
1049 while (f - s) > r: # f > (s + r)
1050 f -= 1
1051 return f
1053# floordiv = __floordiv__ # for naming consistency
1055 def _floordiv(self, other, op): # rather _ffloordiv?
1056 '''Apply C{B{self} //= B{other}}.
1057 '''
1058 q = self._ftruediv(other, op) # == self
1059 return self._fset(q.floor) # floor(q)
1061 fmul = __imul__ # for backward compatibility
1063 def _fmul(self, other, op):
1064 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1065 '''
1066 if isinstance(other, Fsum):
1067 if len(self._ps) != 1:
1068 f = self._mul_Fsum(other, op)
1069 elif len(other._ps) != 1: # and len(self._ps) == 1
1070 f = other._mul_scalar(self._ps[0], op)
1071 else: # len(other._ps) == len(self._ps) == 1
1072 f = self._finite(self._ps[0] * other._ps[0])
1073 elif isscalar(other):
1074 f = self._mul_scalar(other, op)
1075 else:
1076 raise self._TypeError(op, other) # txt=_invalid_
1077 return self._fset(f) # n=len(self) + 1
1079 def fover(self, over):
1080 '''Apply C{B{self} /= B{over}} and summate.
1082 @arg over: An L{Fsum} or C{scalar} denominator.
1084 @return: Precision running sum (C{float}).
1086 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1087 '''
1088 return float(self.fdiv(over)._fprs)
1090 fpow = __ipow__ # for backward compatibility
1092 def _fpow(self, other, op, *mod):
1093 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1094 '''
1095 if mod:
1096 if mod[0] is not None: # == 3-arg C{pow}
1097 f = self._pow_3(other, mod[0], op)
1098 elif self.is_integer():
1099 # return an exact C{int} for C{int}**C{int}
1100 x = _2scalar(other) # C{int}, C{float} or other
1101 i = self._fint2[0] # assert _fint2[1] == 0
1102 f = self._pow_2(i, x, other, op) if isscalar(x) else \
1103 _Fsum_ps(i)._pow_any(x, other, op)
1104 else: # mod[0] is None, power(self, other)
1105 f = self._pow_any(other, other, op)
1106 else: # pow(self, other) == pow(self, other, None)
1107 f = self._pow_any(other, other, op)
1108 return self._fset(f, asis=isint(f)) # n=max(len(self), 1)
1110 @Property_RO
1111 def _fprs(self):
1112 '''(INTERNAL) Get and cache this instance' precision
1113 running sum (C{float} or C{int}), ignoring C{residual}.
1115 @note: The precision running C{fsum} after a C{//=} or
1116 C{//} C{floor} division is C{int} in Python 3+.
1117 '''
1118 return self._fprs2.fsum
1120 @Property_RO
1121 def _fprs2(self):
1122 '''(INTERNAL) Get and cache this instance' precision
1123 running sum and residual (L{Fsum2Tuple}).
1124 '''
1125 ps = self._ps
1126 n = len(ps)
1127 if n > 2: # len(ps) > 2
1128 s = _psum(ps)
1129 r = _fsum(self._ps_1(s)) or INT0
1130 elif n > 1: # len(ps) == 2
1131 ps[:] = _2ps(*_2sum(*ps))
1132 r, s = (INT0, ps[0]) if len(ps) != 2 else ps
1133 elif ps: # len(ps) == 1
1134 s, r = ps[0], INT0
1135 else: # len(ps) == 0
1136 s, r = _0_0, INT0
1137 ps[:] = s,
1138 # assert self._ps is ps
1139 return Fsum2Tuple(s, r)
1141# def _fpsqz(self):
1142# '''(INTERNAL) Compress, squeeze the C{partials}.
1143# '''
1144# if len(self._ps) > 2:
1145# _ = self._fprs
1146# return self
1148 def _fset(self, other, asis=True, n=0):
1149 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1150 '''
1151 if other is self:
1152 pass # from ._fmul, ._ftruediv and ._pow_scalar
1153 elif isinstance(other, Fsum):
1154 self._n = n or other._n
1155 self._ps[:] = other._ps
1156# self._copy_RESIDUAL(other)
1157 # use or zap the C{Property_RO} values
1158 Fsum._fint2._update_from(self, other)
1159 Fsum._fprs ._update_from(self, other)
1160 Fsum._fprs2._update_from(self, other)
1161 elif isscalar(other):
1162 s = other if asis else float(other)
1163 i = int(s) # see ._fint2
1164 t = i, ((s - i) or INT0)
1165 self._n = n or 1
1166 self._ps[:] = s,
1167 # Property_ROs _fint2, _fprs and _fprs2 can't be a Property:
1168 # Property's _fset zaps the value just set by the @setter
1169 self.__dict__.update(_fint2=t, _fprs=s, _fprs2=Fsum2Tuple(s, INT0))
1170 else: # PYCHOK no cover
1171 raise self._TypeError(_fset_op_, other) # txt=_invalid_
1172 return self
1174 def _fset_ps(self, other, n=0): # in .fmath
1175 '''(INTERNAL) Set a known C{Fsum} or C{scalar}.
1176 '''
1177 if isinstance(other, Fsum):
1178 self._n = n or other._n
1179 self._ps[:] = other._ps
1180 else: # assert isscalar(other)
1181 self._n = n or 1
1182 self._ps[:] = other,
1184 def fsub(self, xs=()):
1185 '''Subtract an iterable of C{scalar} or L{Fsum} instances from
1186 this instance.
1188 @arg xs: Iterable, list, tuple. etc. (C{scalar} or L{Fsum}
1189 instances).
1191 @return: This instance, updated (L{Fsum}).
1193 @see: Method L{Fsum.fadd}.
1194 '''
1195 return self._facc(_2floats(xs, neg=True)) if xs else self # PYCHOK yield
1197 def fsub_(self, *xs):
1198 '''Subtract all positional C{scalar} or L{Fsum} instances from
1199 this instance.
1201 @arg xs: Values to subtract (C{scalar} or L{Fsum} instances),
1202 all positional.
1204 @return: This instance, updated (L{Fsum}).
1206 @see: Method L{Fsum.fadd}.
1207 '''
1208 return self._facc(_2floats(xs, origin=1, neg=True)) if xs else self # PYCHOK yield
1210 def _fsub(self, other, op):
1211 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1212 '''
1213 if isinstance(other, Fsum):
1214 if other is self: # or other._fprs2 == self._fprs2:
1215 self._fset(_0_0) # n=len(self) * 2, self -= self
1216 elif other._ps:
1217 self._facc(other._ps_neg)
1218 elif not isscalar(other):
1219 raise self._TypeError(op, other) # txt=_invalid_
1220 elif self._finite(other, op):
1221 self._facc_(-other)
1222 return self
1224 def fsum(self, xs=()):
1225 '''Add more C{scalar} or L{Fsum} instances and summate.
1227 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or
1228 L{Fsum} instances).
1230 @return: Precision running sum (C{float} or C{int}).
1232 @see: Method L{Fsum.fadd}.
1234 @note: Accumulation can continue after summation.
1235 '''
1236 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield
1237 return f._fprs
1239 def fsum_(self, *xs):
1240 '''Add all positional C{scalar} or L{Fsum} instances and summate.
1242 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
1243 all positional.
1245 @return: Precision running sum (C{float} or C{int}).
1247 @see: Methods L{Fsum.fsum} and L{Fsum.fsumf_}.
1248 '''
1249 f = self._facc(_2floats(xs, origin=1)) if xs else self # PYCHOK yield
1250 return f._fprs
1252 def fsum2(self, xs=(), **name):
1253 '''Add more C{scalar} or L{Fsum} instances and return the
1254 current precision running sum and the C{residual}.
1256 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or L{Fsum}
1257 instances).
1258 @kwarg name: Optional name (C{str}).
1260 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1261 current precision running sum and C{residual}, the
1262 (precision) sum of the remaining C{partials}. The
1263 C{residual is INT0} if the C{fsum} is considered
1264 to be I{exact}.
1266 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1267 '''
1268 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield
1269 t = f._fprs2
1270 if name:
1271 n = _xkwds_get(name, name=NN)
1272 if n:
1273 t = t.dup(name=n)
1274 return t
1276 def fsum2_(self, *xs):
1277 '''Add any positional C{scalar} or L{Fsum} instances and return
1278 the precision running sum and the C{differential}.
1280 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
1281 all positional.
1283 @return: 2-Tuple C{(fsum, delta)} with the current precision
1284 running C{fsum} and C{delta}, the difference with
1285 the previous running C{fsum} (C{float}s).
1287 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1288 '''
1289 p, r = self._fprs2
1290 if xs:
1291 s, t = self._facc(_2floats(xs, origin=1))._fprs2 # PYCHOK yield
1292 return s, _fsum((s, -p, r, -t)) # ((s - p) + (r - t))
1293 else: # PYCHOK no cover
1294 return p, _0_0
1296 def fsumf_(self, *xs):
1297 '''Like method L{Fsum.fsum_} but only for known C{float B{xs}}.
1298 '''
1299 f = self._facc(xs) if xs else self # PYCHOK yield
1300 return f._fprs
1302# ftruediv = __itruediv__ # for naming consistency
1304 def _ftruediv(self, other, op):
1305 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1306 '''
1307 n = _1_0
1308 if isinstance(other, Fsum):
1309 if other is self or other._fprs2 == self._fprs2:
1310 return self._fset(_1_0) # n=len(self)
1311 d, r = other._fprs2
1312 if r:
1313 if not d: # PYCHOK no cover
1314 d = r
1315 elif self._raiser(r, d):
1316 raise self._ResidualError(op, other, r)
1317 else:
1318 d, n = other.as_integer_ratio()
1319 elif isscalar(other):
1320 d = other
1321 else: # PYCHOK no cover
1322 raise self._TypeError(op, other) # txt=_invalid_
1323 try:
1324 s = 0 if isinf(d) else (
1325 d if isnan(d) else self._finite(n / d))
1326 except Exception as x:
1327 E, t = _xError2(x)
1328 raise self._Error(op, other, E, txt=t)
1329 f = self._mul_scalar(s, _mul_op_) # handles 0, NAN, etc.
1330 return self._fset(f, asis=False)
1332 @property_RO
1333 def imag(self):
1334 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1336 @see: Properties L{Fsum.ceil}, L{Fsum.floor} and L{Fsum.real}.
1337 '''
1338 return _0_0
1340 def int_float(self, raiser=False):
1341 '''Return this instance' current running sum as C{int} or C{float}.
1343 @kwarg raiser: If C{True} throw a L{ResidualError} if the
1344 residual is non-zero.
1346 @return: This C{integer} sum if this instance C{is_integer},
1347 otherwise return the C{float} sum if the residual
1348 is zero or if C{B{raiser}=False}.
1350 @raise ResidualError: Non-zero residual and C{B{raiser}=True}.
1352 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.
1353 '''
1354 s, r = self._fint2
1355 if r:
1356 s, r = self._fprs2
1357 if r and raiser: # PYCHOK no cover
1358 t = _stresidual(_non_zero_, r)
1359 raise ResidualError(int_float=s, txt=t)
1360 s = float(s) # redundant
1361 return s
1363 def is_exact(self):
1364 '''Is this instance' current running C{fsum} considered to
1365 be exact? (C{bool}).
1366 '''
1367 return self.residual is INT0
1369 def is_integer(self):
1370 '''Is this instance' current running sum C{integer}? (C{bool}).
1372 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.
1373 '''
1374 _, r = self._fint2
1375 return False if r else True
1377 def is_math_fsum(self):
1378 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and
1379 L{fsum1_} plus partials summation are based on Python's
1380 C{math.fsum} or not.
1382 @return: C{2} if all functions and partials summation
1383 are based on C{math.fsum}, C{True} if only
1384 the functions are based on C{math.fsum} (and
1385 partials summation is not) or C{False} if
1386 none are.
1387 '''
1388 f = Fsum._math_fsum
1389 return 2 if _psum is f else bool(f)
1391 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1392 '''(INTERNAL) Return C{B{self} * Fsum B{other}} as L{Fsum} or C{0}.
1393 '''
1394 # assert isinstance(other, Fsum)
1395 if self._ps and other._ps:
1396 f = _Fsum_xs(self._ps_mul(op, *other._ps))
1397 else:
1398 f = _0_0
1399 return f
1401 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1402 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0} or C{self}.
1403 '''
1404 # assert isscalar(factor)
1405 if self._ps and self._finite(factor, op):
1406 f = self if factor == _1_0 else (
1407 self._neg if factor == _N_1_0 else
1408 _Fsum_xs(self._ps_mul(op, factor))) # PYCHOK indent
1409 else:
1410 f = _0_0
1411 return f
1413 @property_RO
1414 def _neg(self):
1415 '''(INTERNAL) Return C{-self}.
1416 '''
1417 return _Fsum_ps(*self._ps_neg) if self._ps else NEG0
1419 @property_RO
1420 def partials(self):
1421 '''Get this instance' current partial sums (C{tuple} of C{float}s and/or C{int}s).
1422 '''
1423 return tuple(self._ps)
1425 def pow(self, x, *mod):
1426 '''Return C{B{self}**B{x}} as L{Fsum}.
1428 @arg x: The exponent (L{Fsum} or C{scalar}).
1429 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
1430 C{pow(B{self}, B{other}, B{mod})} version.
1432 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
1433 result (L{Fsum}).
1435 @note: If B{C{mod}} is given as C{None}, the result will be an
1436 C{integer} L{Fsum} provided this instance C{is_integer}
1437 or set to C{integer} with L{Fsum.fint}.
1439 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint} and L{Fsum.is_integer}.
1440 '''
1441 f = self._copy_2(self.pow)
1442 return f._fpow(x, _pow_op_, *mod) # f = pow(f, x, *mod)
1444 def _pow_0_1(self, x, other):
1445 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
1446 '''
1447 return self if x else (1 if self.is_integer() and isint(other) else _1_0)
1449 def _pow_2(self, b, x, other, op):
1450 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} embellishing errors.
1451 '''
1452 # assert isscalar(b) and isscalar(x)
1453 try: # type(s) == type(x) if x in (_1_0, 1)
1454 s = pow(b, x) # -1**2.3 == -(1**2.3)
1455 if not iscomplex(s):
1456 return self._finite(s) # 0**INF == 0.0, 1**INF==1.0
1457 # neg**frac == complex in Python 3+, but ValueError in 2-
1458 E, t = _ValueError, _strcomplex(s, b, x) # PYCHOK no cover
1459 except Exception as x:
1460 E, t = _xError2(x)
1461 raise self._Error(op, other, E, txt=t)
1463 def _pow_3(self, other, mod, op):
1464 '''(INTERNAL) 3-arg C{pow(B{self}, B{other}, int B{mod} or C{None})}.
1465 '''
1466 b, r = self._fprs2 if mod is None else self._fint2
1467 if r and self._raiser(r, b):
1468 t = _non_zero_ if mod is None else _integer_
1469 E, t = ResidualError, _stresidual(t, r, mod=mod)
1470 else:
1471 try: # b, other, mod all C{int}, unless C{mod} is C{None}
1472 x = _2scalar(other, _raiser=self._raiser)
1473 s = pow(b, x, mod)
1474 if not iscomplex(s):
1475 return self._finite(s)
1476 # neg**frac == complex in Python 3+, but ValueError in 2-
1477 E, t = _ValueError, _strcomplex(s, b, x, mod) # PYCHOK no cover
1478 except Exception as x:
1479 E, t = _xError2(x)
1480 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod), t)
1481 raise self._Error(op, other, E, txt=t)
1483 def _pow_any(self, other, unused, op):
1484 '''Return C{B{self} ** B{other}}.
1485 '''
1486 if isinstance(other, Fsum):
1487 x, r = other._fprs2
1488 f = self._pow_scalar(x, other, op)
1489 if r:
1490 if self._raiser(r, x):
1491 raise self._ResidualError(op, other, r)
1492 s = self._pow_scalar(r, other, op)
1493# s = _2scalar(s) # _raiser = None
1494 f *= s
1495 elif isscalar(other):
1496 x = self._finite(other, op)
1497 f = self._pow_scalar(x, other, op)
1498 else:
1499 raise self._TypeError(op, other) # txt=_invalid_
1500 return f
1502 def _pow_int(self, x, other, op):
1503 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
1504 '''
1505 # assert isint(x) and x >= 0
1506 ps = self._ps
1507 if len(ps) > 1:
1508 f = self
1509 if x > 4:
1510 m = 1 # single-bit mask
1511 if (x & m):
1512 x -= m # x ^= m
1513 else:
1514 f = _Fsum_ps(_1_0)
1515 p = self
1516 while x:
1517 p = p._mul_Fsum(p, op) # p **= 2
1518 m += m # m <<= 1
1519 if (x & m):
1520 x -= m # x ^= m
1521 f = f._mul_Fsum(p, op) # f *= p
1522 elif x > 1: # self**2, 3 or 4
1523 f = f._mul_Fsum(f, op)
1524 if x > 2: # self**3 or 4
1525 p = self if x < 4 else f
1526 f = f._mul_Fsum(p, op)
1527 else: # self**1 or self**0 == 1 or _1_0
1528 f = f._pow_0_1(x, other)
1529 elif ps: # self._ps[0]**x
1530 f = self._pow_2(ps[0], x, other, op)
1531 else: # PYCHOK no cover
1532 # 0**pos_int == 0, but 0**0 == 1
1533 f = 0 if x else 1 # like ._fprs
1534 return f
1536 def _pow_scalar(self, x, other, op):
1537 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
1538 '''
1539 s, r = self._fprs2
1540 if isint(x, both=True):
1541 x = int(x) # Fsum**int
1542 y = abs(x)
1543 if y > 1:
1544 if r:
1545 f = self._pow_int(y, other, op)
1546 if x > 0: # > 1
1547 return f
1548 # assert x < 0 # < -1
1549 s, r = f._fprs2 if isinstance(f, Fsum) else (f, 0)
1550 if r:
1551 return _Fsum_ps(_1_0)._ftruediv(f, op)
1552 # use **= -1 for the CPython float_pow
1553 # error if s is zero, and not s = 1 / s
1554 x = -1
1555 elif x < 0: # self**-1 == 1 / self
1556 if r:
1557 return _Fsum_ps(_1_0)._ftruediv(self, op)
1558 else: # self**1 or self**0
1559 return self._pow_0_1(x, other) # self, 1 or 1.0
1560 elif not isscalar(x): # assert ...
1561 raise self._TypeError(op, other, txt=_not_scalar_)
1562 elif r and self._raiser(r, s): # non-zero residual**fractional
1563 # raise self._ResidualError(op, other, r, fractional_power=x)
1564 t = _stresidual(_non_zero_, r, fractional_power=x)
1565 raise self._Error(op, other, ResidualError, txt=t)
1566 # assert isscalar(s) and isscalar(x)
1567 return self._pow_2(s, x, other, op)
1569 def _ps_1(self, *less):
1570 '''(INTERNAL) Yield partials, 1-primed and subtract any C{less}.
1571 '''
1572 yield _1_0
1573 for p in self._ps:
1574 if p:
1575 yield p
1576 for p in less:
1577 if p:
1578 yield -p
1579 yield _N_1_0
1581 def _ps_mul(self, op, *factors): # see .fmath.Fhorner
1582 '''(INTERNAL) Yield all C{partials} times each B{C{factor}},
1583 in total, up to C{len(partials) * len(factors)} items.
1584 '''
1585 ps = self._ps # tuple(self._ps)
1586 if len(ps) < len(factors):
1587 ps, factors = factors, ps
1588 _f = _isfinite
1589 for f in factors:
1590 for p in ps:
1591 p *= f
1592 yield p if _f(p) else self._finite(p, op)
1594 @property_RO
1595 def _ps_neg(self):
1596 '''(INTERNAL) Yield the partials, I{negated}.
1597 '''
1598 for p in self._ps:
1599 yield -p
1601 @property_RO
1602 def real(self):
1603 '''Get the C{real} part of this instance (C{float}).
1605 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
1606 and properties L{Fsum.ceil}, L{Fsum.floor},
1607 L{Fsum.imag} and L{Fsum.residual}.
1608 '''
1609 return float(self._fprs)
1611 @property_RO
1612 def residual(self):
1613 '''Get this instance' residual (C{float} or C{int}), the
1614 C{sum(partials)} less the precision running sum C{fsum}.
1616 @note: If the C{residual is INT0}, the precision running
1617 C{fsum} is considered to be I{exact}.
1619 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
1620 '''
1621 return self._fprs2.residual
1623 def _raiser(self, r, s):
1624 '''(INTERNAL) Does ratio C{r / s} exceed threshold?
1625 '''
1626 self._ratio = t = fabs((r / s) if s else r)
1627 return t > self._RESIDUAL
1629 def RESIDUAL(self, *threshold):
1630 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
1631 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
1633 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
1634 L{ResidualError}s in division and exponention, if
1635 C{None} restore the default set with env variable
1636 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
1637 current setting.
1639 @return: The previous C{RESIDUAL} setting (C{float}).
1641 @raise ValueError: Negative B{C{threshold}}.
1643 @note: A L{ResidualError} is thrown if the non-zero I{ratio}
1644 C{residual} / C{fsum} exceeds the B{C{threshold}}.
1645 '''
1646 r = self._RESIDUAL
1647 if threshold:
1648 t = threshold[0]
1649 t = Fsum._RESIDUAL if t is None else (
1650 float(t) if isscalar(t) else ( # for backward ...
1651 _0_0 if bool(t) else _1_0)) # ... compatibility
1652 if t < 0:
1653 u = _DOT_(self, unstr(self.RESIDUAL, *threshold))
1654 raise _ValueError(u, RESIDUAL=t, txt=_negative_)
1655 self._RESIDUAL = t
1656 return r
1658 def _ResidualError(self, op, other, residual):
1659 '''(INTERNAL) Non-zero B{C{residual}} etc.
1660 '''
1661 t = _stresidual(_non_zero_, residual, ratio=self._ratio,
1662 RESIDUAL=self._RESIDUAL)
1663 t = t.replace(_COMMASPACE_R_, _exceeds_R_)
1664 return self._Error(op, other, ResidualError, txt=t)
1666 def signOf(self, res=True):
1667 '''Determine the sign of this instance.
1669 @kwarg res: If C{True} consider, otherwise
1670 ignore the residual (C{bool}).
1672 @return: The sign (C{int}, -1, 0 or +1).
1673 '''
1674 s, r = self._fprs2 if res else (self._fprs, 0)
1675 return _signOf(s, -r)
1677 def toRepr(self, **prec_sep_fmt_lenc): # PYCHOK signature
1678 '''Return this C{Fsum} instance as representation.
1680 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for
1681 method L{Fsum2Tuple.toRepr} plus C{B{lenc}=True}
1682 (C{bool}) to in-/exclude the current C{[len]}
1683 of this L{Fsum} enclosed in I{[brackets]}.
1685 @return: This instance (C{repr}).
1686 '''
1687 return self._toT(self._fprs2.toRepr, **prec_sep_fmt_lenc)
1689 def toStr(self, **prec_sep_fmt_lenc): # PYCHOK signature
1690 '''Return this C{Fsum} instance as string.
1692 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for
1693 method L{Fsum2Tuple.toStr} plus C{B{lenc}=True}
1694 (C{bool}) to in-/exclude the current C{[len]}
1695 of this L{Fsum} enclosed in I{[brackets]}.
1697 @return: This instance (C{str}).
1698 '''
1699 return self._toT(self._fprs2.toStr, **prec_sep_fmt_lenc)
1701 def _toT(self, toT, fmt=Fmt.g, lenc=True, **kwds):
1702 '''(INTERNAL) Helper for C{toRepr} and C{toStr}.
1703 '''
1704 n = self.named3
1705 if lenc:
1706 n = Fmt.SQUARE(n, len(self))
1707 return _SPACE_(n, toT(fmt=fmt, **kwds))
1709 def _TypeError(self, op, other, **txt): # PYCHOK no cover
1710 '''(INTERNAL) Return a C{TypeError}.
1711 '''
1712 return self._Error(op, other, _TypeError, **txt)
1714 def _update(self, updated=True): # see ._fset
1715 '''(INTERNAL) Zap all cached C{Property_RO} values.
1716 '''
1717 if updated:
1718 _pop = self.__dict__.pop
1719 for p in _ROs:
1720 _ = _pop(p, None)
1721# Fsum._fint2._update(self)
1722# Fsum._fprs ._update(self)
1723# Fsum._fprs2._update(self)
1724 return self
1726 def _ValueError(self, op, other, **txt): # PYCHOK no cover
1727 '''(INTERNAL) Return a C{ValueError}.
1728 '''
1729 return self._Error(op, other, _ValueError, **txt)
1731 def _ZeroDivisionError(self, op, other, **txt): # PYCHOK no cover
1732 '''(INTERNAL) Return a C{ZeroDivisionError}.
1733 '''
1734 return self._Error(op, other, _ZeroDivisionError, **txt)
1736_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK assert, see Fsum._fset, -._update
1739def _Float_Int(arg, **name_Error):
1740 '''(INTERNAL) Unit of L{Fsum2Tuple} items.
1741 '''
1742 U = Int if isint(arg) else Float
1743 return U(arg, **name_Error)
1746class DivMod2Tuple(_NamedTuple):
1747 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
1748 C{mod} results of a C{divmod} operation.
1750 @note: Quotient C{div} an C{int} in Python 3+ or a C{float} in
1751 Python 2-. Remainder C{mod} an L{Fsum} instance.
1752 '''
1753 _Names_ = (_div_, _mod_)
1754 _Units_ = (_Float_Int, Fsum)
1757class Fsum2Tuple(_NamedTuple):
1758 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
1759 and the C{residual}, the sum of the remaining partials. Each
1760 item is either C{float} or C{int}.
1762 @note: If the C{residual is INT0}, the C{fsum} is considered
1763 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
1764 '''
1765 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
1766 _Units_ = (_Float_Int, _Float_Int)
1768 @Property_RO
1769 def Fsum(self):
1770 '''Get this L{Fsum2Tuple} as an L{Fsum}.
1771 '''
1772 s, r = map(float, self)
1773 return _Fsum_ps(*_2ps(s, r), name=self.name)
1775 def is_exact(self):
1776 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
1777 '''
1778 return self.Fsum.is_exact()
1780 def is_integer(self):
1781 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
1782 '''
1783 return self.Fsum.is_integer()
1786class ResidualError(_ValueError):
1787 '''Error raised for an operation involving a L{pygeodesy.sums.Fsum}
1788 instance with a non-zero C{residual}, I{integer} or otherwise.
1790 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
1791 '''
1792 pass
1795def _Fsum_ps(*ps, **name):
1796 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
1797 '''
1798 f = Fsum(**name) if name else Fsum()
1799 if ps:
1800 f._n = len(ps)
1801 f._ps[:] = ps
1802 return f
1805def _Fsum_xs(xs, up=False, **name):
1806 '''(INTERNAL) Return an C{Fsum} from known floats C{xs}.
1807 '''
1808 f = Fsum(**name) if name else Fsum()
1809 return f._facc(xs, up=up)
1812try:
1813 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
1815 # make sure _fsum works as expected (XXX check
1816 # float.__getformat__('float')[:4] == 'IEEE'?)
1817 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
1818 del _fsum # nope, remove _fsum ...
1819 raise ImportError # ... use _fsum below
1821 Fsum._math_fsum = _sum = _fsum # PYCHOK exported
1823 if _getenv('PYGEODESY_FSUM_PARTIALS', _fsum.__name__) == _fsum.__name__:
1824 _psum = _fsum # PYCHOK re-def
1826except ImportError:
1827 _sum = sum # Fsum(NAN) exception fall-back
1829 def _fsum(xs):
1830 '''(INTERNAL) Precision summation, Python 2.5-.
1831 '''
1832 return Fsum(name=_fsum.__name__).fsum(xs) if xs else _0_0
1835def fsum(xs, floats=False):
1836 '''Precision floating point summation based on or like Python's C{math.fsum}.
1838 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum}
1839 instances).
1840 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1841 are known to be C{float}.
1843 @return: Precision C{fsum} (C{float}).
1845 @raise OverflowError: Partial C{2sum} overflow.
1847 @raise TypeError: Non-scalar B{C{xs}} value.
1849 @raise ValueError: Invalid or non-finite B{C{xs}} value.
1851 @note: Exceptions and I{non-finite} handling may differ if not
1852 based on Python's C{math.fsum}.
1854 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.
1855 '''
1856 return _fsum(xs if floats else _2floats(xs)) if xs else _0_0 # PYCHOK yield
1859def fsum_(*xs, **floats):
1860 '''Precision floating point summation of all positional arguments.
1862 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all
1863 positional.
1864 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1865 are known to be C{float}.
1867 @return: Precision C{fsum} (C{float}).
1869 @see: Function C{fsum}.
1870 '''
1871 return _fsum(xs if _xkwds_get(floats, floats=False) else
1872 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield
1875def fsumf_(*xs):
1876 '''Precision floating point summation L{fsum_}C{(*xs, floats=True)}.
1877 '''
1878 return _fsum(xs) if xs else _0_0
1881def fsum1(xs, floats=False):
1882 '''Precision floating point summation of a few arguments, 1-primed.
1884 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum}
1885 instances).
1886 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1887 are known to be C{float}.
1889 @return: Precision C{fsum} (C{float}).
1891 @see: Function C{fsum}.
1892 '''
1893 return _fsum(_1primed(xs if floats else _2floats(xs))) if xs else _0_0 # PYCHOK yield
1896def fsum1_(*xs, **floats):
1897 '''Precision floating point summation of a few arguments, 1-primed.
1899 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all
1900 positional.
1901 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1902 are known to be C{float}.
1904 @return: Precision C{fsum} (C{float}).
1906 @see: Function C{fsum}
1907 '''
1908 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) else
1909 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield
1912def fsum1f_(*xs):
1913 '''Precision floating point summation L{fsum1_}C{(*xs, floats=True)}.
1914 '''
1915 return _fsum(_1primed(xs)) if xs else _0_0
1918# **) MIT License
1919#
1920# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1921#
1922# Permission is hereby granted, free of charge, to any person obtaining a
1923# copy of this software and associated documentation files (the "Software"),
1924# to deal in the Software without restriction, including without limitation
1925# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1926# and/or sell copies of the Software, and to permit persons to whom the
1927# Software is furnished to do so, subject to the following conditions:
1928#
1929# The above copyright notice and this permission notice shall be included
1930# in all copies or substantial portions of the Software.
1931#
1932# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1933# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1934# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1935# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1936# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1937# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1938# OTHER DEALINGS IN THE SOFTWARE.