Coverage for pygeodesy/fsums.py: 97%
894 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -0400
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -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_RESIDUAL} to a C{float} string greater than
18C{"0.0"} as the threshold to throw a L{ResidualError} for a division, power or
19root operation of an L{Fsum} instance with a C{residual} I{ratio} exceeding
20the threshold. See methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
21and L{Fsum.__itruediv__}.
22'''
23# make sure int/int division yields float quotient, see .basics
24from __future__ import division as _; del _ # PYCHOK semicolon
26from pygeodesy.basics import isbool, iscomplex, isint, isscalar, \
27 _signOf, itemsorted, signOf, _xiterable, \
28 _xiterablen, _enquote
29from pygeodesy.constants import INT0, _isfinite, NEG0, _pos_self, \
30 _0_0, _1_0, _N_1_0, Float, Int
31from pygeodesy.errors import _OverflowError, _TypeError, _UnexpectedError, \
32 _ValueError, _xError, _xError2, _xkwds_get1, \
33 _xkwds_pop2
34# from pygeodesy.internals import _enquote # from .basics
35from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _DOT_, \
36 _EQUAL_, _from_, _LANGLE_, _NOTEQUAL_, \
37 _not_finite_, _PERCENT_, _PLUS_, \
38 _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_
39from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
40from pygeodesy.named import _name__, _name2__, _Named, _NamedTuple, \
41 _NotImplemented
42from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \
43 Property, Property_RO, property_RO
44from pygeodesy.streprs import Fmt, fstr, unstr
45# from pygeodesy.units import Float, Int # from .constants
47from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp
49__all__ = _ALL_LAZY.fsums
50__version__ = '24.06.11'
52_add_op_ = _PLUS_ # in .auxilats.auxAngle
53_eq_op_ = _EQUAL_ * 2 # _DEQUAL_
54_div_ = 'div'
55_floordiv_op_ = _SLASH_ * 2 # _DSLASH_
56_fset_op_ = _EQUAL_
57_ge_op_ = _RANGLE_ + _EQUAL_
58_gt_op_ = _RANGLE_
59_iadd_op_ = _add_op_ + _EQUAL_ # in .auxilats.auxAngle, .fstats
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_
69_significant_ = 'significant'
70_sub_op_ = _DASH_ # in .auxilats.auxAngle
71_threshold_ = 'threshold'
72_truediv_op_ = _SLASH_
73_divmod_op_ = _floordiv_op_ + _mod_op_
74_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle
77def _2delta(*ab):
78 '''(INTERNAL) Helper for C{Fsum._fsum2}.
79 '''
80 try:
81 a, b = _2sum(*ab)
82 except _OverflowError:
83 a, b = ab
84 return float(a if fabs(a) > fabs(b) else b)
87def _2error(unused): # in .fstats
88 '''(INTERNAL) Throw a C{not-finite} exception.
89 '''
90 raise ValueError(_not_finite_)
93def _2finite(x):
94 '''(INTERNAL) return C{float(x)} if finite.
95 '''
96 x = float(x)
97 return x if _isfinite(x) else _2error(x)
100def _2float(index=None, **name_value): # in .fmath, .fstats
101 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.
102 '''
103 n, v = name_value.popitem() # _xkwds_item2(name_value)
104 try:
105 return _2finite(v)
106 except Exception as X:
107 raise _xError(X, Fmt.INDEX(n, index), v)
110def _X_ps(X): # for _2floats only
111 return X._ps
114def _2floats(xs, origin=0, _X=_X_ps, _x=float):
115 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
116 '''
117 try:
118 i, x = origin, _X
119 _fin = _isfinite
120 _FsT = _Fsum_Fsum2Tuple_types
121 _isa = isinstance
122 for x in _xiterable(xs):
123 if _isa(x, _FsT):
124 for p in _X(x._Fsum):
125 yield p
126 else:
127 f = _x(x)
128 yield f if _fin(f) else _2error(f)
129 i += 1
130 except Exception as X:
131 raise _xError(X, xs=xs) if x is _X else \
132 _xError(X, Fmt.INDEX(xs=i), x)
135def _Fsumf_(*xs): # floats=True, in .auxLat, ...
136 '''(INTERNAL) An C{Fsum} of I{known scalars}.
137 '''
138 return Fsum()._facc_scalar(xs, up=False)
141def _Fsum1f_(*xs): # floats=True, in .albers, ...
142 '''(INTERNAL) An C{Fsum} of I{known scalars}, 1-primed.
143 '''
144 return Fsum()._facc_scalar(_1primed(xs), up=False)
147def _2halfeven(s, r, p):
148 '''(INTERNAL) Round half-even.
149 '''
150 if (p > 0 and r > 0) or \
151 (p < 0 and r < 0): # signs match
152 r *= 2
153 t = s + r
154 if r == (t - s):
155 s = t
156 return s
159def _isFsum(x): # in .fmath
160 '''(INTERNAL) Is C{x} an C{Fsum} instance?
161 '''
162 return isinstance(x, Fsum)
165def _isFsumTuple(x): # in .fmath
166 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance?
167 '''
168 return isinstance(x, _Fsum_Fsum2Tuple_types)
171def _1_Over(x, op, **raiser_RESIDUAL): # vs _1_over
172 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
173 '''
174 return _Psum_(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
177def _1primed(xs): # in .fmath
178 '''(INTERNAL) 1-Primed summation of iterable C{xs}
179 items, all I{known} to be C{scalar}.
180 '''
181 yield _1_0
182 for x in xs:
183 yield x
184 yield _N_1_0
187def _psum(ps): # PYCHOK used!
188 '''(INTERNAL) Partials summation, updating C{ps}.
189 '''
190 # assert isinstance(ps, list)
191 i = len(ps) - 1
192 s = _0_0 if i < 0 else ps[i]
193 _2s = _2sum
194 while i > 0:
195 i -= 1
196 s, r = _2s(s, ps[i])
197 if r: # sum(ps) became inexact
198 if s:
199 ps[i:] = r, s
200 if i > 0:
201 s = _2halfeven(s, r, ps[i-1])
202 break # return s
203 s = r # PYCHOK no cover
204 ps[i:] = s,
205 return s
208def _Psum(ps, **name_RESIDUAL):
209 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
210 '''
211 f = Fsum(**name_RESIDUAL) if name_RESIDUAL else Fsum()
212 if ps:
213 f._ps[:] = ps
214 f._n = len(f._ps)
215 return f
218def _Psum_(*ps, **name_RESIDUAL):
219 '''(INTERNAL) Return an C{Fsum} from 1 or 2 known scalar(s) C{ps}.
220 '''
221 return _Psum(ps, **name_RESIDUAL)
224def _2scalar2(other):
225 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
226 C{float} or C{as-is} and C{r} the residual of C{as-is}.
227 '''
228 if _isFsumTuple(other):
229 s, r = other._fint2
230 if r:
231 s, r = other._fprs2
232 if r: # PYCHOK no cover
233 s = other # L{Fsum} as-is
234 else:
235 r = 0
236 s = other # C{type} as-is
237 if isint(s, both=True):
238 s = int(s)
239 return s, r
242def _s_r(s, r):
243 '''(INTERNAL) Return C{(s, r)}, I{ordered}.
244 '''
245 if r:
246 if fabs(s) < fabs(r):
247 s, r = r, (s or INT0)
248 else:
249 r = INT0
250 return s, r
253def _strcomplex(s, *args):
254 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
255 '''
256 c = _strcomplex.__name__[4:]
257 n = _DASH_(len(args), _arg_)
258 t = unstr(pow, *args)
259 return _SPACE_(c, s, _from_, n, t)
262def _stresidual(prefix, residual, R=0, **mod_ratio):
263 '''(INTERNAL) Residual error txt C{str}.
264 '''
265 p = _stresidual.__name__[3:]
266 t = Fmt.PARENSPACED(p, Fmt(residual))
267 for n, v in itemsorted(mod_ratio):
268 p = Fmt.PARENSPACED(n, Fmt(v))
269 t = _COMMASPACE_(t, p)
270 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_)
273def _2sum(a, b): # by .testFmath
274 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual).
275 '''
276 # Neumaier, A. U{Rundungsfehleranalyse einiger Verfahren zur Summation endlicher
277 # Summen<https://OnlineLibrary.Wiley.com/doi/epdf/10.1002/zamm.19740540106>},
278 # 1974, Zeitschrift für Angewandte Mathmatik und Mechanik, vol 51, nr 1, p 39-51
279 # <https://StackOverflow.com/questions/78633770/can-neumaier-summation-be-sped-up>
280 s = a + b
281 if _isfinite(s):
282 if fabs(a) < fabs(b):
283 r = (b - s) + a
284 else:
285 r = (a - s) + b
286 return s, r
287 u = unstr(_2sum, a, b)
288 t = Fmt.PARENSPACED(_not_finite_, s)
289 raise _OverflowError(u, txt=t)
292def _threshold(threshold=_0_0, **kwds):
293 '''(INTERNAL) Get the L{ResidualError}s threshold,
294 optionally from single kwds C{B{RESIDUAL}=scalar}.
295 '''
296 if kwds:
297 threshold, kwds = _xkwds_pop2(kwds, RESIDUAL=threshold)
298# threshold = kwds.pop('RESIDUAL', threshold)
299 if kwds:
300 raise _UnexpectedError(**kwds)
301 try:
302 return _2finite(threshold) # PYCHOK None
303 except Exception as x:
304 raise ResidualError(threshold=threshold, cause=x)
307class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase
308 '''Precision floating point summation and I{running} summation.
310 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
311 I{running}, precision floating point summations. Accumulation may continue after any
312 intermediate, I{running} summuation.
314 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances,
315 any C{type} having method C{__float__} to convert the C{scalar} to a single
316 C{float}, except C{complex}.
318 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from
319 Python's C{math.fsum}.
321 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/
322 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>},
323 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
324 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
325 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
326 <https://Bugs.Python.org/issue2819>}.
327 '''
328 _math_fsum = None
329 _n = 0
330# _ps = [] # partial sums
331# _ps_max = 0 # max(Fsum._ps_max, len(Fsum._ps))
332 _RESIDUAL = _threshold(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0))
334 def __init__(self, *xs, **name_RESIDUAL):
335 '''New L{Fsum} for I{running} precision floating point summation.
337 @arg xs: No, one or more initial items to add (each C{scalar} or
338 an L{Fsum} or L{Fsum2Tuple} instance), all positional.
339 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) for this
340 L{Fsum} and the C{B{RESIDUAL}=0.0} threshold for
341 L{ResidualError}s (C{scalar}).
343 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.
344 '''
345 if name_RESIDUAL:
346 n, kwds = _name2__(**name_RESIDUAL)
347 if kwds:
348 R = Fsum._RESIDUAL
349 t = _threshold(R, **kwds)
350 if t != R:
351 self._RESIDUAL = t
352 if n:
353 self.name = n
355 self._ps = [] # [_0_0], see L{Fsum._fprs}
356 if xs:
357 self._facc_1(xs, up=False)
359 def __abs__(self):
360 '''Return this instance' absolute value as an L{Fsum}.
361 '''
362 s = self.signOf() # == self._cmp_0(0)
363 return (-self) if s < 0 else self._copy_2(self.__abs__)
365 def __add__(self, other):
366 '''Return C{B{self} + B{other}} as an L{Fsum}.
368 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
370 @return: The sum (L{Fsum}).
372 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
373 '''
374 f = self._copy_2(self.__add__)
375 return f._fadd(other, _add_op_)
377 def __bool__(self): # PYCHOK Python 3+
378 '''Return C{True} if this instance is I{exactly} non-zero.
379 '''
380 s, r = self._fprs2
381 return bool(s or r) and s != -r # == self != 0
383 def __ceil__(self): # PYCHOK not special in Python 2-
384 '''Return this instance' C{math.ceil} as C{int} or C{float}.
386 @return: An C{int} in Python 3+, but C{float} in Python 2-.
388 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
389 '''
390 return self.ceil
392 def __cmp__(self, other): # PYCHOK no cover
393 '''Compare this with an other instance or C{scalar}, Python 2-.
395 @return: -1, 0 or +1 (C{int}).
397 @raise TypeError: Incompatible B{C{other}} C{type}.
398 '''
399 s = self._cmp_0(other, self.cmp.__name__)
400 return _signOf(s, 0)
402 def __divmod__(self, other, **raiser_RESIDUAL):
403 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
404 with quotient C{div} an C{int} in Python 3+ or C{float}
405 in Python 2- and remainder C{mod} an L{Fsum} instance.
407 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
408 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
409 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
410 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
412 @raise ResidualError: Non-zero, significant residual or invalid
413 B{C{RESIDUAL}}.
415 @see: Method L{Fsum.fdiv}.
416 '''
417 f = self._copy_2(self.__divmod__)
418 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
420 def __eq__(self, other):
421 '''Compare this with an other instance or C{scalar}.
422 '''
423 return self._cmp_0(other, _eq_op_) == 0
425 def __float__(self):
426 '''Return this instance' current, precision running sum as C{float}.
428 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
429 '''
430 return float(self._fprs)
432 def __floor__(self): # PYCHOK not special in Python 2-
433 '''Return this instance' C{math.floor} as C{int} or C{float}.
435 @return: An C{int} in Python 3+, but C{float} in Python 2-.
437 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
438 '''
439 return self.floor
441 def __floordiv__(self, other):
442 '''Return C{B{self} // B{other}} as an L{Fsum}.
444 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
446 @return: The C{floor} quotient (L{Fsum}).
448 @see: Methods L{Fsum.__ifloordiv__}.
449 '''
450 f = self._copy_2(self.__floordiv__)
451 return f._floordiv(other, _floordiv_op_)
453 def __format__(self, *other): # PYCHOK no cover
454 '''Not implemented.'''
455 return _NotImplemented(self, *other)
457 def __ge__(self, other):
458 '''Compare this with an other instance or C{scalar}.
459 '''
460 return self._cmp_0(other, _ge_op_) >= 0
462 def __gt__(self, other):
463 '''Compare this with an other instance or C{scalar}.
464 '''
465 return self._cmp_0(other, _gt_op_) > 0
467 def __hash__(self): # PYCHOK no cover
468 '''Return this instance' C{hash}.
469 '''
470 return hash(self._ps) # XXX id(self)?
472 def __iadd__(self, other):
473 '''Apply C{B{self} += B{other}} to this instance.
475 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
476 an iterable of several of the former.
478 @return: This instance, updated (L{Fsum}).
480 @raise TypeError: Invalid B{C{other}}, not
481 C{scalar} nor L{Fsum}.
483 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
484 '''
485 try:
486 return self._fadd(other, _iadd_op_)
487 except TypeError:
488 return self._facc_inplace(other, _iadd_op_, self._facc)
490 def __ifloordiv__(self, other):
491 '''Apply C{B{self} //= B{other}} to this instance.
493 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
495 @return: This instance, updated (L{Fsum}).
497 @raise ResidualError: Non-zero, significant residual
498 in B{C{other}}.
500 @raise TypeError: Invalid B{C{other}} type.
502 @raise ValueError: Invalid or non-finite B{C{other}}.
504 @raise ZeroDivisionError: Zero B{C{other}}.
506 @see: Methods L{Fsum.__itruediv__}.
507 '''
508 return self._floordiv(other, _floordiv_op_ + _fset_op_)
510 def __imatmul__(self, other): # PYCHOK no cover
511 '''Not implemented.'''
512 return _NotImplemented(self, other)
514 def __imod__(self, other):
515 '''Apply C{B{self} %= B{other}} to this instance.
517 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
519 @return: This instance, updated (L{Fsum}).
521 @see: Method L{Fsum.__divmod__}.
522 '''
523 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
525 def __imul__(self, other):
526 '''Apply C{B{self} *= B{other}} to this instance.
528 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
530 @return: This instance, updated (L{Fsum}).
532 @raise OverflowError: Partial C{2sum} overflow.
534 @raise TypeError: Invalid B{C{other}} type.
536 @raise ValueError: Invalid or non-finite B{C{other}}.
537 '''
538 return self._fmul(other, _mul_op_ + _fset_op_)
540 def __int__(self):
541 '''Return this instance as an C{int}.
543 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
544 and L{Fsum.floor}.
545 '''
546 i, _ = self._fint2
547 return i
549 def __invert__(self): # PYCHOK no cover
550 '''Not implemented.'''
551 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
552 return _NotImplemented(self)
554 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
555 '''Apply C{B{self} **= B{other}} to this instance.
557 @arg other: The exponent (C{scalar}, L{Fsum} or L{Fsum2Tuple}).
558 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
559 C{pow(B{self}, B{other}, B{mod})} version.
560 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
561 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
562 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
564 @return: This instance, updated (L{Fsum}).
566 @note: If B{C{mod}} is given, the result will be an C{integer}
567 L{Fsum} in Python 3+ if this instance C{is_integer} or
568 set to C{as_integer} and B{C{mod}} is given and C{None}.
570 @raise OverflowError: Partial C{2sum} overflow.
572 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
573 is non-zero and significant and either
574 B{C{other}} is a fractional or negative
575 C{scalar} or B{C{mod}} is given and not
576 C{None}.
578 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
579 invocation failed.
581 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
582 instance is C{0} or B{C{other}} is a fractional
583 C{scalar} and this instance is negative or has a
584 non-zero and significant residual or B{C{mod}}
585 is given as C{0}.
587 @see: CPython function U{float_pow<https://GitHub.com/
588 python/cpython/blob/main/Objects/floatobject.c>}.
589 '''
590 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
592 def __isub__(self, other):
593 '''Apply C{B{self} -= B{other}} to this instance.
595 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
596 an iterable of several of the former.
598 @return: This instance, updated (L{Fsum}).
600 @raise TypeError: Invalid B{C{other}} type.
602 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
603 '''
604 try:
605 return self._fsub(other, _isub_op_)
606 except TypeError:
607 return self._facc_inplace(other, _isub_op_, self._facc_neg)
609 def __iter__(self):
610 '''Return an C{iter}ator over a C{partials} duplicate.
611 '''
612 return iter(self.partials)
614 def __itruediv__(self, other, **raiser_RESIDUAL):
615 '''Apply C{B{self} /= B{other}} to this instance.
617 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
618 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
619 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
620 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
622 @return: This instance, updated (L{Fsum}).
624 @raise OverflowError: Partial C{2sum} overflow.
626 @raise ResidualError: Non-zero, significant residual or invalid
627 B{C{RESIDUAL}}.
629 @raise TypeError: Invalid B{C{other}} type.
631 @raise ValueError: Invalid or non-finite B{C{other}}.
633 @raise ZeroDivisionError: Zero B{C{other}}.
635 @see: Method L{Fsum.__ifloordiv__}.
636 '''
637 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
639 def __le__(self, other):
640 '''Compare this with an other instance or C{scalar}.
641 '''
642 return self._cmp_0(other, _le_op_) <= 0
644 def __len__(self):
645 '''Return the number of values accumulated (C{int}).
646 '''
647 return self._n
649 def __lt__(self, other):
650 '''Compare this with an other instance or C{scalar}.
651 '''
652 return self._cmp_0(other, _lt_op_) < 0
654 def __matmul__(self, other): # PYCHOK no cover
655 '''Not implemented.'''
656 return _NotImplemented(self, other)
658 def __mod__(self, other):
659 '''Return C{B{self} % B{other}} as an L{Fsum}.
661 @see: Method L{Fsum.__imod__}.
662 '''
663 f = self._copy_2(self.__mod__)
664 return f._fdivmod2(other, _mod_op_).mod
666 def __mul__(self, other):
667 '''Return C{B{self} * B{other}} as an L{Fsum}.
669 @see: Method L{Fsum.__imul__}.
670 '''
671 f = self._copy_2(self.__mul__)
672 return f._fmul(other, _mul_op_)
674 def __ne__(self, other):
675 '''Compare this with an other instance or C{scalar}.
676 '''
677 return self._cmp_0(other, _ne_op_) != 0
679 def __neg__(self):
680 '''Return I{a copy of} this instance, I{negated}.
681 '''
682 f = self._copy_2(self.__neg__)
683 return f._fset(self._neg)
685 def __pos__(self):
686 '''Return this instance I{as-is}, like C{float.__pos__()}.
687 '''
688 return self if _pos_self else self._copy_2(self.__pos__)
690 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
691 '''Return C{B{self}**B{other}} as an L{Fsum}.
693 @see: Method L{Fsum.__ipow__}.
694 '''
695 f = self._copy_2(self.__pow__)
696 return f._fpow(other, _pow_op_, *mod)
698 def __radd__(self, other):
699 '''Return C{B{other} + B{self}} as an L{Fsum}.
701 @see: Method L{Fsum.__iadd__}.
702 '''
703 f = self._copy_2r(other, self.__radd__)
704 return f._fadd(self, _add_op_)
706 def __rdivmod__(self, other):
707 '''Return C{divmod(B{other}, B{self})} as 2-tuple
708 C{(quotient, remainder)}.
710 @see: Method L{Fsum.__divmod__}.
711 '''
712 f = self._copy_2r(other, self.__rdivmod__)
713 return f._fdivmod2(self, _divmod_op_)
715# def __repr__(self):
716# '''Return the default C{repr(this)}.
717# '''
718# return self.toRepr(lenc=True)
720 def __rfloordiv__(self, other):
721 '''Return C{B{other} // B{self}} as an L{Fsum}.
723 @see: Method L{Fsum.__ifloordiv__}.
724 '''
725 f = self._copy_2r(other, self.__rfloordiv__)
726 return f._floordiv(self, _floordiv_op_)
728 def __rmatmul__(self, other): # PYCHOK no cover
729 '''Not implemented.'''
730 return _NotImplemented(self, other)
732 def __rmod__(self, other):
733 '''Return C{B{other} % B{self}} as an L{Fsum}.
735 @see: Method L{Fsum.__imod__}.
736 '''
737 f = self._copy_2r(other, self.__rmod__)
738 return f._fdivmod2(self, _mod_op_).mod
740 def __rmul__(self, other):
741 '''Return C{B{other} * B{self}} as an L{Fsum}.
743 @see: Method L{Fsum.__imul__}.
744 '''
745 f = self._copy_2r(other, self.__rmul__)
746 return f._fmul(self, _mul_op_)
748 def __round__(self, *ndigits): # PYCHOK Python 3+
749 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
751 @arg ndigits: Optional number of digits (C{int}).
752 '''
753 f = self._copy_2(self.__round__)
754 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
755 return f._fset(round(float(self), *ndigits)) # can be C{int}
757 def __rpow__(self, other, *mod):
758 '''Return C{B{other}**B{self}} as an L{Fsum}.
760 @see: Method L{Fsum.__ipow__}.
761 '''
762 f = self._copy_2r(other, self.__rpow__)
763 return f._fpow(self, _pow_op_, *mod)
765 def __rsub__(self, other):
766 '''Return C{B{other} - B{self}} as L{Fsum}.
768 @see: Method L{Fsum.__isub__}.
769 '''
770 f = self._copy_2r(other, self.__rsub__)
771 return f._fsub(self, _sub_op_)
773 def __rtruediv__(self, other, **raiser_RESIDUAL):
774 '''Return C{B{other} / B{self}} as an L{Fsum}.
776 @see: Method L{Fsum.__itruediv__}.
777 '''
778 f = self._copy_2r(other, self.__rtruediv__)
779 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
781 def __str__(self):
782 '''Return the default C{str(self)}.
783 '''
784 return self.toStr(lenc=True)
786 def __sub__(self, other):
787 '''Return C{B{self} - B{other}} as an L{Fsum}.
789 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
791 @return: The difference (L{Fsum}).
793 @see: Method L{Fsum.__isub__}.
794 '''
795 f = self._copy_2(self.__sub__)
796 return f._fsub(other, _sub_op_)
798 def __truediv__(self, other, **raiser_RESIDUAL):
799 '''Return C{B{self} / B{other}} as an L{Fsum}.
801 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
802 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
803 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
804 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
806 @return: The quotient (L{Fsum}).
808 @raise ResidualError: Non-zero, significant residual or invalid
809 B{C{RESIDUAL}}.
811 @see: Method L{Fsum.__itruediv__}.
812 '''
813 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
815 __trunc__ = __int__
817 if _sys_version_info2 < (3, 0): # PYCHOK no cover
818 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
819 __div__ = __truediv__
820 __idiv__ = __itruediv__
821 __long__ = __int__
822 __nonzero__ = __bool__
823 __rdiv__ = __rtruediv__
825 def as_integer_ratio(self):
826 '''Return this instance as the ratio of 2 integers.
828 @return: 2-Tuple C{(numerator, denominator)} both C{int}
829 with C{numerator} signed and C{denominator}
830 non-zero, positive.
832 @see: Standard C{float.as_integer_ratio} in Python 2.7+.
833 '''
834 n, r = self._fint2
835 if r:
836 i, d = float(r).as_integer_ratio()
837 n *= d
838 n += i
839 else: # PYCHOK no cover
840 d = 1
841 return n, d
843 @property_RO
844 def as_iscalar(self):
845 '''Get this instance I{as-is} (L{Fsum} or C{scalar}), the
846 latter only if the C{residual} equals C{zero}.
847 '''
848 s, r = self._fprs2
849 return self if r else s
851 @property_RO
852 def ceil(self):
853 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
854 C{float} in Python 2-).
856 @note: This C{ceil} takes the C{residual} into account.
858 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
859 L{Fsum.imag} and L{Fsum.real}.
860 '''
861 s, r = self._fprs2
862 c = _ceil(s) + int(r) - 1
863 while r > (c - s): # (s + r) > c
864 c += 1
865 return c # _ceil(self._n_d)
867 cmp = __cmp__
869 def _cmp_0(self, other, op):
870 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
871 '''
872 if _isFsumTuple(other):
873 s = self._ps_1sum(*other._ps)
874 elif self._scalar(other, op):
875 s = self._ps_1sum(other)
876 else:
877 s = self.signOf() # res=True
878 return s
880 def copy(self, deep=False, **name):
881 '''Copy this instance, C{shallow} or B{C{deep}}.
883 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}).
885 @return: The copy (L{Fsum}).
886 '''
887 n = _name__(name, name__=self.copy)
888 f = _Named.copy(self, deep=deep, name=n)
889 if f._ps is self._ps:
890 f._ps = list(self._ps) # separate list
891 if not deep:
892 f._n = 1
893 # assert f._Fsum is f
894 return f
896 def _copy_2(self, which, name=NN):
897 '''(INTERNAL) Copy for I{dyadic} operators.
898 '''
899 n = name or which.__name__ # _dunder_nameof
900 # NOT .classof due to .Fdot(a, *b) args, etc.
901 f = _Named.copy(self, deep=False, name=n)
902 f._ps = list(self._ps) # separate list
903 # assert f._n == self._n
904 # assert f._Fsum is f
905 return f
907 def _copy_2r(self, other, which):
908 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
909 '''
910 return other._copy_2(which) if _isFsum(other) else \
911 self._copy_2(which)._fset(other)
913# def _copy_RESIDUAL(self, other):
914# '''(INTERNAL) Copy C{other._RESIDUAL}.
915# '''
916# R = other._RESIDUAL
917# if R is not Fsum._RESIDUAL:
918# self._RESIDUAL = R
920 divmod = __divmod__
922 def _Error(self, op, other, Error, **txt_cause):
923 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
924 '''
925 return Error(_SPACE_(self.as_iscalar, op, other), **txt_cause)
927 def _ErrorX(self, X, op, other, *mod):
928 '''(INTERNAL) Format the caught exception C{X}.
929 '''
930 E, t = _xError2(X)
931 if mod:
932 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
933 return self._Error(op, other, E, txt=t, cause=X)
935 def _ErrorXs(self, X, xs, **kwds): # in .fmath
936 '''(INTERNAL) Format the caught exception C{X}.
937 '''
938 E, t = _xError2(X)
939 u = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
940 return E(u, txt=t, cause=X)
942 def _facc(self, xs, up=True, **origin_X_x):
943 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s.
944 '''
945 if xs:
946 _xs = _2floats(xs, **origin_X_x) # PYCHOK yield
947 ps = self._ps
948 ps[:] = self._ps_acc(list(ps), _xs, up=up)
949 return self
951 def _facc_1(self, xs, **up):
952 '''(INTERNAL) Accumulate 0, 1 or more C{scalars} or L{Fsum}s,
953 all positional C{xs} in the caller of this method.
954 '''
955 return self._fadd(xs[0], _add_op_, **up) if len(xs) == 1 else \
956 self._facc(xs, origin=1, **up)
958 def _facc_inplace(self, other, op, _facc):
959 '''(INTERNAL) Accumulate from an iterable.
960 '''
961 try:
962 return _facc(other, origin=1) if _xiterable(other) else self
963 except Exception as X:
964 raise self._ErrorX(X, op, other)
966 def _facc_neg(self, xs, **up_origin):
967 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s, negated.
968 '''
969 def _N(X):
970 return X._ps_neg
972 def _n(x):
973 return -float(x)
975 return self._facc(xs, _X=_N, _x=_n, **up_origin)
977 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
978 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
979 '''
980 def _Pow4(p):
981 r = 0
982 if _isFsumTuple(p):
983 s, r = p._fprs2
984 if r:
985 m = Fsum._pow
986 else: # scalar
987 return _Pow4(s)
988 elif isint(p, both=True) and int(p) >= 0:
989 p = s = int(p)
990 m = Fsum._pow_int
991 else:
992 p = s = _2float(power=p)
993 m = Fsum._pow_scalar
994 return m, p, s, r
996 _Pow, p, s, r = _Pow4(power)
997 if p: # and xs:
998 op = which.__name__
999 _flt = float
1000 _Fs = Fsum
1001 _isa = isinstance
1002 _pow = self._pow_2_3
1004 def _P(X):
1005 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
1006 return f._ps if _isa(f, _Fs) else (f,)
1008 def _p(x):
1009 x = _flt(x)
1010 f = _pow(x, s, power, op, **raiser_RESIDUAL)
1011 if f and r:
1012 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
1013 return f
1015 f = self._facc(xs, origin=1, _X=_P, _x=_p)
1016 else:
1017 f = self._facc_scalar_(float(len(xs))) # x**0 == 1
1018 return f
1020 def _facc_scalar(self, xs, **up):
1021 '''(INTERNAL) Accumulate all C{xs}, known to be scalar.
1022 '''
1023 if xs:
1024 _ = self._ps_acc(self._ps, xs, **up)
1025 return self
1027 def _facc_scalar_(self, *xs, **up):
1028 '''(INTERNAL) Accumulate all positional C{xs}, known to be scalar.
1029 '''
1030 if xs:
1031 _ = self._ps_acc(self._ps, xs, **up)
1032 return self
1034# def _facc_up(self, up=True):
1035# '''(INTERNAL) Update the C{partials}, by removing
1036# and re-accumulating the final C{partial}.
1037# '''
1038# ps = self._ps
1039# while len(ps) > 1:
1040# p = ps.pop()
1041# if p:
1042# n = self._n
1043# _ = self._ps_acc(ps, (p,), up=False)
1044# self._n = n
1045# break
1046# return self._update() if up else self
1048 def fadd(self, xs=()):
1049 '''Add an iterable's items to this instance.
1051 @arg xs: Iterable of items to add (each C{scalar}
1052 or an L{Fsum} or L{Fsum2Tuple} instance).
1054 @return: This instance (L{Fsum}).
1056 @raise OverflowError: Partial C{2sum} overflow.
1058 @raise TypeError: An invalid B{C{xs}} item.
1060 @raise ValueError: Invalid or non-finite B{C{xs}} value.
1061 '''
1062 if _isFsumTuple(xs):
1063 self._facc_scalar(xs._ps)
1064 elif isscalar(xs): # for backward compatibility
1065 self._facc_scalar_(_2float(x=xs)) # PYCHOK no cover
1066 elif xs: # _xiterable(xs)
1067 self._facc(xs)
1068 return self
1070 def fadd_(self, *xs):
1071 '''Add all positional items to this instance.
1073 @arg xs: Values to add (each C{scalar} or an L{Fsum}
1074 or L{Fsum2Tuple} instance), all positional.
1076 @see: Method L{Fsum.fadd} for further details.
1077 '''
1078 return self._facc_1(xs)
1080 def _fadd(self, other, op, **up): # in .fmath.Fhorner
1081 '''(INTERNAL) Apply C{B{self} += B{other}}.
1082 '''
1083 if not self._ps: # new Fsum(x)
1084 self._fset(other, op=op, **up)
1085 elif _isFsumTuple(other):
1086 self._facc_scalar(other._ps, **up)
1087 elif self._scalar(other, op):
1088 self._facc_scalar_(other, **up)
1089 return self
1091 fcopy = copy # for backward compatibility
1092 fdiv = __itruediv__
1093 fdivmod = __divmod__
1095 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1096 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1097 '''
1098 # result mostly follows CPython function U{float_divmod
1099 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1100 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1101 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1102 if q: # == float // other == floor(float / other)
1103 self -= Fsum(q) * other # NOT other * q!
1105 s = signOf(other) # make signOf(self) == signOf(other)
1106 if s and self.signOf() == -s: # PYCHOK no cover
1107 self += other
1108 q -= 1
1109# t = self.signOf()
1110# if t and t != s:
1111# raise self._Error(op, other, _AssertionError, txt__=signOf)
1112 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1114 def _fhorner(self, x, cs, op): # in .fmath
1115 '''(INTERNAL) Add an L{Fhorner} evaluation of polynomial
1116 M{sum(cs[i] * x**i for i=0..len(cs)-1)}.
1117 '''
1118 if _xiterablen(cs):
1119 H = Fsum(name__=self._fhorner)
1120 if _isFsumTuple(x):
1121 _mul = H._mul_Fsum
1122 else:
1123 _mul = H._mul_scalar
1124 x = _2float(x=x)
1125 if len(cs) > 1 and x:
1126 for c in reversed(cs):
1127 H._fset_ps(_mul(x, op))
1128 H._fadd(c, op, up=False)
1129 else: # x == 0
1130 H = cs[0]
1131 self._fadd(H, op)
1132 return self
1134 def _finite(self, other, op=None):
1135 '''(INTERNAL) Return B{C{other}} if C{finite}.
1136 '''
1137 if _isfinite(other):
1138 return other
1139 raise ValueError(_not_finite_) if op is None else \
1140 self._Error(op, other, _ValueError, txt=_not_finite_)
1142 def fint(self, name=NN, **raiser_RESIDUAL):
1143 '''Return this instance' current running sum as C{integer}.
1145 @kwarg name: Optional, overriding C{B{name}="fint"} (C{str}).
1146 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1147 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1148 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1150 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1151 with a zero or insignificant I{integer} residual.
1153 @raise ResidualError: Non-zero, significant residual or invalid
1154 B{C{RESIDUAL}}.
1156 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1157 '''
1158 i, r = self._fint2
1159 if r:
1160 R = self._raiser(r, i, **raiser_RESIDUAL)
1161 if R:
1162 t = _stresidual(_integer_, r, **R)
1163 raise ResidualError(_integer_, i, txt=t)
1164 return _Psum_(i, name=_name__(name, name__=self.fint))
1166 def fint2(self, **name):
1167 '''Return this instance' current running sum as C{int} and the
1168 I{integer} residual.
1170 @kwarg name: Optional name (C{str}).
1172 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1173 an C{int} and I{integer} C{residual} a C{float} or
1174 C{INT0} if the C{fsum} is considered to be I{exact}.
1175 '''
1176 return Fsum2Tuple(*self._fint2, **name)
1178 @Property
1179 def _fint2(self): # see ._fset
1180 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1181 '''
1182 s, r = self._fprs2
1183 i = int(s)
1184 n = len(self._ps)
1185 r = self._ps_1sum(i) if r and n > 1 else float(s - i)
1186 return i, (r or INT0) # Fsum2Tuple?
1188 @_fint2.setter_ # PYCHOK setter_underscore!
1189 def _fint2(self, s):
1190 '''(INTERNAL) Replace the C{_fint2} value.
1191 '''
1192 i = int(s)
1193 return i, ((s - i) or INT0)
1195 @deprecated_property_RO
1196 def float_int(self): # PYCHOK no cover
1197 '''DEPRECATED, use method C{Fsum.int_float}.'''
1198 return self.int_float() # raiser=False
1200 @property_RO
1201 def floor(self):
1202 '''Get this instance' C{floor} (C{int} in Python 3+, but
1203 C{float} in Python 2-).
1205 @note: This C{floor} takes the C{residual} into account.
1207 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1208 L{Fsum.imag} and L{Fsum.real}.
1209 '''
1210 s, r = self._fprs2
1211 f = _floor(s) + _floor(r) + 1
1212 while (f - s) > r: # f > (s + r)
1213 f -= 1
1214 return f # _floor(self._n_d)
1216# ffloordiv = __ifloordiv__ # for naming consistency
1217# floordiv = __floordiv__ # for naming consistency
1219 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1220 '''Apply C{B{self} //= B{other}}.
1221 '''
1222 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1223 return self._fset(q.floor) # floor(q)
1225 fmul = __imul__
1227 def _fmul(self, other, op):
1228 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1229 '''
1230 if _isFsumTuple(other):
1231 if len(self._ps) != 1:
1232 f = self._mul_Fsum(other, op)
1233 elif len(other._ps) != 1: # and len(self._ps) == 1
1234 f = other._mul_scalar(self._ps[0], op)
1235 else: # len(other._ps) == len(self._ps) == 1
1236 f = self._finite(self._ps[0] * other._ps[0])
1237 else:
1238 s = self._scalar(other, op)
1239 f = self._mul_scalar(s, op)
1240 return self._fset(f) # n=len(self) + 1
1242 def fover(self, over, **raiser_RESIDUAL):
1243 '''Apply C{B{self} /= B{over}} and summate.
1245 @arg over: An L{Fsum} or C{scalar} denominator.
1246 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1247 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1248 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1250 @return: Precision running sum (C{float}).
1252 @raise ResidualError: Non-zero, significant residual or invalid
1253 B{C{RESIDUAL}}.
1255 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1256 '''
1257 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1259 fpow = __ipow__
1261 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1262 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1263 '''
1264 if mod:
1265 if mod[0] is not None: # == 3-arg C{pow}
1266 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1267 elif self.is_integer():
1268 # return an exact C{int} for C{int}**C{int}
1269 i, _ = self._fint2 # assert _ == 0
1270 x, r = _2scalar2(other) # C{int}, C{float} or other
1271 f = _Psum_(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1272 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1273 else: # mod[0] is None, power(self, other)
1274 f = self._pow(other, other, op, **raiser_RESIDUAL)
1275 else: # pow(self, other)
1276 f = self._pow(other, other, op, **raiser_RESIDUAL)
1277 return self._fset(f) # n=max(len(self), 1)
1279 @Property
1280 def _fprs(self):
1281 '''(INTERNAL) Get and cache this instance' precision
1282 running sum (C{float} or C{int}), ignoring C{residual}.
1284 @note: The precision running C{fsum} after a C{//=} or
1285 C{//} C{floor} division is C{int} in Python 3+.
1286 '''
1287 s, _ = self._fprs2
1288 return s # ._fprs2.fsum
1290 @_fprs.setter_ # PYCHOK setter_underscore!
1291 def _fprs(self, s):
1292 '''(INTERNAL) Replace the C{_fprs} value.
1293 '''
1294 return s
1296 @Property
1297 def _fprs2(self):
1298 '''(INTERNAL) Get and cache this instance' precision
1299 running sum and residual (L{Fsum2Tuple}).
1300 '''
1301 ps = self._ps
1302 n = len(ps) - 2
1303 if n > 0: # len(ps) > 2
1304 s = _psum(ps)
1305 n = len(ps) - 2
1306 if n > 0:
1307 r = self._ps_1sum(s)
1308 return Fsum2Tuple(*_s_r(s, r))
1309 if n == 0: # len(ps) == 2
1310 s, r = _s_r(*_2sum(*ps))
1311 ps[:] = (r, s) if r else (s,)
1312 elif ps: # len(ps) == 1
1313 s, r = ps[0], INT0
1314 else: # len(ps) == 0
1315 s, r = _0_0, INT0
1316 ps[:] = s,
1317 # assert self._ps is ps
1318 return Fsum2Tuple(s, r)
1320 @_fprs2.setter_ # PYCHOK setter_underscore!
1321 def _fprs2(self, s_r):
1322 '''(INTERNAL) Replace the C{_fprs2} value.
1323 '''
1324 return Fsum2Tuple(s_r)
1326 def fset_(self, *xs):
1327 '''Replace this instance' value with all positional items.
1329 @arg xs: Optional, new values (each C{scalar} or
1330 an L{Fsum} or L{Fsum2Tuple} instance),
1331 all positional.
1333 @return: This instance, replaced (C{Fsum}).
1335 @see: Method L{Fsum.fadd} for further details.
1336 '''
1337 f = xs[0] if len(xs) == 1 else (
1338 Fsum(*xs) if xs else _0_0)
1339 return self._fset(f)
1341 def _fset(self, other, n=0, up=True, **op):
1342 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1343 '''
1344 if other is self:
1345 pass # from ._fmul, ._ftruediv and ._pow_0_1
1346 elif _isFsumTuple(other):
1347 self._ps[:] = other._ps
1348 self._n = n or other._n
1349# self._copy_RESIDUAL(other)
1350 if up: # use or zap the C{Property_RO} values
1351 Fsum._fint2._update_from(self, other)
1352 Fsum._fprs ._update_from(self, other)
1353 Fsum._fprs2._update_from(self, other)
1354 elif isscalar(other):
1355 s = float(self._finite(other, **op)) if op else other
1356 self._ps[:] = s,
1357 self._n = n or 1
1358 if up: # Property _fint2, _fprs and _fprs2 all have
1359 # @.setter_underscore and NOT @.setter because the
1360 # latter's _fset zaps the value set by @.setter
1361 self._fint2 = s
1362 self._fprs = s
1363 self._fprs2 = s, INT0
1364 # assert self._fprs is s
1365 else: # PYCHOK no cover
1366 op = _xkwds_get1(op, op=_fset_op_)
1367 raise self._Error(op, other, _TypeError)
1368 return self
1370 def _fset_ps(self, other): # in .fmath
1371 '''(INTERNAL) Set partials from a known C{scalar}, L{Fsum} or L{Fsum2Tuple}.
1372 '''
1373 return self._fset(other, up=False)
1375 def fsub(self, xs=()):
1376 '''Subtract an iterable's items from this instance.
1378 @see: Method L{Fsum.fadd} for further details.
1379 '''
1380 return self._facc_neg(xs)
1382 def fsub_(self, *xs):
1383 '''Subtract all positional items from this instance.
1385 @see: Method L{Fsum.fadd_} for further details.
1386 '''
1387 return self._fsub(xs[0], _sub_op_) if len(xs) == 1 else \
1388 self._facc_neg(xs, origin=1)
1390 def _fsub(self, other, op):
1391 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1392 '''
1393 if _isFsumTuple(other):
1394 if other is self: # or other._fprs2 == self._fprs2:
1395 self._fset(_0_0, n=len(self) * 2)
1396 elif other._ps:
1397 self._facc_scalar(other._ps_neg)
1398 elif self._scalar(other, op):
1399 self._facc_scalar_(-other)
1400 return self
1402 def fsum(self, xs=()):
1403 '''Add an iterable's items, summate and return the
1404 current precision running sum.
1406 @arg xs: Iterable of items to add (each item C{scalar}
1407 or an L{Fsum} or L{Fsum2Tuple} instance).
1409 @return: Precision running sum (C{float} or C{int}).
1411 @see: Method L{Fsum.fadd}.
1413 @note: Accumulation can continue after summation.
1414 '''
1415 return self._facc(xs)._fprs
1417 def fsum_(self, *xs):
1418 '''Add any positional items, summate and return the
1419 current precision running sum.
1421 @arg xs: Items to add (each C{scalar} or an L{Fsum}
1422 or L{Fsum2Tuple} instance), all positional.
1424 @return: Precision running sum (C{float} or C{int}).
1426 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1427 '''
1428 return self._facc_1(xs)._fprs
1430 @property_RO
1431 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, for C{_2floats}, .fstats
1432 return self # NOT @Property_RO, see .copy and ._copy_2
1434 def Fsum_(self, *xs, **name):
1435 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1437 @kwarg name: Optional name (C{str}).
1439 @return: Copy of this updated instance (L{Fsum}).
1440 '''
1441 return self._facc_1(xs)._copy_2(self.Fsum_, **name)
1443 def Fsum2Tuple_(self, *xs, **name):
1444 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1446 @kwarg name: Optional name (C{str}).
1448 @return: Precision running sum (L{Fsum2Tuple}).
1449 '''
1450 return Fsum2Tuple(self._facc_1(xs)._fprs2, **name)
1452 def fsum2(self, xs=(), **name):
1453 '''Add an iterable's items, summate and return the
1454 current precision running sum I{and} the C{residual}.
1456 @arg xs: Iterable of items to add (each item C{scalar}
1457 or an L{Fsum} or L{Fsum2Tuple} instance).
1458 @kwarg name: Optional C{B{name}=NN} (C{str}).
1460 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1461 current precision running sum and C{residual}, the
1462 (precision) sum of the remaining C{partials}. The
1463 C{residual is INT0} if the C{fsum} is considered
1464 to be I{exact}.
1466 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1467 '''
1468 t = self._facc(xs)._fprs2
1469 return t.dup(name=name) if name else t
1471 def fsum2_(self, *xs):
1472 '''Add any positional items, summate and return the current
1473 precision running sum and the I{differential}.
1475 @arg xs: Values to add (each C{scalar} or an L{Fsum} or
1476 L{Fsum2Tuple} instance), all positional.
1478 @return: 2Tuple C{(fsum, delta)} with the current, precision
1479 running C{fsum} like method L{Fsum.fsum} and C{delta},
1480 the difference with previous running C{fsum}, C{float}.
1482 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1483 '''
1484 return self._fsum2(xs, self._facc_1)
1486 def _fsum2(self, xs, _facc, **origin):
1487 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1488 '''
1489 p, q = self._fprs2
1490 if xs:
1491 s, r = _facc(xs, **origin)._fprs2
1492 return s, _2delta(s - p, r - q) # _fsum(_1primed((s, -p, r, -q))
1493 else:
1494 return p, _0_0
1496 def fsumf_(self, *xs):
1497 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1498 '''
1499 return self._facc_scalar(xs)._fprs
1501 def Fsumf_(self, *xs):
1502 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1503 '''
1504 return self._facc_scalar(xs)._copy_2(self.Fsumf_)
1506 def fsum2f_(self, *xs):
1507 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}} are I{known to be scalar}.
1508 '''
1509 return self._fsum2(xs, self._facc_scalar, origin=1)
1511# ftruediv = __itruediv__ # for naming consistency?
1513 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1514 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1515 '''
1516 n = _1_0
1517 if _isFsumTuple(other):
1518 if other is self or self == other:
1519 return self._fset(n, n=len(self))
1520 d, r = other._fprs2
1521 if r:
1522 R = self._raiser(r, d, **raiser_RESIDUAL)
1523 if R:
1524 raise self._ResidualError(op, other, r, **R)
1525 d, n = other.as_integer_ratio()
1526 else:
1527 d = self._scalar(other, op)
1528 try:
1529 s = n / d
1530 except Exception as X:
1531 raise self._ErrorX(X, op, other)
1532 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1533 return self._fset(f)
1535 @property_RO
1536 def imag(self):
1537 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1539 @see: Property L{Fsum.real}.
1540 '''
1541 return _0_0
1543 def int_float(self, **raiser_RESIDUAL):
1544 '''Return this instance' current running sum as C{int} or C{float}.
1546 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1547 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1548 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1550 @return: This C{integer} sum if this instance C{is_integer},
1551 otherwise return the C{float} sum if the residual is
1552 zero or not significant.
1554 @raise ResidualError: Non-zero, significant residual or invalid
1555 B{C{RESIDUAL}}.
1557 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.RESIDUAL} and
1558 property L{Fsum.as_iscalar}.
1559 '''
1560 s, r = self._fint2
1561 if r:
1562 s, r = self._fprs2
1563 if r: # PYCHOK no cover
1564 R = self._raiser(r, s, **raiser_RESIDUAL)
1565 if R:
1566 t = _stresidual(_non_zero_, r, **R)
1567 raise ResidualError(int_float=s, txt=t)
1568 s = float(s)
1569 return s
1571 def is_exact(self):
1572 '''Is this instance' running C{fsum} considered to be exact?
1573 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1574 '''
1575 return self.residual is INT0
1577 def is_integer(self):
1578 '''Is this instance' running sum C{integer}? (C{bool}).
1580 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1581 '''
1582 _, r = self._fint2
1583 return False if r else True
1585 def is_math_fsum(self):
1586 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and
1587 L{fsum1_} plus partials summation are based on Python's
1588 C{math.fsum} or not.
1590 @return: C{2} if all functions and partials summation
1591 are based on C{math.fsum}, C{True} if only
1592 the functions are based on C{math.fsum} (and
1593 partials summation is not) or C{False} if
1594 none are.
1595 '''
1596 f = Fsum._math_fsum
1597 return 2 if _psum is f else bool(f)
1599 def is_scalar(self, **raiser_RESIDUAL):
1600 '''Is this instance' running sum C{scalar} without residual or with
1601 a residual I{ratio} not exceeding the RESIDUAL threshold?
1603 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1604 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1605 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1607 @return: C{True} if this instance' non-zero residual C{ratio} exceeds
1608 the L{RESIDUAL<Fsum.RESIDUAL>} threshold (C{bool}).
1610 @raise ResidualError: Non-zero, significant residual or invalid
1611 B{C{RESIDUAL}}.
1613 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property
1614 L{Fsum.as_iscalar}.
1615 '''
1616 s, r = self._fprs2
1617 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1619 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1620 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1621 '''
1622 # assert _isFsumTuple(other)
1623 if self._ps and other._ps:
1624 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
1625 else:
1626 f = _0_0
1627 return f
1629 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1630 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
1631 '''
1632 # assert isscalar(factor)
1633 if self._ps and self._finite(factor, op):
1634 f = self if factor == _1_0 else (
1635 self._neg if factor == _N_1_0 else
1636 self._ps_mul(op, factor).as_iscalar)
1637 else:
1638 f = _0_0
1639 return f
1641# @property_RO
1642# def _n_d(self):
1643# n, d = self.as_integer_ratio()
1644# return n / d
1646 @property_RO
1647 def _neg(self):
1648 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
1649 '''
1650 return _Psum(self._ps_neg) if self._ps else NEG0
1652 @property_RO
1653 def partials(self):
1654 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
1655 '''
1656 return tuple(self._ps)
1658 def pow(self, x, *mod, **raiser_RESIDUAL):
1659 '''Return C{B{self}**B{x}} as L{Fsum}.
1661 @arg x: The exponent (C{scalar} or L{Fsum}).
1662 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
1663 C{pow(B{self}, B{other}, B{mod})} version.
1664 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1665 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1666 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1668 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
1669 result (L{Fsum}).
1671 @raise ResidualError: Non-zero, significant residual or invalid
1672 B{C{RESIDUAL}}.
1674 @note: If B{C{mod}} is given and C{None}, the result will be an
1675 C{integer} L{Fsum} provided this instance C{is_integer}
1676 or set to C{integer} by an L{Fsum.fint} call.
1678 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
1679 and L{Fsum.root}.
1680 '''
1681 f = self._copy_2(self.pow)
1682 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
1684 def _pow(self, other, unused, op, **raiser_RESIDUAL):
1685 '''Return C{B{self} ** B{other}}.
1686 '''
1687 if _isFsumTuple(other):
1688 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
1689 elif self._scalar(other, op):
1690 x = self._finite(other, op)
1691 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1692 else:
1693 f = self._pow_0_1(0, other)
1694 return f
1696 def _pow_0_1(self, x, other):
1697 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
1698 '''
1699 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
1701 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
1702 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
1703 B{x}, int B{mod} or C{None})}, embellishing errors.
1704 '''
1706 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
1707 m = mod[0]
1708 # assert _isFsumTuple(b)
1710 def _s(s, r):
1711 R = self._raiser(r, s, **raiser_RESIDUAL)
1712 if R:
1713 raise self._ResidualError(op, other, r, mod=m, **R)
1714 return s
1716 b = _s(*(b._fprs2 if m is None else b._fint2))
1717 x = _s(*_2scalar2(x))
1719 try:
1720 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
1721 s = pow(b, x, *mod)
1722 if iscomplex(s):
1723 # neg**frac == complex in Python 3+, but ValueError in 2-
1724 raise ValueError(_strcomplex(s, b, x, *mod))
1725 return self._finite(s)
1726 except Exception as X:
1727 raise self._ErrorX(X, op, other, *mod)
1729 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
1730 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsumTuple(other)}.
1731 '''
1732 # assert _isFsumTuple(other)
1733 x, r = other._fprs2
1734 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1735 if f and r:
1736 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
1737 return f
1739 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
1740 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
1741 '''
1742 # assert isint(x) and x >= 0
1743 ps = self._ps
1744 if len(ps) > 1:
1745 _mul_Fsum = Fsum._mul_Fsum
1746 if x > 4:
1747 p = self
1748 f = self if (x & 1) else _Psum_(_1_0)
1749 m = x >> 1 # // 2
1750 while m:
1751 p = _mul_Fsum(p, p, op) # p **= 2
1752 if (m & 1):
1753 f = _mul_Fsum(f, p, op) # f *= p
1754 m >>= 1 # //= 2
1755 elif x > 1: # self**2, 3, or 4
1756 f = _mul_Fsum(self, self, op)
1757 if x > 2: # self**3 or 4
1758 p = self if x < 4 else f
1759 f = _mul_Fsum(f, p, op)
1760 else: # self**1 or self**0 == 1 or _1_0
1761 f = self._pow_0_1(x, other)
1762 elif ps: # self._ps[0]**x
1763 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
1764 else: # PYCHOK no cover
1765 # 0**pos_int == 0, but 0**0 == 1
1766 f = 0 if x else 1
1767 return f
1769 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
1770 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
1771 '''
1772 s, r = self._fprs2
1773 if r:
1774 # assert s != 0
1775 if isint(x, both=True): # self**int
1776 x = int(x)
1777 y = abs(x)
1778 if y > 1:
1779 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
1780 if x > 0: # i.e. > 1
1781 return f # Fsum or scalar
1782 # assert x < 0 # i.e. < -1
1783 if _isFsum(f):
1784 s, r = f._fprs2
1785 if r:
1786 return _1_Over(f, op, **raiser_RESIDUAL)
1787 else: # scalar
1788 s = f
1789 # use s**(-1) to get the CPython
1790 # float_pow error iff s is zero
1791 x = -1
1792 elif x < 0: # self**(-1)
1793 return _1_Over(self, op, **raiser_RESIDUAL) # 1 / self
1794 else: # self**1 or self**0
1795 return self._pow_0_1(x, other) # self, 1 or 1.0
1796 else: # self**fractional
1797 R = self._raiser(r, s, **raiser_RESIDUAL)
1798 if R:
1799 raise self._ResidualError(op, other, r, **R)
1800 n, d = self.as_integer_ratio()
1801 if abs(n) > abs(d):
1802 n, d, x = d, n, (-x)
1803 s = n / d
1804 # assert isscalar(s) and isscalar(x)
1805 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
1807 def _ps_acc(self, ps, xs, up=True, **unused):
1808 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.
1809 '''
1810 n = 0
1811 _2s = _2sum
1812 for x in (tuple(xs) if xs is ps else xs):
1813 # assert isscalar(x) and _isfinite(x)
1814 if x:
1815 i = 0
1816 for p in ps:
1817 x, p = _2s(x, p)
1818 if p:
1819 ps[i] = p
1820 i += 1
1821 ps[i:] = (x,) if x else ()
1822 n += 1
1823 if n:
1824 self._n += n
1825 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
1826 if up:
1827 self._update()
1828 return ps
1830 def _ps_mul(self, op, *factors):
1831 '''(INTERNAL) Multiply this instance' C{partials} with
1832 each scalar C{factor} and accumulate into an C{Fsum}.
1833 '''
1834 def _pfs(ps, fs):
1835 if len(ps) < len(fs):
1836 ps, fs = fs, ps
1837 _fin = _isfinite
1838 for f in fs:
1839 for p in ps:
1840 p *= f
1841 yield p if _fin(p) else self._finite(p, op)
1843 return Fsum()._facc_scalar(_pfs(self._ps, factors), up=False)
1845 @property_RO
1846 def _ps_neg(self):
1847 '''(INTERNAL) Yield the partials, I{negated}.
1848 '''
1849 for p in self._ps:
1850 yield -p
1852 def _ps_1sum(self, *less):
1853 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
1854 '''
1855 def _1pls(ps, ls):
1856 yield _1_0
1857 for p in ps:
1858 yield p
1859 for p in ls:
1860 yield -p
1861 yield _N_1_0
1863 return _fsum(_1pls(self._ps, less))
1865 def _raiser(self, r, s, raiser=True, **RESIDUAL):
1866 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
1867 I{and} is residual C{r} I{non-zero} or I{significant} (for a
1868 negative respectively positive C{RESIDUAL} threshold)?
1869 '''
1870 if r and raiser:
1871 t = self._RESIDUAL
1872 if RESIDUAL:
1873 t = _threshold(t, **RESIDUAL)
1874 if t < 0 or (s + r) != s:
1875 q = (r / s) if s else s # == 0.
1876 if fabs(q) > fabs(t):
1877 return dict(ratio=q, R=t)
1878 return {}
1880 rdiv = __rtruediv__
1882 @property_RO
1883 def real(self):
1884 '''Get the C{real} part of this instance (C{float}).
1886 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
1887 and properties L{Fsum.ceil}, L{Fsum.floor},
1888 L{Fsum.imag} and L{Fsum.residual}.
1889 '''
1890 return float(self._fprs)
1892 @property_RO
1893 def residual(self):
1894 '''Get this instance' residual (C{float} or C{int}): the
1895 C{sum(partials)} less the precision running sum C{fsum}.
1897 @note: The C{residual is INT0} iff the precision running
1898 C{fsum} is considered to be I{exact}.
1900 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
1901 '''
1902 return self._fprs2.residual
1904 def RESIDUAL(self, *threshold):
1905 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
1906 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
1908 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
1909 L{ResidualError}s in division and exponention, if
1910 C{None} restore the default set with env variable
1911 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
1912 current setting.
1914 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
1916 @raise ResidualError: Invalid B{C{threshold}}.
1918 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}
1919 C{residual / fsum} exceeds the given B{C{threshold}} and (2)
1920 the C{residual} is non-zero and (3) I{significant} vs the
1921 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional
1922 keyword argument C{raiser=False} is missing. Specify a
1923 negative B{C{threshold}} for only non-zero C{residual}
1924 testing without I{significant}.
1925 '''
1926 r = self._RESIDUAL
1927 if threshold:
1928 t = threshold[0]
1929 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
1930 (_0_0 if t else _1_0) if isbool(t) else
1931 _threshold(t)) # ... backward compatibility
1932 return r
1934 def _ResidualError(self, op, other, residual, **mod_R):
1935 '''(INTERNAL) Non-zero B{C{residual}} etc.
1936 '''
1937 def _p(mod=None, R=0, **unused): # ratio=0
1938 return (_non_zero_ if R < 0 else _significant_) \
1939 if mod is None else _integer_
1941 t = _stresidual(_p(**mod_R), residual, **mod_R)
1942 return self._Error(op, other, ResidualError, txt=t)
1944 def root(self, root, **raiser_RESIDUAL):
1945 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
1947 @arg root: The order (C{scalar} or L{Fsum}), non-zero.
1948 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1949 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1950 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1952 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
1954 @raise ResidualError: Non-zero, significant residual or invalid
1955 B{C{RESIDUAL}}.
1957 @see: Method L{Fsum.pow}.
1958 '''
1959 x = _1_Over(root, _truediv_op_, **raiser_RESIDUAL)
1960 f = self._copy_2(self.root)
1961 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
1963 def _scalar(self, other, op, **txt):
1964 '''(INTERNAL) Return scalar C{other}.
1965 '''
1966 if isscalar(other):
1967 return other
1968 raise self._Error(op, other, _TypeError, **txt) # _invalid_
1970 def signOf(self, res=True):
1971 '''Determine the sign of this instance.
1973 @kwarg res: If C{True} consider, otherwise
1974 ignore the residual (C{bool}).
1976 @return: The sign (C{int}, -1, 0 or +1).
1977 '''
1978 s, r = self._fprs2
1979 r = (-r) if res else 0
1980 return _signOf(s, r)
1982 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
1983 '''Return this C{Fsum} instance as representation.
1985 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
1986 for method L{Fsum.toStr}.
1988 @return: This instance (C{repr}).
1989 '''
1990 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
1992 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
1993 '''Return this C{Fsum} instance as string.
1995 @kwarg lenc: If C{True} include the current C{[len]} of this
1996 L{Fsum} enclosed in I{[brackets]} (C{bool}).
1997 @kwarg prec_sep_fmt: Optional keyword arguments for method
1998 L{Fsum2Tuple.toStr}.
2000 @return: This instance (C{str}).
2001 '''
2002 p = self.classname
2003 if lenc:
2004 p = Fmt.SQUARE(p, len(self))
2005 n = _enquote(self.name, white=_UNDER_)
2006 t = self._fprs2.toStr(**prec_sep_fmt)
2007 return NN(p, _SPACE_, n, t)
2009 def _truediv(self, other, op, **raiser_RESIDUAL):
2010 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
2011 '''
2012 f = self._copy_2(self.__truediv__)
2013 return f._ftruediv(other, op, **raiser_RESIDUAL)
2015 def _update(self, updated=True): # see ._fset
2016 '''(INTERNAL) Zap all cached C{Property_RO} values.
2017 '''
2018 if updated:
2019 _pop = self.__dict__.pop
2020 for p in _ROs:
2021 _ = _pop(p, None)
2022# Fsum._fint2._update(self)
2023# Fsum._fprs ._update(self)
2024# Fsum._fprs2._update(self)
2025 return self # for .fset_
2027_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
2030def _Float_Int(arg, **name_Error):
2031 '''(INTERNAL) Unit of L{Fsum2Tuple} items.
2032 '''
2033 U = Int if isint(arg) else Float
2034 return U(arg, **name_Error)
2037class DivMod2Tuple(_NamedTuple):
2038 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
2039 C{mod} results of a C{divmod} operation.
2041 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2042 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2043 '''
2044 _Names_ = (_div_, _mod_)
2045 _Units_ = (_Float_Int, Fsum)
2048class Fsum2Tuple(_NamedTuple): # in .fstats
2049 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2050 and the C{residual}, the sum of the remaining partials. Each
2051 item is C{float} or C{int}.
2053 @note: If the C{residual is INT0}, the C{fsum} is considered
2054 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2055 '''
2056 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2057 _Units_ = (_Float_Int, _Float_Int)
2059 def __abs__(self): # in .fmath
2060 return self._Fsum.__abs__()
2062 def __bool__(self): # PYCHOK Python 3+
2063 return bool(self._Fsum)
2065 def __eq__(self, other):
2066 return self._other_op(other, self.__eq__)
2068 def __float__(self):
2069 return self._Fsum.__float__()
2071 def __ge__(self, other):
2072 return self._other_op(other, self.__ge__)
2074 def __gt__(self, other):
2075 return self._other_op(other, self.__gt__)
2077 def __le__(self, other):
2078 return self._other_op(other, self.__le__)
2080 def __lt__(self, other):
2081 return self._other_op(other, self.__lt__)
2083 def __int__(self):
2084 return self._Fsum.__int__()
2086 def __ne__(self, other):
2087 return self._other_op(other, self.__ne__)
2089 def __neg__(self):
2090 return self._Fsum.__neg__()
2092 __nonzero__ = __bool__ # Python 2-
2094 def __pos__(self):
2095 return self._Fsum.__pos__()
2097 def as_integer_ratio(self):
2098 '''Return this instance as the ratio of 2 integers.
2100 @see: Method L{Fsum.as_integer_ratio} for further details.
2101 '''
2102 return self._Fsum.as_integer_ratio()
2104 @property_RO
2105 def _fint2(self):
2106 return self._Fsum._fint2
2108 @property_RO
2109 def _fprs2(self):
2110 return self._Fsum._fprs2
2112 @Property_RO
2113 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2114 s, r = _s_r(*self)
2115 ps = (r, s) if r else (s,)
2116 return _Psum(ps, name=self.name)
2118 def Fsum_(self, *xs, **name_RESIDUAL):
2119 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2120 '''
2121 f = _Psum(self._Fsum._ps, **name_RESIDUAL)
2122 return f._facc_1(xs, up=False) if xs else f
2124 def is_exact(self):
2125 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2126 '''
2127 return self._Fsum.is_exact()
2129 def is_integer(self):
2130 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2131 '''
2132 return self._Fsum.is_integer()
2134 def _mul_scalar(self, other, op): # for Fsum._fmul
2135 return self._Fsum._mul_scalar(other, op)
2137 @property_RO
2138 def _n(self):
2139 return self._Fsum._n
2141 def _other_op(self, other, which):
2142 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2143 return getattr(C, which.__name__)(s, other)
2145 @property_RO
2146 def _ps(self):
2147 return self._Fsum._ps
2149 @property_RO
2150 def _ps_neg(self):
2151 return self._Fsum._ps_neg
2153 def signOf(self, **res):
2154 '''Like method L{Fsum.signOf}.
2155 '''
2156 return self._Fsum.signOf(**res)
2158 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2159 '''Return this L{Fsum2Tuple} as string (C{str}).
2161 @kwarg fmt: Optional C{float} format (C{letter}).
2162 @kwarg prec_sep: Optional keyword arguments for function
2163 L{fstr<streprs.fstr>}.
2164 '''
2165 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2167_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2170class ResidualError(_ValueError):
2171 '''Error raised for a division, power or root operation of
2172 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2173 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2175 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2176 '''
2177 pass
2180try:
2181 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2183 # make sure _fsum works as expected (XXX check
2184 # float.__getformat__('float')[:4] == 'IEEE'?)
2185 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2186 del _fsum # nope, remove _fsum ...
2187 raise ImportError() # ... use _fsum below
2189 Fsum._math_fsum = _sum = _fsum # PYCHOK exported
2190except ImportError:
2191 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic
2193 def _fsum(xs):
2194 '''(INTERNAL) Precision summation, Python 2.5-.
2195 '''
2196 F = Fsum()
2197 F.name = _fsum.__name__
2198 return F._facc(xs, up=False)._fprs2.fsum
2201def fsum(xs, floats=False):
2202 '''Precision floating point summation based on/like Python's C{math.fsum}.
2204 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2205 instance).
2206 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2207 be scalar} (C{bool}).
2209 @return: Precision C{fsum} (C{float}).
2211 @raise OverflowError: Partial C{2sum} overflow.
2213 @raise TypeError: Non-scalar B{C{xs}} item.
2215 @raise ValueError: Invalid or non-finite B{C{xs}} item.
2217 @note: Exception and I{non-finite} handling may differ if not based
2218 on Python's C{math.fsum}.
2220 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.
2221 '''
2222 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield
2225def fsum_(*xs, **floats):
2226 '''Precision floating point summation of all positional items.
2228 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2229 all positional.
2230 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2231 be scalar} (C{bool}).
2233 @see: Function L{fsum<fsums.fsum>} for further details.
2234 '''
2235 return _fsum(xs if _xkwds_get1(floats, floats=False) is True else
2236 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield
2239def fsumf_(*xs):
2240 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2242 @see: Function L{fsum_<fsums.fsum_>} for further details.
2243 '''
2244 return _fsum(xs) if xs else _0_0
2247def fsum1(xs, floats=False):
2248 '''Precision floating point summation, 1-primed.
2250 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2251 instance).
2252 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2253 be scalar} (C{bool}).
2255 @see: Function L{fsum<fsums.fsum>} for further details.
2256 '''
2257 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield
2260def fsum1_(*xs, **floats):
2261 '''Precision floating point summation, 1-primed of all positional items.
2263 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2264 all positional.
2265 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2266 be scalar} (C{bool}).
2268 @see: Function L{fsum_<fsums.fsum_>} for further details.
2269 '''
2270 return _fsum(_1primed(xs if _xkwds_get1(floats, floats=False) is True else
2271 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield
2274def fsum1f_(*xs):
2275 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2277 @see: Function L{fsum_<fsums.fsum_>} for further details.
2278 '''
2279 return _fsum(_1primed(xs)) if xs else _0_0
2282if __name__ == '__main__':
2284 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums
2286 if _getenv(_psum.__name__, NN) == _fsum.__name__:
2287 _psum = _fsum
2289 def _test(n):
2290 # copied from Hettinger, see L{Fsum} reference
2291 from pygeodesy import frandoms, printf
2293 printf(_fsum.__name__, end=_COMMASPACE_)
2294 printf(_psum.__name__, end=_COMMASPACE_)
2296 F = Fsum()
2297 if F.is_math_fsum():
2298 for t in frandoms(n, seeded=True):
2299 assert float(F.fset_(*t)) == _fsum(t)
2300 printf(_DOT_, end=NN)
2301 printf(NN)
2303 _test(128)
2305# **) MIT License
2306#
2307# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
2308#
2309# Permission is hereby granted, free of charge, to any person obtaining a
2310# copy of this software and associated documentation files (the "Software"),
2311# to deal in the Software without restriction, including without limitation
2312# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2313# and/or sell copies of the Software, and to permit persons to whom the
2314# Software is furnished to do so, subject to the following conditions:
2315#
2316# The above copyright notice and this permission notice shall be included
2317# in all copies or substantial portions of the Software.
2318#
2319# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2320# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2321# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2322# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2323# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2324# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2325# OTHER DEALINGS IN THE SOFTWARE.