Coverage for pygeodesy/fsums.py: 97%
876 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-25 12:04 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-25 12:04 -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 _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_get, \
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_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.05.24'
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 s = a + b
277 if _isfinite(s):
278 if fabs(a) < fabs(b):
279 b, a = a, b
280 return s, (b - (s - a))
281 u = unstr(_2sum, a, b)
282 t = Fmt.PARENSPACED(_not_finite_, s)
283 raise _OverflowError(u, txt=t)
286def _threshold(threshold=_0_0, **kwds):
287 '''(INTERNAL) Get the L{ResidualError}s threshold,
288 optionally from single kwds C{B{RESIDUAL}=scalar}.
289 '''
290 if kwds:
291 threshold, kwds = _xkwds_pop2(kwds, RESIDUAL=threshold)
292# threshold = kwds.pop('RESIDUAL', threshold)
293 if kwds:
294 raise _UnexpectedError(**kwds)
295 try:
296 return _2finite(threshold) # PYCHOK None
297 except Exception as x:
298 raise ResidualError(threshold=threshold, cause=x)
301class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase
302 '''Precision floating point summation and I{running} summation.
304 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
305 I{running}, precision floating point summations. Accumulation may continue after any
306 intermediate, I{running} summuation.
308 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances,
309 any C{type} having method C{__float__} to convert the C{scalar} to a single
310 C{float}, except C{complex}.
312 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from
313 Python's C{math.fsum}.
315 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/
316 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>},
317 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
318 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
319 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
320 <https://Bugs.Python.org/issue2819>}.
321 '''
322 _math_fsum = None
323 _n = 0
324# _ps = [] # partial sums
325# _ps_max = 0 # max(Fsum._ps_max, len(Fsum._ps))
326 _RESIDUAL = _threshold(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0))
328 def __init__(self, *xs, **name_RESIDUAL):
329 '''New L{Fsum} for I{running} precision floating point summation.
331 @arg xs: No, one or more initial items to add (each C{scalar} or
332 an L{Fsum} or L{Fsum2Tuple} instance), all positional.
333 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) for this
334 L{Fsum} and the C{B{RESIDUAL}=0.0} threshold for
335 L{ResidualError}s (C{scalar}).
337 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.
338 '''
339 if name_RESIDUAL:
340 n, kwds = _name2__(**name_RESIDUAL)
341 if kwds:
342 R = Fsum._RESIDUAL
343 t = _threshold(R, **kwds)
344 if t != R:
345 self._RESIDUAL = t
346 if n:
347 self.name = n
349 self._ps = [] # [_0_0], see L{Fsum._fprs}
350 if xs:
351 self._facc_1(xs, up=False)
353 def __abs__(self):
354 '''Return this instance' absolute value as an L{Fsum}.
355 '''
356 s = self.signOf() # == self._cmp_0(0)
357 return (-self) if s < 0 else self._copy_2(self.__abs__)
359 def __add__(self, other):
360 '''Return C{B{self} + B{other}} as an L{Fsum}.
362 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
364 @return: The sum (L{Fsum}).
366 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
367 '''
368 f = self._copy_2(self.__add__)
369 return f._fadd(other, _add_op_)
371 def __bool__(self): # PYCHOK Python 3+
372 '''Return C{True} if this instance is I{exactly} non-zero.
373 '''
374 s, r = self._fprs2
375 return bool(s or r) and s != -r # == self != 0
377 def __ceil__(self): # PYCHOK not special in Python 2-
378 '''Return this instance' C{math.ceil} as C{int} or C{float}.
380 @return: An C{int} in Python 3+, but C{float} in Python 2-.
382 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
383 '''
384 return self.ceil
386 def __cmp__(self, other): # PYCHOK no cover
387 '''Compare this with an other instance or C{scalar}, Python 2-.
389 @return: -1, 0 or +1 (C{int}).
391 @raise TypeError: Incompatible B{C{other}} C{type}.
392 '''
393 s = self._cmp_0(other, self.cmp.__name__)
394 return _signOf(s, 0)
396 def __divmod__(self, other, **raiser_RESIDUAL):
397 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
398 with quotient C{div} an C{int} in Python 3+ or C{float}
399 in Python 2- and remainder C{mod} an L{Fsum} instance.
401 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
402 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
403 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
404 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
406 @raise ResidualError: Non-zero, significant residual or invalid
407 B{C{RESIDUAL}}.
409 @see: Method L{Fsum.fdiv}.
410 '''
411 f = self._copy_2(self.__divmod__)
412 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
414 def __eq__(self, other):
415 '''Compare this with an other instance or C{scalar}.
416 '''
417 return self._cmp_0(other, _eq_op_) == 0
419 def __float__(self):
420 '''Return this instance' current, precision running sum as C{float}.
422 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
423 '''
424 return float(self._fprs)
426 def __floor__(self): # PYCHOK not special in Python 2-
427 '''Return this instance' C{math.floor} as C{int} or C{float}.
429 @return: An C{int} in Python 3+, but C{float} in Python 2-.
431 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
432 '''
433 return self.floor
435 def __floordiv__(self, other):
436 '''Return C{B{self} // B{other}} as an L{Fsum}.
438 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
440 @return: The C{floor} quotient (L{Fsum}).
442 @see: Methods L{Fsum.__ifloordiv__}.
443 '''
444 f = self._copy_2(self.__floordiv__)
445 return f._floordiv(other, _floordiv_op_)
447 def __format__(self, *other): # PYCHOK no cover
448 '''Not implemented.'''
449 return _NotImplemented(self, *other)
451 def __ge__(self, other):
452 '''Compare this with an other instance or C{scalar}.
453 '''
454 return self._cmp_0(other, _ge_op_) >= 0
456 def __gt__(self, other):
457 '''Compare this with an other instance or C{scalar}.
458 '''
459 return self._cmp_0(other, _gt_op_) > 0
461 def __hash__(self): # PYCHOK no cover
462 '''Return this instance' C{hash}.
463 '''
464 return hash(self._ps) # XXX id(self)?
466 def __iadd__(self, other):
467 '''Apply C{B{self} += B{other}} to this instance.
469 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
470 an iterable of several of the former.
472 @return: This instance, updated (L{Fsum}).
474 @raise TypeError: Invalid B{C{other}}, not
475 C{scalar} nor L{Fsum}.
477 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
478 '''
479 try:
480 return self._fadd(other, _iadd_op_)
481 except TypeError:
482 return self._facc_inplace(other, _iadd_op_, self._facc)
484 def __ifloordiv__(self, other):
485 '''Apply C{B{self} //= B{other}} to this instance.
487 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
489 @return: This instance, updated (L{Fsum}).
491 @raise ResidualError: Non-zero, significant residual
492 in B{C{other}}.
494 @raise TypeError: Invalid B{C{other}} type.
496 @raise ValueError: Invalid or non-finite B{C{other}}.
498 @raise ZeroDivisionError: Zero B{C{other}}.
500 @see: Methods L{Fsum.__itruediv__}.
501 '''
502 return self._floordiv(other, _floordiv_op_ + _fset_op_)
504 def __imatmul__(self, other): # PYCHOK no cover
505 '''Not implemented.'''
506 return _NotImplemented(self, other)
508 def __imod__(self, other):
509 '''Apply C{B{self} %= B{other}} to this instance.
511 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
513 @return: This instance, updated (L{Fsum}).
515 @see: Method L{Fsum.__divmod__}.
516 '''
517 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
519 def __imul__(self, other):
520 '''Apply C{B{self} *= B{other}} to this instance.
522 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
524 @return: This instance, updated (L{Fsum}).
526 @raise OverflowError: Partial C{2sum} overflow.
528 @raise TypeError: Invalid B{C{other}} type.
530 @raise ValueError: Invalid or non-finite B{C{other}}.
531 '''
532 return self._fmul(other, _mul_op_ + _fset_op_)
534 def __int__(self):
535 '''Return this instance as an C{int}.
537 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
538 and L{Fsum.floor}.
539 '''
540 i, _ = self._fint2
541 return i
543 def __invert__(self): # PYCHOK no cover
544 '''Not implemented.'''
545 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
546 return _NotImplemented(self)
548 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
549 '''Apply C{B{self} **= B{other}} to this instance.
551 @arg other: The exponent (C{scalar}, L{Fsum} or L{Fsum2Tuple}).
552 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
553 C{pow(B{self}, B{other}, B{mod})} version.
554 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
555 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
556 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
558 @return: This instance, updated (L{Fsum}).
560 @note: If B{C{mod}} is given, the result will be an C{integer}
561 L{Fsum} in Python 3+ if this instance C{is_integer} or
562 set to C{as_integer} and B{C{mod}} is given as C{None}.
564 @raise OverflowError: Partial C{2sum} overflow.
566 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
567 is non-zero and significant and either
568 B{C{other}} is a fractional or negative
569 C{scalar} or B{C{mod}} is given and not
570 C{None}.
572 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
573 invocation failed.
575 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
576 instance is C{0} or B{C{other}} is a fractional
577 C{scalar} and this instance is negative or has a
578 non-zero and significant residual or B{C{mod}}
579 is given as C{0}.
581 @see: CPython function U{float_pow<https://GitHub.com/
582 python/cpython/blob/main/Objects/floatobject.c>}.
583 '''
584 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
586 def __isub__(self, other):
587 '''Apply C{B{self} -= B{other}} to this instance.
589 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
590 an iterable of several of the former.
592 @return: This instance, updated (L{Fsum}).
594 @raise TypeError: Invalid B{C{other}} type.
596 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
597 '''
598 try:
599 return self._fsub(other, _isub_op_)
600 except TypeError:
601 return self._facc_inplace(other, _isub_op_, self._facc_neg)
603 def __iter__(self):
604 '''Return an C{iter}ator over a C{partials} duplicate.
605 '''
606 return iter(self.partials)
608 def __itruediv__(self, other, **raiser_RESIDUAL):
609 '''Apply C{B{self} /= B{other}} to this instance.
611 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
612 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
613 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
614 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
616 @return: This instance, updated (L{Fsum}).
618 @raise OverflowError: Partial C{2sum} overflow.
620 @raise ResidualError: Non-zero, significant residual or invalid
621 B{C{RESIDUAL}}.
623 @raise TypeError: Invalid B{C{other}} type.
625 @raise ValueError: Invalid or non-finite B{C{other}}.
627 @raise ZeroDivisionError: Zero B{C{other}}.
629 @see: Method L{Fsum.__ifloordiv__}.
630 '''
631 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
633 def __le__(self, other):
634 '''Compare this with an other instance or C{scalar}.
635 '''
636 return self._cmp_0(other, _le_op_) <= 0
638 def __len__(self):
639 '''Return the number of values accumulated (C{int}).
640 '''
641 return self._n
643 def __lt__(self, other):
644 '''Compare this with an other instance or C{scalar}.
645 '''
646 return self._cmp_0(other, _lt_op_) < 0
648 def __matmul__(self, other): # PYCHOK no cover
649 '''Not implemented.'''
650 return _NotImplemented(self, other)
652 def __mod__(self, other):
653 '''Return C{B{self} % B{other}} as an L{Fsum}.
655 @see: Method L{Fsum.__imod__}.
656 '''
657 f = self._copy_2(self.__mod__)
658 return f._fdivmod2(other, _mod_op_).mod
660 def __mul__(self, other):
661 '''Return C{B{self} * B{other}} as an L{Fsum}.
663 @see: Method L{Fsum.__imul__}.
664 '''
665 f = self._copy_2(self.__mul__)
666 return f._fmul(other, _mul_op_)
668 def __ne__(self, other):
669 '''Compare this with an other instance or C{scalar}.
670 '''
671 return self._cmp_0(other, _ne_op_) != 0
673 def __neg__(self):
674 '''Return I{a copy of} this instance, I{negated}.
675 '''
676 f = self._copy_2(self.__neg__)
677 return f._fset(self._neg)
679 def __pos__(self):
680 '''Return this instance I{as-is}, like C{float.__pos__()}.
681 '''
682 return self if _pos_self else self._copy_2(self.__pos__)
684 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
685 '''Return C{B{self}**B{other}} as an L{Fsum}.
687 @see: Method L{Fsum.__ipow__}.
688 '''
689 f = self._copy_2(self.__pow__)
690 return f._fpow(other, _pow_op_, *mod)
692 def __radd__(self, other):
693 '''Return C{B{other} + B{self}} as an L{Fsum}.
695 @see: Method L{Fsum.__iadd__}.
696 '''
697 f = self._copy_2r(other, self.__radd__)
698 return f._fadd(self, _add_op_)
700 def __rdivmod__(self, other):
701 '''Return C{divmod(B{other}, B{self})} as 2-tuple
702 C{(quotient, remainder)}.
704 @see: Method L{Fsum.__divmod__}.
705 '''
706 f = self._copy_2r(other, self.__rdivmod__)
707 return f._fdivmod2(self, _divmod_op_)
709# def __repr__(self):
710# '''Return the default C{repr(this)}.
711# '''
712# return self.toRepr(lenc=True)
714 def __rfloordiv__(self, other):
715 '''Return C{B{other} // B{self}} as an L{Fsum}.
717 @see: Method L{Fsum.__ifloordiv__}.
718 '''
719 f = self._copy_2r(other, self.__rfloordiv__)
720 return f._floordiv(self, _floordiv_op_)
722 def __rmatmul__(self, other): # PYCHOK no cover
723 '''Not implemented.'''
724 return _NotImplemented(self, other)
726 def __rmod__(self, other):
727 '''Return C{B{other} % B{self}} as an L{Fsum}.
729 @see: Method L{Fsum.__imod__}.
730 '''
731 f = self._copy_2r(other, self.__rmod__)
732 return f._fdivmod2(self, _mod_op_).mod
734 def __rmul__(self, other):
735 '''Return C{B{other} * B{self}} as an L{Fsum}.
737 @see: Method L{Fsum.__imul__}.
738 '''
739 f = self._copy_2r(other, self.__rmul__)
740 return f._fmul(self, _mul_op_)
742 def __round__(self, *ndigits): # PYCHOK Python 3+
743 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
745 @arg ndigits: Optional number of digits (C{int}).
746 '''
747 f = self._copy_2(self.__round__)
748 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
749 return f._fset(round(float(self), *ndigits)) # can be C{int}
751 def __rpow__(self, other, *mod):
752 '''Return C{B{other}**B{self}} as an L{Fsum}.
754 @see: Method L{Fsum.__ipow__}.
755 '''
756 f = self._copy_2r(other, self.__rpow__)
757 return f._fpow(self, _pow_op_, *mod)
759 def __rsub__(self, other):
760 '''Return C{B{other} - B{self}} as L{Fsum}.
762 @see: Method L{Fsum.__isub__}.
763 '''
764 f = self._copy_2r(other, self.__rsub__)
765 return f._fsub(self, _sub_op_)
767 def __rtruediv__(self, other, **raiser_RESIDUAL):
768 '''Return C{B{other} / B{self}} as an L{Fsum}.
770 @see: Method L{Fsum.__itruediv__}.
771 '''
772 f = self._copy_2r(other, self.__rtruediv__)
773 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
775 def __str__(self):
776 '''Return the default C{str(self)}.
777 '''
778 return self.toStr(lenc=True)
780 def __sub__(self, other):
781 '''Return C{B{self} - B{other}} as an L{Fsum}.
783 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
785 @return: The difference (L{Fsum}).
787 @see: Method L{Fsum.__isub__}.
788 '''
789 f = self._copy_2(self.__sub__)
790 return f._fsub(other, _sub_op_)
792 def __truediv__(self, other, **raiser_RESIDUAL):
793 '''Return C{B{self} / B{other}} as an L{Fsum}.
795 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
796 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
797 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
798 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
800 @return: The quotient (L{Fsum}).
802 @raise ResidualError: Non-zero, significant residual or invalid
803 B{C{RESIDUAL}}.
805 @see: Method L{Fsum.__itruediv__}.
806 '''
807 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
809 __trunc__ = __int__
811 if _sys_version_info2 < (3, 0): # PYCHOK no cover
812 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
813 __div__ = __truediv__
814 __idiv__ = __itruediv__
815 __long__ = __int__
816 __nonzero__ = __bool__
817 __rdiv__ = __rtruediv__
819 def as_integer_ratio(self):
820 '''Return this instance as the ratio of 2 integers.
822 @return: 2-Tuple C{(numerator, denominator)} both C{int}
823 with C{numerator} signed and C{denominator}
824 non-zero, positive.
826 @see: Standard C{float.as_integer_ratio} in Python 2.7+.
827 '''
828 n, r = self._fint2
829 if r:
830 i, d = float(r).as_integer_ratio()
831 n *= d
832 n += i
833 else: # PYCHOK no cover
834 d = 1
835 return n, d
837 @property_RO
838 def as_iscalar(self):
839 '''Get this instance I{as-is} (L{Fsum} or C{scalar}), the
840 latter only if the C{residual} equals C{zero}.
841 '''
842 s, r = self._fprs2
843 return self if r else s
845 @property_RO
846 def ceil(self):
847 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
848 C{float} in Python 2-).
850 @note: This C{ceil} takes the C{residual} into account.
852 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
853 L{Fsum.imag} and L{Fsum.real}.
854 '''
855 s, r = self._fprs2
856 c = _ceil(s) + int(r) - 1
857 while r > (c - s): # (s + r) > c
858 c += 1
859 return c # _ceil(self._n_d)
861 cmp = __cmp__
863 def _cmp_0(self, other, op):
864 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
865 '''
866 if _isFsumTuple(other):
867 s = self._ps_1sum(*other._ps)
868 elif self._scalar(other, op):
869 s = self._ps_1sum(other)
870 else:
871 s = self.signOf() # res=True
872 return s
874 def copy(self, deep=False, **name):
875 '''Copy this instance, C{shallow} or B{C{deep}}.
877 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}).
879 @return: The copy (L{Fsum}).
880 '''
881 n = _name__(name, name__=self.copy)
882 f = _Named.copy(self, deep=deep, name=n)
883 if f._ps is self._ps:
884 f._ps = list(self._ps) # separate list
885 if not deep:
886 f._n = 1
887 # assert f._Fsum is f
888 return f
890 def _copy_2(self, which, name=NN):
891 '''(INTERNAL) Copy for I{dyadic} operators.
892 '''
893 n = name or which.__name__ # _dunder_nameof
894 # NOT .classof due to .Fdot(a, *b) args, etc.
895 f = _Named.copy(self, deep=False, name=n)
896 f._ps = list(self._ps) # separate list
897 # assert f._n == self._n
898 # assert f._Fsum is f
899 return f
901 def _copy_2r(self, other, which):
902 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
903 '''
904 return other._copy_2(which) if _isFsum(other) else \
905 self._copy_2(which)._fset(other)
907# def _copy_RESIDUAL(self, other):
908# '''(INTERNAL) Copy C{other._RESIDUAL}.
909# '''
910# R = other._RESIDUAL
911# if R is not Fsum._RESIDUAL:
912# self._RESIDUAL = R
914 divmod = __divmod__
916 def _Error(self, op, other, Error, **txt_cause):
917 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
918 '''
919 return Error(_SPACE_(self.as_iscalar, op, other), **txt_cause)
921 def _ErrorX(self, X, op, other, *mod):
922 '''(INTERNAL) Format the caught exception C{X}.
923 '''
924 E, t = _xError2(X)
925 if mod:
926 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
927 return self._Error(op, other, E, txt=t, cause=X)
929 def _ErrorXs(self, X, xs, **kwds): # in .fmath
930 '''(INTERNAL) Format the caught exception C{X}.
931 '''
932 E, t = _xError2(X)
933 u = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
934 return E(u, txt=t, cause=X)
936 def _facc(self, xs, up=True, **origin_X_x):
937 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s.
938 '''
939 if xs:
940 _xs = _2floats(xs, **origin_X_x) # PYCHOK yield
941 ps = self._ps
942 ps[:] = self._ps_acc(list(ps), _xs, up=up)
943 return self
945 def _facc_1(self, xs, **up):
946 '''(INTERNAL) Accumulate 0, 1 or more C{scalars} or L{Fsum}s,
947 all positional C{xs} in the caller of this method.
948 '''
949 return self._fadd(xs[0], _add_op_, **up) if len(xs) == 1 else \
950 self._facc(xs, origin=1, **up)
952 def _facc_inplace(self, other, op, _facc):
953 '''(INTERNAL) Accumulate from an iterable.
954 '''
955 try:
956 return _facc(other, origin=1) if _xiterable(other) else self
957 except Exception as X:
958 raise self._ErrorX(X, op, other)
960 def _facc_neg(self, xs, **up_origin):
961 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s, negated.
962 '''
963 def _N(X):
964 return X._ps_neg
966 def _n(x):
967 return -float(x)
969 return self._facc(xs, _X=_N, _x=_n, **up_origin)
971 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
972 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
973 '''
974 def _Pow4(p):
975 r = 0
976 if _isFsumTuple(p):
977 s, r = p._fprs2
978 if r:
979 m = Fsum._pow
980 else: # scalar
981 return _Pow4(s)
982 elif isint(p, both=True) and int(p) >= 0:
983 p = s = int(p)
984 m = Fsum._pow_int
985 else:
986 p = s = _2float(power=p)
987 m = Fsum._pow_scalar
988 return m, p, s, r
990 _Pow, p, s, r = _Pow4(power)
991 if p: # and xs:
992 op = which.__name__
993 _flt = float
994 _Fs = Fsum
995 _isa = isinstance
996 _pow = self._pow_2_3
998 def _P(X):
999 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
1000 return f._ps if _isa(f, _Fs) else (f,)
1002 def _p(x):
1003 x = _flt(x)
1004 f = _pow(x, s, power, op, **raiser_RESIDUAL)
1005 if f and r:
1006 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
1007 return f
1009 f = self._facc(xs, origin=1, _X=_P, _x=_p)
1010 else:
1011 f = self._facc_scalar_(float(len(xs))) # x**0 == 1
1012 return f
1014 def _facc_scalar(self, xs, **up):
1015 '''(INTERNAL) Accumulate all C{xs}, known to be scalar.
1016 '''
1017 if xs:
1018 _ = self._ps_acc(self._ps, xs, **up)
1019 return self
1021 def _facc_scalar_(self, *xs, **up):
1022 '''(INTERNAL) Accumulate all positional C{xs}, known to be scalar.
1023 '''
1024 if xs:
1025 _ = self._ps_acc(self._ps, xs, **up)
1026 return self
1028# def _facc_up(self, up=True):
1029# '''(INTERNAL) Update the C{partials}, by removing
1030# and re-accumulating the final C{partial}.
1031# '''
1032# ps = self._ps
1033# while len(ps) > 1:
1034# p = ps.pop()
1035# if p:
1036# n = self._n
1037# _ = self._ps_acc(ps, (p,), up=False)
1038# self._n = n
1039# break
1040# return self._update() if up else self
1042 def fadd(self, xs=()):
1043 '''Add an iterable's items to this instance.
1045 @arg xs: Iterable of items to add (each C{scalar}
1046 or an L{Fsum} or L{Fsum2Tuple} instance).
1048 @return: This instance (L{Fsum}).
1050 @raise OverflowError: Partial C{2sum} overflow.
1052 @raise TypeError: An invalid B{C{xs}} item.
1054 @raise ValueError: Invalid or non-finite B{C{xs}} value.
1055 '''
1056 if _isFsumTuple(xs):
1057 self._facc_scalar(xs._ps)
1058 elif isscalar(xs): # for backward compatibility
1059 self._facc_scalar_(_2float(x=xs)) # PYCHOK no cover
1060 elif xs: # _xiterable(xs)
1061 self._facc(xs)
1062 return self
1064 def fadd_(self, *xs):
1065 '''Add all positional items to this instance.
1067 @arg xs: Values to add (each C{scalar} or an L{Fsum}
1068 or L{Fsum2Tuple} instance), all positional.
1070 @see: Method L{Fsum.fadd} for further details.
1071 '''
1072 return self._facc_1(xs)
1074 def _fadd(self, other, op, **up): # in .fmath.Fhorner
1075 '''(INTERNAL) Apply C{B{self} += B{other}}.
1076 '''
1077 if not self._ps: # new Fsum(x)
1078 self._fset(other, op=op, **up)
1079 elif _isFsumTuple(other):
1080 self._facc_scalar(other._ps, **up)
1081 elif self._scalar(other, op):
1082 self._facc_scalar_(other, **up)
1083 return self
1085 fcopy = copy # for backward compatibility
1086 fdiv = __itruediv__
1087 fdivmod = __divmod__
1089 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1090 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1091 '''
1092 # result mostly follows CPython function U{float_divmod
1093 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1094 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1095 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1096 if q: # == float // other == floor(float / other)
1097 self -= Fsum(q) * other # NOT other * q!
1099 s = signOf(other) # make signOf(self) == signOf(other)
1100 if s and self.signOf() == -s: # PYCHOK no cover
1101 self += other
1102 q -= 1
1103# t = self.signOf()
1104# if t and t != s:
1105# raise self._Error(op, other, _AssertionError, txt__=signOf)
1106 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1108 def _finite(self, other, op=None):
1109 '''(INTERNAL) Return B{C{other}} if C{finite}.
1110 '''
1111 if _isfinite(other):
1112 return other
1113 raise ValueError(_not_finite_) if op is None else \
1114 self._Error(op, other, _ValueError, txt=_not_finite_)
1116 def fint(self, name=NN, **raiser_RESIDUAL):
1117 '''Return this instance' current running sum as C{integer}.
1119 @kwarg name: Optional, overriding C{B{name}="fint"} (C{str}).
1120 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1121 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1122 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1124 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1125 with a zero or insignificant I{integer} residual.
1127 @raise ResidualError: Non-zero, significant residual or invalid
1128 B{C{RESIDUAL}}.
1130 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1131 '''
1132 i, r = self._fint2
1133 if r:
1134 R = self._raiser(r, i, **raiser_RESIDUAL)
1135 if R:
1136 t = _stresidual(_integer_, r, **R)
1137 raise ResidualError(_integer_, i, txt=t)
1138 return _Psum_(i, name=_name__(name, name__=self.fint))
1140 def fint2(self, **name):
1141 '''Return this instance' current running sum as C{int} and the
1142 I{integer} residual.
1144 @kwarg name: Optional name (C{str}).
1146 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1147 an C{int} and I{integer} C{residual} a C{float} or
1148 C{INT0} if the C{fsum} is considered to be I{exact}.
1149 '''
1150 return Fsum2Tuple(*self._fint2, **name)
1152 @Property_RO
1153 def _fint2(self): # see ._fset
1154 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1155 '''
1156 s, r = self._fprs2
1157 i = int(s)
1158 n = len(self._ps)
1159 r = self._ps_1sum(i) if r and n > 1 else float(s - i)
1160 return i, (r or INT0) # Fsum2Tuple?
1162 @deprecated_property_RO
1163 def float_int(self): # PYCHOK no cover
1164 '''DEPRECATED, use method C{Fsum.int_float}.'''
1165 return self.int_float() # raiser=False
1167 @property_RO
1168 def floor(self):
1169 '''Get this instance' C{floor} (C{int} in Python 3+, but
1170 C{float} in Python 2-).
1172 @note: This C{floor} takes the C{residual} into account.
1174 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1175 L{Fsum.imag} and L{Fsum.real}.
1176 '''
1177 s, r = self._fprs2
1178 f = _floor(s) + _floor(r) + 1
1179 while (f - s) > r: # f > (s + r)
1180 f -= 1
1181 return f # _floor(self._n_d)
1183# ffloordiv = __ifloordiv__ # for naming consistency
1184# floordiv = __floordiv__ # for naming consistency
1186 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1187 '''Apply C{B{self} //= B{other}}.
1188 '''
1189 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1190 return self._fset(q.floor) # floor(q)
1192 fmul = __imul__
1194 def _fmul(self, other, op):
1195 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1196 '''
1197 if _isFsumTuple(other):
1198 if len(self._ps) != 1:
1199 f = self._mul_Fsum(other, op)
1200 elif len(other._ps) != 1: # and len(self._ps) == 1
1201 f = other._mul_scalar(self._ps[0], op)
1202 else: # len(other._ps) == len(self._ps) == 1
1203 f = self._finite(self._ps[0] * other._ps[0])
1204 else:
1205 s = self._scalar(other, op)
1206 f = self._mul_scalar(s, op)
1207 return self._fset(f) # n=len(self) + 1
1209 def fover(self, over, **raiser_RESIDUAL):
1210 '''Apply C{B{self} /= B{over}} and summate.
1212 @arg over: An L{Fsum} or C{scalar} denominator.
1213 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1214 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1215 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1217 @return: Precision running sum (C{float}).
1219 @raise ResidualError: Non-zero, significant residual or invalid
1220 B{C{RESIDUAL}}.
1222 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1223 '''
1224 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1226 fpow = __ipow__
1228 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1229 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1230 '''
1231 if mod:
1232 if mod[0] is not None: # == 3-arg C{pow}
1233 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1234 elif self.is_integer():
1235 # return an exact C{int} for C{int}**C{int}
1236 i, _ = self._fint2 # assert _ == 0
1237 x, r = _2scalar2(other) # C{int}, C{float} or other
1238 f = _Psum_(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1239 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1240 else: # mod[0] is None, power(self, other)
1241 f = self._pow(other, other, op, **raiser_RESIDUAL)
1242 else: # pow(self, other)
1243 f = self._pow(other, other, op, **raiser_RESIDUAL)
1244 return self._fset(f) # n=max(len(self), 1)
1246 @Property_RO
1247 def _fprs(self):
1248 '''(INTERNAL) Get and cache this instance' precision
1249 running sum (C{float} or C{int}), ignoring C{residual}.
1251 @note: The precision running C{fsum} after a C{//=} or
1252 C{//} C{floor} division is C{int} in Python 3+.
1253 '''
1254 s, _ = self._fprs2
1255 return s # ._fprs2.fsum
1257 @Property_RO
1258 def _fprs2(self):
1259 '''(INTERNAL) Get and cache this instance' precision
1260 running sum and residual (L{Fsum2Tuple}).
1261 '''
1262 ps = self._ps
1263 n = len(ps) - 2
1264 if n > 0: # len(ps) > 2
1265 s = _psum(ps)
1266 n = len(ps) - 2
1267 if n > 0:
1268 r = self._ps_1sum(s)
1269 return Fsum2Tuple(*_s_r(s, r))
1270 if n == 0: # len(ps) == 2
1271 s, r = _s_r(*_2sum(*ps))
1272 ps[:] = (r, s) if r else (s,)
1273 elif ps: # len(ps) == 1
1274 s, r = ps[0], INT0
1275 else: # len(ps) == 0
1276 s, r = _0_0, INT0
1277 ps[:] = s,
1278 # assert self._ps is ps
1279 return Fsum2Tuple(s, r)
1281 def fset_(self, *xs):
1282 '''Replace this instance' value with all positional items.
1284 @arg xs: Optional, new values (each C{scalar} or
1285 an L{Fsum} or L{Fsum2Tuple} instance),
1286 all positional.
1288 @return: This instance, replaced (C{Fsum}).
1290 @see: Method L{Fsum.fadd} for further details.
1291 '''
1292 f = xs[0] if len(xs) == 1 else (
1293 Fsum(*xs) if xs else _0_0)
1294 return self._fset(f)
1296 def _fset(self, other, n=0, up=True, **op):
1297 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1298 '''
1299 if other is self:
1300 pass # from ._fmul, ._ftruediv and ._pow_0_1
1301 elif _isFsumTuple(other):
1302 self._ps[:] = other._ps
1303 self._n = n or other._n
1304# self._copy_RESIDUAL(other)
1305 if up: # use or zap the C{Property_RO} values
1306 Fsum._fint2._update_from(self, other)
1307 Fsum._fprs ._update_from(self, other)
1308 Fsum._fprs2._update_from(self, other)
1309 elif isscalar(other):
1310 s = float(self._finite(other, **op)) if op else other
1311 self._ps[:] = s,
1312 self._n = n or 1
1313 if up:
1314 i = int(s) # see ._fint2
1315 t = i, ((s - i) or INT0)
1316 # Property_ROs _fint2, _fprs and _fprs2 can't be a Property:
1317 # Property's _fset zaps the value just set by the @setter
1318 self.__dict__.update(_fint2=t, _fprs=s, _fprs2=Fsum2Tuple(s, INT0))
1319 else: # PYCHOK no cover
1320 op = _xkwds_get(op, op=_fset_op_)
1321 raise self._Error(op, other, _TypeError)
1322 return self
1324 def _fset_ps(self, other, n=0): # in .fmath
1325 '''(INTERNAL) Set partials from a known C{scalar}, L{Fsum} or L{Fsum2Tuple}.
1326 '''
1327 if _isFsumTuple(other):
1328 self._ps[:] = other._ps
1329 self._n = n or other._n
1330 else: # assert isscalar(other)
1331 self._ps[:] = other,
1332 self._n = n or 1
1333 return self
1335 def fsub(self, xs=()):
1336 '''Subtract an iterable's items from this instance.
1338 @see: Method L{Fsum.fadd} for further details.
1339 '''
1340 return self._facc_neg(xs)
1342 def fsub_(self, *xs):
1343 '''Subtract all positional items from this instance.
1345 @see: Method L{Fsum.fadd_} for further details.
1346 '''
1347 return self._fsub(xs[0], _sub_op_) if len(xs) == 1 else \
1348 self._facc_neg(xs, origin=1)
1350 def _fsub(self, other, op):
1351 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1352 '''
1353 if _isFsumTuple(other):
1354 if other is self: # or other._fprs2 == self._fprs2:
1355 self._fset(_0_0, n=len(self) * 2)
1356 elif other._ps:
1357 self._facc_scalar(other._ps_neg)
1358 elif self._scalar(other, op):
1359 self._facc_scalar_(-other)
1360 return self
1362 def fsum(self, xs=()):
1363 '''Add an iterable's items, summate and return the
1364 current precision running sum.
1366 @arg xs: Iterable of items to add (each item C{scalar}
1367 or an L{Fsum} or L{Fsum2Tuple} instance).
1369 @return: Precision running sum (C{float} or C{int}).
1371 @see: Method L{Fsum.fadd}.
1373 @note: Accumulation can continue after summation.
1374 '''
1375 return self._facc(xs)._fprs
1377 def fsum_(self, *xs):
1378 '''Add any positional items, summate and return the
1379 current precision running sum.
1381 @arg xs: Items to add (each C{scalar} or an L{Fsum}
1382 or L{Fsum2Tuple} instance), all positional.
1384 @return: Precision running sum (C{float} or C{int}).
1386 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1387 '''
1388 return self._facc_1(xs)._fprs
1390 @property_RO
1391 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, for C{_2floats}, .fstats
1392 return self # NOT @Property_RO, see .copy and ._copy_2
1394 def Fsum_(self, *xs, **name):
1395 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1397 @kwarg name: Optional name (C{str}).
1399 @return: Copy of this updated instance (L{Fsum}).
1400 '''
1401 return self._facc_1(xs)._copy_2(self.Fsum_, **name)
1403 def Fsum2Tuple_(self, *xs, **name):
1404 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1406 @kwarg name: Optional name (C{str}).
1408 @return: Precision running sum (L{Fsum2Tuple}).
1409 '''
1410 return Fsum2Tuple(self._facc_1(xs)._fprs2, **name)
1412 def fsum2(self, xs=(), **name):
1413 '''Add an iterable's items, summate and return the
1414 current precision running sum I{and} the C{residual}.
1416 @arg xs: Iterable of items to add (each item C{scalar}
1417 or an L{Fsum} or L{Fsum2Tuple} instance).
1418 @kwarg name: Optional C{B{name}=NN} (C{str}).
1420 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1421 current precision running sum and C{residual}, the
1422 (precision) sum of the remaining C{partials}. The
1423 C{residual is INT0} if the C{fsum} is considered
1424 to be I{exact}.
1426 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1427 '''
1428 t = self._facc(xs)._fprs2
1429 return t.dup(name=name) if name else t
1431 def fsum2_(self, *xs):
1432 '''Add any positional items, summate and return the current
1433 precision running sum and the I{differential}.
1435 @arg xs: Values to add (each C{scalar} or an L{Fsum} or
1436 L{Fsum2Tuple} instance), all positional.
1438 @return: 2Tuple C{(fsum, delta)} with the current, precision
1439 running C{fsum} like method L{Fsum.fsum} and C{delta},
1440 the difference with previous running C{fsum}, C{float}.
1442 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1443 '''
1444 return self._fsum2(xs, self._facc_1)
1446 def _fsum2(self, xs, _facc, **origin):
1447 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1448 '''
1449 p, q = self._fprs2
1450 if xs:
1451 s, r = _facc(xs, **origin)._fprs2
1452 return s, _2delta(s - p, r - q) # _fsum(_1primed((s, -p, r, -q))
1453 else:
1454 return p, _0_0
1456 def fsumf_(self, *xs):
1457 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1458 '''
1459 return self._facc_scalar(xs)._fprs
1461 def Fsumf_(self, *xs):
1462 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1463 '''
1464 return self._facc_scalar(xs)._copy_2(self.Fsumf_)
1466 def fsum2f_(self, *xs):
1467 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}} are I{known to be scalar}.
1468 '''
1469 return self._fsum2(xs, self._facc_scalar, origin=1)
1471# ftruediv = __itruediv__ # for naming consistency?
1473 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1474 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1475 '''
1476 n = _1_0
1477 if _isFsumTuple(other):
1478 if other is self or self == other:
1479 return self._fset(n, n=len(self))
1480 d, r = other._fprs2
1481 if r:
1482 R = self._raiser(r, d, **raiser_RESIDUAL)
1483 if R:
1484 raise self._ResidualError(op, other, r, **R)
1485 d, n = other.as_integer_ratio()
1486 else:
1487 d = self._scalar(other, op)
1488 try:
1489 s = n / d
1490 except Exception as X:
1491 raise self._ErrorX(X, op, other)
1492 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1493 return self._fset(f)
1495 @property_RO
1496 def imag(self):
1497 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1499 @see: Property L{Fsum.real}.
1500 '''
1501 return _0_0
1503 def int_float(self, **raiser_RESIDUAL):
1504 '''Return this instance' current running sum as C{int} or C{float}.
1506 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1507 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1508 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1510 @return: This C{integer} sum if this instance C{is_integer},
1511 otherwise return the C{float} sum if the residual is
1512 zero or not significant.
1514 @raise ResidualError: Non-zero, significant residual or invalid
1515 B{C{RESIDUAL}}.
1517 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.RESIDUAL} and
1518 property L{Fsum.as_iscalar}.
1519 '''
1520 s, r = self._fint2
1521 if r:
1522 s, r = self._fprs2
1523 if r: # PYCHOK no cover
1524 R = self._raiser(r, s, **raiser_RESIDUAL)
1525 if R:
1526 t = _stresidual(_non_zero_, r, **R)
1527 raise ResidualError(int_float=s, txt=t)
1528 s = float(s)
1529 return s
1531 def is_exact(self):
1532 '''Is this instance' running C{fsum} considered to be exact?
1533 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1534 '''
1535 return self.residual is INT0
1537 def is_integer(self):
1538 '''Is this instance' running sum C{integer}? (C{bool}).
1540 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1541 '''
1542 _, r = self._fint2
1543 return False if r else True
1545 def is_math_fsum(self):
1546 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and
1547 L{fsum1_} plus partials summation are based on Python's
1548 C{math.fsum} or not.
1550 @return: C{2} if all functions and partials summation
1551 are based on C{math.fsum}, C{True} if only
1552 the functions are based on C{math.fsum} (and
1553 partials summation is not) or C{False} if
1554 none are.
1555 '''
1556 f = Fsum._math_fsum
1557 return 2 if _psum is f else bool(f)
1559 def is_scalar(self, **raiser_RESIDUAL):
1560 '''Is this instance' running sum C{scalar} without residual or with
1561 a residual I{ratio} not exceeding the RESIDUAL threshold?
1563 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1564 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1565 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1567 @return: C{True} if this instance' non-zero residual C{ratio} exceeds
1568 the L{RESIDUAL<Fsum.RESIDUAL>} threshold (C{bool}).
1570 @raise ResidualError: Non-zero, significant residual or invalid
1571 B{C{RESIDUAL}}.
1573 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property
1574 L{Fsum.as_iscalar}.
1575 '''
1576 s, r = self._fprs2
1577 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1579 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1580 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1581 '''
1582 # assert _isFsumTuple(other)
1583 if self._ps and other._ps:
1584 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
1585 else:
1586 f = _0_0
1587 return f
1589 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1590 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
1591 '''
1592 # assert isscalar(factor)
1593 if self._ps and self._finite(factor, op):
1594 f = self if factor == _1_0 else (
1595 self._neg if factor == _N_1_0 else
1596 self._ps_mul(op, factor).as_iscalar)
1597 else:
1598 f = _0_0
1599 return f
1601# @property_RO
1602# def _n_d(self):
1603# n, d = self.as_integer_ratio()
1604# return n / d
1606 @property_RO
1607 def _neg(self):
1608 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
1609 '''
1610 return _Psum(self._ps_neg) if self._ps else NEG0
1612 @property_RO
1613 def partials(self):
1614 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
1615 '''
1616 return tuple(self._ps)
1618 def pow(self, x, *mod, **raiser_RESIDUAL):
1619 '''Return C{B{self}**B{x}} as L{Fsum}.
1621 @arg x: The exponent (C{scalar} or L{Fsum}).
1622 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
1623 C{pow(B{self}, B{other}, B{mod})} version.
1624 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1625 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1626 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1628 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
1629 result (L{Fsum}).
1631 @raise ResidualError: Non-zero, significant residual or invalid
1632 B{C{RESIDUAL}}.
1634 @note: If B{C{mod}} is given as C{None}, the result will be an
1635 C{integer} L{Fsum} provided this instance C{is_integer}
1636 or set to C{integer} by an L{Fsum.fint} call.
1638 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
1639 and L{Fsum.root}.
1640 '''
1641 f = self._copy_2(self.pow)
1642 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
1644 def _pow(self, other, unused, op, **raiser_RESIDUAL):
1645 '''Return C{B{self} ** B{other}}.
1646 '''
1647 if _isFsumTuple(other):
1648 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
1649 elif self._scalar(other, op):
1650 x = self._finite(other, op)
1651 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1652 else:
1653 f = self._pow_0_1(0, other)
1654 return f
1656 def _pow_0_1(self, x, other):
1657 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
1658 '''
1659 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
1661 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
1662 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
1663 B{x}, int B{mod} or C{None})}, embellishing errors.
1664 '''
1666 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
1667 m = mod[0]
1668 # assert _isFsumTuple(b)
1670 def _s(s, r):
1671 R = self._raiser(r, s, **raiser_RESIDUAL)
1672 if R:
1673 raise self._ResidualError(op, other, r, mod=m, **R)
1674 return s
1676 b = _s(*(b._fprs2 if m is None else b._fint2))
1677 x = _s(*_2scalar2(x))
1679 try:
1680 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
1681 s = pow(b, x, *mod)
1682 if iscomplex(s):
1683 # neg**frac == complex in Python 3+, but ValueError in 2-
1684 raise ValueError(_strcomplex(s, b, x, *mod))
1685 return self._finite(s)
1686 except Exception as X:
1687 raise self._ErrorX(X, op, other, *mod)
1689 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
1690 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsumTuple(other)}.
1691 '''
1692 # assert _isFsumTuple(other)
1693 x, r = other._fprs2
1694 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1695 if f and r:
1696 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
1697 return f
1699 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
1700 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
1701 '''
1702 # assert isint(x) and x >= 0
1703 ps = self._ps
1704 if len(ps) > 1:
1705 _mul_Fsum = Fsum._mul_Fsum
1706 if x > 4:
1707 p = self
1708 f = self if (x & 1) else _Psum_(_1_0)
1709 m = x >> 1 # // 2
1710 while m:
1711 p = _mul_Fsum(p, p, op) # p **= 2
1712 if (m & 1):
1713 f = _mul_Fsum(f, p, op) # f *= p
1714 m >>= 1 # //= 2
1715 elif x > 1: # self**2, 3, or 4
1716 f = _mul_Fsum(self, self, op)
1717 if x > 2: # self**3 or 4
1718 p = self if x < 4 else f
1719 f = _mul_Fsum(f, p, op)
1720 else: # self**1 or self**0 == 1 or _1_0
1721 f = self._pow_0_1(x, other)
1722 elif ps: # self._ps[0]**x
1723 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
1724 else: # PYCHOK no cover
1725 # 0**pos_int == 0, but 0**0 == 1
1726 f = 0 if x else 1
1727 return f
1729 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
1730 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
1731 '''
1732 s, r = self._fprs2
1733 if r:
1734 # assert s != 0
1735 if isint(x, both=True): # self**int
1736 x = int(x)
1737 y = abs(x)
1738 if y > 1:
1739 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
1740 if x > 0: # i.e. > 1
1741 return f # Fsum or scalar
1742 # assert x < 0 # i.e. < -1
1743 if _isFsum(f):
1744 s, r = f._fprs2
1745 if r:
1746 return _1_Over(f, op, **raiser_RESIDUAL)
1747 else: # scalar
1748 s = f
1749 # use s**(-1) to get the CPython
1750 # float_pow error iff s is zero
1751 x = -1
1752 elif x < 0: # self**(-1)
1753 return _1_Over(self, op, **raiser_RESIDUAL) # 1 / self
1754 else: # self**1 or self**0
1755 return self._pow_0_1(x, other) # self, 1 or 1.0
1756 else: # self**fractional
1757 R = self._raiser(r, s, **raiser_RESIDUAL)
1758 if R:
1759 raise self._ResidualError(op, other, r, **R)
1760 n, d = self.as_integer_ratio()
1761 if abs(n) > abs(d):
1762 n, d, x = d, n, (-x)
1763 s = n / d
1764 # assert isscalar(s) and isscalar(x)
1765 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
1767 def _ps_acc(self, ps, xs, up=True, **unused):
1768 '''(INTERNAL) Accumulate C{xs} scalars into list C{ps}.
1769 '''
1770 n = 0
1771 _2s = _2sum
1772 for x in (tuple(xs) if xs is ps else xs):
1773 # assert isscalar(x) and _isfinite(x)
1774 if x:
1775 i = 0
1776 for p in ps:
1777 x, p = _2s(x, p)
1778 if p:
1779 ps[i] = p
1780 i += 1
1781 ps[i:] = (x,) if x else ()
1782 n += 1
1783 if n:
1784 self._n += n
1785 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
1786 if up:
1787 self._update()
1788 return ps
1790 def _ps_mul(self, op, *factors):
1791 '''(INTERNAL) Multiply this instance' C{partials} with
1792 each scalar C{factor} and accumulate into an C{Fsum}.
1793 '''
1794 def _pfs(ps, fs):
1795 if len(ps) < len(fs):
1796 ps, fs = fs, ps
1797 _fin = _isfinite
1798 for f in fs:
1799 for p in ps:
1800 p *= f
1801 yield p if _fin(p) else self._finite(p, op)
1803 return Fsum()._facc_scalar(_pfs(self._ps, factors), up=False)
1805 @property_RO
1806 def _ps_neg(self):
1807 '''(INTERNAL) Yield the partials, I{negated}.
1808 '''
1809 for p in self._ps:
1810 yield -p
1812 def _ps_1sum(self, *less):
1813 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
1814 '''
1815 def _1pls(ps, ls):
1816 yield _1_0
1817 for p in ps:
1818 yield p
1819 for p in ls:
1820 yield -p
1821 yield _N_1_0
1823 return _fsum(_1pls(self._ps, less))
1825 def _raiser(self, r, s, raiser=True, **RESIDUAL):
1826 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
1827 I{and} is residual C{r} I{non-zero} or I{significant} (for a
1828 negative respectively positive C{RESIDUAL} threshold)?
1829 '''
1830 if r and raiser:
1831 t = self._RESIDUAL
1832 if RESIDUAL:
1833 t = _threshold(t, **RESIDUAL)
1834 if t < 0 or (s + r) != s:
1835 q = (r / s) if s else s # == 0.
1836 if fabs(q) > fabs(t):
1837 return dict(ratio=q, R=t)
1838 return {}
1840 rdiv = __rtruediv__
1842 @property_RO
1843 def real(self):
1844 '''Get the C{real} part of this instance (C{float}).
1846 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
1847 and properties L{Fsum.ceil}, L{Fsum.floor},
1848 L{Fsum.imag} and L{Fsum.residual}.
1849 '''
1850 return float(self._fprs)
1852 @property_RO
1853 def residual(self):
1854 '''Get this instance' residual (C{float} or C{int}): the
1855 C{sum(partials)} less the precision running sum C{fsum}.
1857 @note: The C{residual is INT0} iff the precision running
1858 C{fsum} is considered to be I{exact}.
1860 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
1861 '''
1862 return self._fprs2.residual
1864 def RESIDUAL(self, *threshold):
1865 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
1866 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
1868 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
1869 L{ResidualError}s in division and exponention, if
1870 C{None} restore the default set with env variable
1871 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
1872 current setting.
1874 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
1876 @raise ResidualError: Invalid B{C{threshold}}.
1878 @note: L{ResidualError}s may be thrown if the non-zero I{ratio}
1879 C{residual / fsum} exceeds the given B{C{threshold}} and
1880 if the C{residual} is non-zero and I{significant} vs the
1881 C{fsum}, i.e. C{(fsum + residual) != fsum} and if optional
1882 keyword argument C{raiser=False} is missing. Specify a
1883 negative B{C{threshold}} for only non-zero C{residual}
1884 testing without I{significant}.
1885 '''
1886 r = self._RESIDUAL
1887 if threshold:
1888 t = threshold[0]
1889 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
1890 (_0_0 if t else _1_0) if isbool(t) else
1891 _threshold(t)) # ... backward compatibility
1892 return r
1894 def _ResidualError(self, op, other, residual, **mod_R):
1895 '''(INTERNAL) Non-zero B{C{residual}} etc.
1896 '''
1897 def _p(mod=None, R=0, **unused): # ratio=0
1898 return (_non_zero_ if R < 0 else _significant_) \
1899 if mod is None else _integer_
1901 t = _stresidual(_p(**mod_R), residual, **mod_R)
1902 return self._Error(op, other, ResidualError, txt=t)
1904 def root(self, root, **raiser_RESIDUAL):
1905 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
1907 @arg root: The order (C{scalar} or L{Fsum}), non-zero.
1908 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1909 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1910 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1912 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
1914 @raise ResidualError: Non-zero, significant residual or invalid
1915 B{C{RESIDUAL}}.
1917 @see: Method L{Fsum.pow}.
1918 '''
1919 x = _1_Over(root, _truediv_op_, **raiser_RESIDUAL)
1920 f = self._copy_2(self.root)
1921 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
1923 def _scalar(self, other, op, **txt):
1924 '''(INTERNAL) Return scalar C{other}.
1925 '''
1926 if isscalar(other):
1927 return other
1928 raise self._Error(op, other, _TypeError, **txt) # _invalid_
1930 def signOf(self, res=True):
1931 '''Determine the sign of this instance.
1933 @kwarg res: If C{True} consider, otherwise
1934 ignore the residual (C{bool}).
1936 @return: The sign (C{int}, -1, 0 or +1).
1937 '''
1938 s, r = self._fprs2
1939 r = (-r) if res else 0
1940 return _signOf(s, r)
1942 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
1943 '''Return this C{Fsum} instance as representation.
1945 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
1946 for method L{Fsum.toStr}.
1948 @return: This instance (C{repr}).
1949 '''
1950 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
1952 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
1953 '''Return this C{Fsum} instance as string.
1955 @kwarg lenc: If C{True} include the current C{[len]} of this
1956 L{Fsum} enclosed in I{[brackets]} (C{bool}).
1957 @kwarg prec_sep_fmt: Optional keyword arguments for method
1958 L{Fsum2Tuple.toStr}.
1960 @return: This instance (C{str}).
1961 '''
1962 p = self.classname
1963 if lenc:
1964 p = Fmt.SQUARE(p, len(self))
1965 n = _enquote(self.name, white=_UNDER_)
1966 t = self._fprs2.toStr(**prec_sep_fmt)
1967 return NN(p, _SPACE_, n, t)
1969 def _truediv(self, other, op, **raiser_RESIDUAL):
1970 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
1971 '''
1972 f = self._copy_2(self.__truediv__)
1973 return f._ftruediv(other, op, **raiser_RESIDUAL)
1975 def _update(self, updated=True): # see ._fset
1976 '''(INTERNAL) Zap all cached C{Property_RO} values.
1977 '''
1978 if updated:
1979 _pop = self.__dict__.pop
1980 for p in _ROs:
1981 _ = _pop(p, None)
1982# Fsum._fint2._update(self)
1983# Fsum._fprs ._update(self)
1984# Fsum._fprs2._update(self)
1985 return self # for .fset_
1987_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
1990def _Float_Int(arg, **name_Error):
1991 '''(INTERNAL) Unit of L{Fsum2Tuple} items.
1992 '''
1993 U = Int if isint(arg) else Float
1994 return U(arg, **name_Error)
1997class DivMod2Tuple(_NamedTuple):
1998 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
1999 C{mod} results of a C{divmod} operation.
2001 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2002 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2003 '''
2004 _Names_ = (_div_, _mod_)
2005 _Units_ = (_Float_Int, Fsum)
2008class Fsum2Tuple(_NamedTuple): # in .fstats
2009 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2010 and the C{residual}, the sum of the remaining partials. Each
2011 item is C{float} or C{int}.
2013 @note: If the C{residual is INT0}, the C{fsum} is considered
2014 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2015 '''
2016 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2017 _Units_ = (_Float_Int, _Float_Int)
2019 def __abs__(self): # in .fmath
2020 return self._Fsum.__abs__()
2022 def __bool__(self): # PYCHOK Python 3+
2023 return bool(self._Fsum)
2025 def __eq__(self, other):
2026 return self._other_op(other, self.__eq__)
2028 def __float__(self):
2029 return self._Fsum.__float__()
2031 def __ge__(self, other):
2032 return self._other_op(other, self.__ge__)
2034 def __gt__(self, other):
2035 return self._other_op(other, self.__gt__)
2037 def __le__(self, other):
2038 return self._other_op(other, self.__le__)
2040 def __lt__(self, other):
2041 return self._other_op(other, self.__lt__)
2043 def __int__(self):
2044 return self._Fsum.__int__()
2046 def __ne__(self, other):
2047 return self._other_op(other, self.__ne__)
2049 def __neg__(self):
2050 return self._Fsum.__neg__()
2052 __nonzero__ = __bool__ # Python 2-
2054 def __pos__(self):
2055 return self._Fsum.__pos__()
2057 def as_integer_ratio(self):
2058 '''Return this instance as the ratio of 2 integers.
2060 @see: Method L{Fsum.as_integer_ratio} for further details.
2061 '''
2062 return self._Fsum.as_integer_ratio()
2064 @property_RO
2065 def _fint2(self):
2066 return self._Fsum._fint2
2068 @property_RO
2069 def _fprs2(self):
2070 return self._Fsum._fprs2
2072 @Property_RO
2073 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2074 s, r = _s_r(*self)
2075 ps = (r, s) if r else (s,)
2076 return _Psum(ps, name=self.name)
2078 def Fsum_(self, *xs, **name_RESIDUAL):
2079 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2080 '''
2081 f = _Psum(self._Fsum._ps, **name_RESIDUAL)
2082 return f._facc_1(xs, up=False) if xs else f
2084 def is_exact(self):
2085 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2086 '''
2087 return self._Fsum.is_exact()
2089 def is_integer(self):
2090 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2091 '''
2092 return self._Fsum.is_integer()
2094 def _mul_scalar(self, other, op): # for Fsum._fmul
2095 return self._Fsum._mul_scalar(other, op)
2097 @property_RO
2098 def _n(self):
2099 return self._Fsum._n
2101 def _other_op(self, other, which):
2102 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2103 return getattr(C, which.__name__)(s, other)
2105 @property_RO
2106 def _ps(self):
2107 return self._Fsum._ps
2109 @property_RO
2110 def _ps_neg(self):
2111 return self._Fsum._ps_neg
2113 def signOf(self, **res):
2114 '''Like method L{Fsum.signOf}.
2115 '''
2116 return self._Fsum.signOf(**res)
2118 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2119 '''Return this L{Fsum2Tuple} as string (C{str}).
2121 @kwarg fmt: Optional C{float} format (C{letter}).
2122 @kwarg prec_sep: Optional keyword arguments for function
2123 L{fstr<streprs.fstr>}.
2124 '''
2125 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2127_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2130class ResidualError(_ValueError):
2131 '''Error raised for a division, power or root operation of
2132 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2133 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2135 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2136 '''
2137 pass
2140try:
2141 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2143 # make sure _fsum works as expected (XXX check
2144 # float.__getformat__('float')[:4] == 'IEEE'?)
2145 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2146 del _fsum # nope, remove _fsum ...
2147 raise ImportError # ... use _fsum below
2149 Fsum._math_fsum = _sum = _fsum # PYCHOK exported
2150except ImportError:
2151 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic
2153 def _fsum(xs):
2154 '''(INTERNAL) Precision summation, Python 2.5-.
2155 '''
2156 F = Fsum()
2157 F.name = _fsum.__name__
2158 return F._facc(xs, up=False)._fprs2.fsum
2161def fsum(xs, floats=False):
2162 '''Precision floating point summation based on/like Python's C{math.fsum}.
2164 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2165 instance).
2166 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2167 be scalar} (C{bool}).
2169 @return: Precision C{fsum} (C{float}).
2171 @raise OverflowError: Partial C{2sum} overflow.
2173 @raise TypeError: Non-scalar B{C{xs}} item.
2175 @raise ValueError: Invalid or non-finite B{C{xs}} item.
2177 @note: Exception and I{non-finite} handling may differ if not based
2178 on Python's C{math.fsum}.
2180 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.
2181 '''
2182 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield
2185def fsum_(*xs, **floats):
2186 '''Precision floating point summation of all positional items.
2188 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2189 all positional.
2190 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2191 be scalar} (C{bool}).
2193 @see: Function L{fsum<fsums.fsum>} for further details.
2194 '''
2195 return _fsum(xs if _xkwds_get(floats, floats=False) is True else
2196 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield
2199def fsumf_(*xs):
2200 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2202 @see: Function L{fsum_<fsums.fsum_>} for further details.
2203 '''
2204 return _fsum(xs) if xs else _0_0
2207def fsum1(xs, floats=False):
2208 '''Precision floating point summation, 1-primed.
2210 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2211 instance).
2212 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2213 be scalar} (C{bool}).
2215 @see: Function L{fsum<fsums.fsum>} for further details.
2216 '''
2217 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield
2220def fsum1_(*xs, **floats):
2221 '''Precision floating point summation, 1-primed of all positional items.
2223 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2224 all positional.
2225 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2226 be scalar} (C{bool}).
2228 @see: Function L{fsum_<fsums.fsum_>} for further details.
2229 '''
2230 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) is True else
2231 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield
2234def fsum1f_(*xs):
2235 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2237 @see: Function L{fsum_<fsums.fsum_>} for further details.
2238 '''
2239 return _fsum(_1primed(xs)) if xs else _0_0
2242if __name__ == '__main__':
2244 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums
2246 if _getenv(_psum.__name__, NN) == _fsum.__name__:
2247 _psum = _fsum
2249 def _test(n):
2250 # copied from Hettinger, see L{Fsum} reference
2251 from pygeodesy import frandoms, printf
2253 printf(_fsum.__name__, end=_COMMASPACE_)
2254 printf(_psum.__name__, end=_COMMASPACE_)
2256 F = Fsum()
2257 if F.is_math_fsum():
2258 for t in frandoms(n, seeded=True):
2259 assert float(F.fset_(*t)) == _fsum(t)
2260 printf(_DOT_, end=NN)
2261 printf(NN)
2263 _test(128)
2265# **) MIT License
2266#
2267# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
2268#
2269# Permission is hereby granted, free of charge, to any person obtaining a
2270# copy of this software and associated documentation files (the "Software"),
2271# to deal in the Software without restriction, including without limitation
2272# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2273# and/or sell copies of the Software, and to permit persons to whom the
2274# Software is furnished to do so, subject to the following conditions:
2275#
2276# The above copyright notice and this permission notice shall be included
2277# in all copies or substantial portions of the Software.
2278#
2279# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2280# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2281# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2282# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2283# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2284# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2285# OTHER DEALINGS IN THE SOFTWARE.