Coverage for pygeodesy/fsums.py: 97%
869 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-06 16:50 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-06 16:50 -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, itemsorted, \
27 signOf, _signOf
28from pygeodesy.constants import INT0, _isfinite, NEG0, _pos_self, \
29 _0_0, _1_0, _N_1_0, Float, Int
30from pygeodesy.errors import _OverflowError, _TypeError, _ValueError, \
31 _xError, _xError2, _xkwds_get
32from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _DOT_, \
33 _enquote, _EQUAL_, _from_, _LANGLE_, _NOTEQUAL_, \
34 _not_finite_, _PERCENT_, _PLUS_, _RANGLE_, \
35 _SLASH_, _SPACE_, _STAR_, _UNDER_
36from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
37from pygeodesy.named import _Named, _NamedTuple, _NotImplemented
38from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \
39 Property_RO, property_RO
40from pygeodesy.streprs import Fmt, fstr, unstr
41# from pygeodesy.units import Float, Int # from .constants
43from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp
45__all__ = _ALL_LAZY.fsums
46__version__ = '24.05.06'
48_abs = abs
49_add_op_ = _PLUS_ # in .auxilats.auxAngle
50_eq_op_ = _EQUAL_ * 2 # _DEQUAL_
51_div_ = 'div'
52_Float = float # in .fstats
53_floordiv_op_ = _SLASH_ * 2 # _DSLASH_
54_fset_op_ = _EQUAL_
55_ge_op_ = _RANGLE_ + _EQUAL_
56_gt_op_ = _RANGLE_
57_iadd_op_ = _add_op_ + _EQUAL_ # in .auxilats.auxAngle, .fstats
58_integer_ = 'integer'
59_isAn = isinstance # in .fstats
60_le_op_ = _LANGLE_ + _EQUAL_
61_len = len
62_List = list
63_lt_op_ = _LANGLE_
64_mod_ = 'mod'
65_mod_op_ = _PERCENT_
66_mul_op_ = _STAR_
67_ne_op_ = _NOTEQUAL_
68_non_zero_ = 'non-zero'
69_pow_op_ = _STAR_ * 2 # _DSTAR_
70_significant_ = 'significant'
71_sub_op_ = _DASH_ # in .auxilats.auxAngle
72_threshold_ = 'threshold'
73_truediv_op_ = _SLASH_
74_Tuple = tuple
75_divmod_op_ = _floordiv_op_ + _mod_op_
76_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle
79def _2delta(*ab):
80 '''(INTERNAL) Helper for C{Fsum._fsum2}.
81 '''
82 try:
83 a, b = _2sum(*ab)
84 except _OverflowError:
85 a, b = ab
86 return _Float(a if fabs(a) > fabs(b) else b)
89def _2error(unused):
90 '''(INTERNAL) Throw a C{not-finite} exception.
91 '''
92 raise ValueError(_not_finite_)
95def _2float(index=None, **name_value): # in .fmath, .fstats
96 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.
97 '''
98 n, v = name_value.popitem() # _xkwds_item2(name_value)
99 try:
100 v = _Float(v)
101 return v if _isfinite(v) else _2error(v)
102 except Exception as X:
103 raise _xError(X, Fmt.INDEX(n, index), v)
106def _X_ps(X): # for _2floats only
107 return X._ps
110def _2floats(xs, origin=0, _X=_X_ps, _x=_Float):
111 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
112 '''
113 try:
114 i, x = origin, None
115 _fin = _isfinite
116 _FsT = _Fsum_Fsum2Tuple_types
117 _is = _isAn
118 for x in xs:
119 if _is(x, _FsT):
120 for p in _X(x._Fsum):
121 yield p
122 else:
123 f = _x(x)
124 yield f if _fin(f) else _2error(f)
125 i += 1
126 except Exception as X:
127 raise _xError(X, Fmt.INDEX(xs=i), x)
130def _Fsumf_(*xs): # floats=True, in .auxLat, ...
131 '''(INTERNAL) An C{Fsum} of I{known scalars}.
132 '''
133 return Fsum()._facc_scalar(xs, up=False)
136def _Fsum1f_(*xs): # floats=True, in .albers, ...
137 '''(INTERNAL) An C{Fsum} of I{known scalars}, 1-primed.
138 '''
139 return Fsum()._facc_scalar(_1primed(xs), up=False)
142def _2halfeven(s, r, p):
143 '''(INTERNAL) Round half-even.
144 '''
145 if (p > 0 and r > 0) or \
146 (p < 0 and r < 0): # signs match
147 r *= 2
148 t = s + r
149 if r == (t - s):
150 s = t
151 return s
154def _isFsum(x): # in .fmath
155 '''(INTERNAL) Is C{x} an C{Fsum} instance?
156 '''
157 return _isAn(x, Fsum)
160def _isFsumTuple(x): # in .fmath
161 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance?
162 '''
163 return _isAn(x, _Fsum_Fsum2Tuple_types)
166def _1_Over(x, op, **raiser_RESIDUAL): # vs _1_over
167 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
168 '''
169 return _Psum_(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
172def _1primed(xs): # in .fmath
173 '''(INTERNAL) 1-Primed summation of iterable C{xs}
174 items, all I{known} to be C{scalar}.
175 '''
176 yield _1_0
177 for x in xs:
178 yield x
179 yield _N_1_0
182def _psum(ps): # PYCHOK used!
183 '''(INTERNAL) Partials summation, updating C{ps}.
184 '''
185 # assert _isAn(ps, _List)
186 i = _len(ps) - 1
187 s = _0_0 if i < 0 else ps[i]
188 _2s = _2sum
189 while i > 0:
190 i -= 1
191 s, r = _2s(s, ps[i])
192 if r: # sum(ps) became inexact
193 if s:
194 ps[i:] = r, s
195 if i > 0:
196 s = _2halfeven(s, r, ps[i-1])
197 break # return s
198 s = r # PYCHOK no cover
199 ps[i:] = s,
200 return s
203def _Psum(ps, **name_RESIDUAL):
204 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
205 '''
206 f = Fsum(**name_RESIDUAL) if name_RESIDUAL else Fsum()
207 if ps:
208 f._ps[:] = ps
209 f._n = _len(f._ps)
210 return f
213def _Psum_(*ps, **name_RESIDUAL):
214 '''(INTERNAL) Return an C{Fsum} from 1 or 2 known scalar(s) C{ps}.
215 '''
216 return _Psum(ps, **name_RESIDUAL)
219def _2scalar2(other):
220 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
221 C{float} or C{as-is} and C{r} the residual of C{as-is}.
222 '''
223 if _isFsumTuple(other):
224 s, r = other._fint2
225 if r:
226 s, r = other._fprs2
227 if r: # PYCHOK no cover
228 s = other # L{Fsum} as-is
229 else:
230 r = 0
231 s = other # C{type} as-is
232 if isint(s, both=True):
233 s = int(s)
234 return s, r
237def _s_r(s, r):
238 '''(INTERNAL) Return C{(s, r)}, I{ordered}.
239 '''
240 if r:
241 if fabs(s) < fabs(r):
242 s, r = r, (s or INT0)
243 else:
244 r = INT0
245 return s, r
248def _strcomplex(s, *args):
249 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
250 '''
251 c = _strcomplex.__name__[4:]
252 n = _DASH_(_len(args), _arg_)
253 t = unstr(pow, *args)
254 return _SPACE_(c, s, _from_, n, t)
257def _stresidual(prefix, residual, R=0, **mod_ratio):
258 '''(INTERNAL) Residual error txt C{str}.
259 '''
260 p = _stresidual.__name__[3:]
261 t = Fmt.PARENSPACED(p, Fmt(residual))
262 for n, v in itemsorted(mod_ratio):
263 p = Fmt.PARENSPACED(n, Fmt(v))
264 t = _COMMASPACE_(t, p)
265 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_)
268def _2sum(a, b): # by .testFmath
269 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual).
270 '''
271 s = a + b
272 if _isfinite(s):
273 if fabs(a) < fabs(b):
274 b, a = a, b
275 return s, (b - (s - a))
276 u = unstr(_2sum, a, b)
277 t = Fmt.PARENSPACED(_not_finite_, s)
278 raise _OverflowError(u, txt=t)
281def _threshold(threshold):
282 '''(INTERNAL) Get the L{ResidualError}s threshold.
283 '''
284 try:
285 t = _Float(threshold) or _0_0
286 return t if _isfinite(t) else _2error(t) # PYCHOK None
287 except Exception as x:
288 raise ResidualError(threshold=threshold, cause=x)
291class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase
292 '''Precision floating point summation and I{running} summation.
294 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
295 I{running}, precision floating point summations. Accumulation may continue after any
296 intermediate, I{running} summuation.
298 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances,
299 any C{type} having method C{__float__} to convert the C{scalar} to a single
300 C{float}, except C{complex}.
302 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from
303 Python's C{math.fsum}.
305 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/
306 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>},
307 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
308 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
309 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
310 <https://Bugs.Python.org/issue2819>}.
311 '''
312 _math_fsum = None
313 _n = 0
314# _ps = [] # partial sums
315# _ps_max = 0 # max(Fsum._ps_max, _len(Fsum._ps))
316 _RESIDUAL = _threshold(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0))
318 def __init__(self, *xs, **name_RESIDUAL):
319 '''New L{Fsum} for I{running} precision floating point summation.
321 @arg xs: No, one or more items to add (each C{scalar} or an L{Fsum}
322 or L{Fsum2Tuple} instance), all positional.
323 @kwarg name_RESIDUAL: Optional C{B{name}=NN} for this L{Fsum} and
324 the C{B{RESIDUAL}=0.0} threshold for L{ResidualError}s.
326 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.
327 '''
328 if name_RESIDUAL:
330 def _n_R(name=NN, RESIDUAL=None):
331 return name, RESIDUAL
333 n, R = _n_R(**name_RESIDUAL)
334 if R is not None:
335 self.RESIDUAL(R)
336 if n:
337 self.name = n
339 self._ps = [] # [_0_0], see L{Fsum._fprs}
340 if xs:
341 self._facc_1(xs, up=False)
343 def __abs__(self):
344 '''Return this instance' absolute value as an L{Fsum}.
345 '''
346 s = self.signOf() # == self._cmp_0(0)
347 return (-self) if s < 0 else self._copy_2(self.__abs__)
349 def __add__(self, other):
350 '''Return C{B{self} + B{other}} as an L{Fsum}.
352 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
354 @return: The sum (L{Fsum}).
356 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
357 '''
358 f = self._copy_2(self.__add__)
359 return f._fadd(other, _add_op_)
361 def __bool__(self): # PYCHOK Python 3+
362 '''Return C{True} if this instance is I{exactly} non-zero.
363 '''
364 s, r = self._fprs2
365 return bool(s or r) and s != -r # == self != 0
367 def __ceil__(self): # PYCHOK not special in Python 2-
368 '''Return this instance' C{math.ceil} as C{int} or C{float}.
370 @return: An C{int} in Python 3+, but C{float} in Python 2-.
372 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
373 '''
374 return self.ceil
376 def __cmp__(self, other): # PYCHOK no cover
377 '''Compare this with an other instance or C{scalar}, Python 2-.
379 @return: -1, 0 or +1 (C{int}).
381 @raise TypeError: Incompatible B{C{other}} C{type}.
382 '''
383 s = self._cmp_0(other, self.cmp.__name__)
384 return _signOf(s, 0)
386 def __divmod__(self, other, **raiser_RESIDUAL):
387 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
388 with quotient C{div} an C{int} in Python 3+ or C{float}
389 in Python 2- and remainder C{mod} an L{Fsum} instance.
391 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
392 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
393 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
394 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
396 @raise ResidualError: Non-zero, significant residual or invalid
397 B{C{RESIDUAL}}.
399 @see: Method L{Fsum.fdiv}.
400 '''
401 f = self._copy_2(self.__divmod__)
402 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
404 def __eq__(self, other):
405 '''Compare this with an other instance or C{scalar}.
406 '''
407 return self._cmp_0(other, _eq_op_) == 0
409 def __float__(self):
410 '''Return this instance' current, precision running sum as C{float}.
412 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
413 '''
414 return _Float(self._fprs)
416 def __floor__(self): # PYCHOK not special in Python 2-
417 '''Return this instance' C{math.floor} as C{int} or C{float}.
419 @return: An C{int} in Python 3+, but C{float} in Python 2-.
421 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
422 '''
423 return self.floor
425 def __floordiv__(self, other):
426 '''Return C{B{self} // B{other}} as an L{Fsum}.
428 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
430 @return: The C{floor} quotient (L{Fsum}).
432 @see: Methods L{Fsum.__ifloordiv__}.
433 '''
434 f = self._copy_2(self.__floordiv__)
435 return f._floordiv(other, _floordiv_op_)
437 def __format__(self, *other): # PYCHOK no cover
438 '''Not implemented.'''
439 return _NotImplemented(self, *other)
441 def __ge__(self, other):
442 '''Compare this with an other instance or C{scalar}.
443 '''
444 return self._cmp_0(other, _ge_op_) >= 0
446 def __gt__(self, other):
447 '''Compare this with an other instance or C{scalar}.
448 '''
449 return self._cmp_0(other, _gt_op_) > 0
451 def __hash__(self): # PYCHOK no cover
452 '''Return this instance' C{hash}.
453 '''
454 return hash(self._ps) # XXX id(self)?
456 def __iadd__(self, other):
457 '''Apply C{B{self} += B{other}} to this instance.
459 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} instance.
461 @return: This instance, updated (L{Fsum}).
463 @raise TypeError: Invalid B{C{other}}, not
464 C{scalar} nor L{Fsum}.
466 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
467 '''
468 return self._fadd(other, _iadd_op_)
470 def __ifloordiv__(self, other):
471 '''Apply C{B{self} //= B{other}} to this instance.
473 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
475 @return: This instance, updated (L{Fsum}).
477 @raise ResidualError: Non-zero, significant residual
478 in B{C{other}}.
480 @raise TypeError: Invalid B{C{other}} type.
482 @raise ValueError: Invalid or non-finite B{C{other}}.
484 @raise ZeroDivisionError: Zero B{C{other}}.
486 @see: Methods L{Fsum.__itruediv__}.
487 '''
488 return self._floordiv(other, _floordiv_op_ + _fset_op_)
490 def __imatmul__(self, other): # PYCHOK no cover
491 '''Not implemented.'''
492 return _NotImplemented(self, other)
494 def __imod__(self, other):
495 '''Apply C{B{self} %= B{other}} to this instance.
497 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
499 @return: This instance, updated (L{Fsum}).
501 @see: Method L{Fsum.__divmod__}.
502 '''
503 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
505 def __imul__(self, other):
506 '''Apply C{B{self} *= B{other}} to this instance.
508 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
510 @return: This instance, updated (L{Fsum}).
512 @raise OverflowError: Partial C{2sum} overflow.
514 @raise TypeError: Invalid B{C{other}} type.
516 @raise ValueError: Invalid or non-finite B{C{other}}.
517 '''
518 return self._fmul(other, _mul_op_ + _fset_op_)
520 def __int__(self):
521 '''Return this instance as an C{int}.
523 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
524 and L{Fsum.floor}.
525 '''
526 i, _ = self._fint2
527 return i
529 def __invert__(self): # PYCHOK no cover
530 '''Not implemented.'''
531 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
532 return _NotImplemented(self)
534 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
535 '''Apply C{B{self} **= B{other}} to this instance.
537 @arg other: The exponent (C{scalar}, L{Fsum} or L{Fsum2Tuple}).
538 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
539 C{pow(B{self}, B{other}, B{mod})} version.
540 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
541 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
542 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
544 @return: This instance, updated (L{Fsum}).
546 @note: If B{C{mod}} is given, the result will be an C{integer}
547 L{Fsum} in Python 3+ if this instance C{is_integer} or
548 set to C{as_integer} and B{C{mod}} is given as C{None}.
550 @raise OverflowError: Partial C{2sum} overflow.
552 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
553 is non-zero and significant and either
554 B{C{other}} is a fractional or negative
555 C{scalar} or B{C{mod}} is given and not
556 C{None}.
558 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
559 invocation failed.
561 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
562 instance is C{0} or B{C{other}} is a fractional
563 C{scalar} and this instance is negative or has a
564 non-zero and significant residual or B{C{mod}}
565 is given as C{0}.
567 @see: CPython function U{float_pow<https://GitHub.com/
568 python/cpython/blob/main/Objects/floatobject.c>}.
569 '''
570 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
572 def __isub__(self, other):
573 '''Apply C{B{self} -= B{other}} to this instance.
575 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
577 @return: This instance, updated (L{Fsum}).
579 @raise TypeError: Invalid B{C{other}} type.
581 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
582 '''
583 return self._fsub(other, _isub_op_)
585 def __iter__(self):
586 '''Return an C{iter}ator over a C{partials} duplicate.
587 '''
588 return iter(self.partials)
590 def __itruediv__(self, other, **raiser_RESIDUAL):
591 '''Apply C{B{self} /= B{other}} to this instance.
593 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
594 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
595 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
596 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
598 @return: This instance, updated (L{Fsum}).
600 @raise OverflowError: Partial C{2sum} overflow.
602 @raise ResidualError: Non-zero, significant residual or invalid
603 B{C{RESIDUAL}}.
605 @raise TypeError: Invalid B{C{other}} type.
607 @raise ValueError: Invalid or non-finite B{C{other}}.
609 @raise ZeroDivisionError: Zero B{C{other}}.
611 @see: Method L{Fsum.__ifloordiv__}.
612 '''
613 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
615 def __le__(self, other):
616 '''Compare this with an other instance or C{scalar}.
617 '''
618 return self._cmp_0(other, _le_op_) <= 0
620 def __len__(self):
621 '''Return the number of values accumulated (C{int}).
622 '''
623 return self._n
625 def __lt__(self, other):
626 '''Compare this with an other instance or C{scalar}.
627 '''
628 return self._cmp_0(other, _lt_op_) < 0
630 def __matmul__(self, other): # PYCHOK no cover
631 '''Not implemented.'''
632 return _NotImplemented(self, other)
634 def __mod__(self, other):
635 '''Return C{B{self} % B{other}} as an L{Fsum}.
637 @see: Method L{Fsum.__imod__}.
638 '''
639 f = self._copy_2(self.__mod__)
640 return f._fdivmod2(other, _mod_op_).mod
642 def __mul__(self, other):
643 '''Return C{B{self} * B{other}} as an L{Fsum}.
645 @see: Method L{Fsum.__imul__}.
646 '''
647 f = self._copy_2(self.__mul__)
648 return f._fmul(other, _mul_op_)
650 def __ne__(self, other):
651 '''Compare this with an other instance or C{scalar}.
652 '''
653 return self._cmp_0(other, _ne_op_) != 0
655 def __neg__(self):
656 '''Return I{a copy of} this instance, I{negated}.
657 '''
658 f = self._copy_2(self.__neg__)
659 return f._fset(self._neg)
661 def __pos__(self):
662 '''Return this instance I{as-is}, like C{float.__pos__()}.
663 '''
664 return self if _pos_self else self._copy_2(self.__pos__)
666 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
667 '''Return C{B{self}**B{other}} as an L{Fsum}.
669 @see: Method L{Fsum.__ipow__}.
670 '''
671 f = self._copy_2(self.__pow__)
672 return f._fpow(other, _pow_op_, *mod)
674 def __radd__(self, other):
675 '''Return C{B{other} + B{self}} as an L{Fsum}.
677 @see: Method L{Fsum.__iadd__}.
678 '''
679 f = self._copy_2r(other, self.__radd__)
680 return f._fadd(self, _add_op_)
682 def __rdivmod__(self, other):
683 '''Return C{divmod(B{other}, B{self})} as 2-tuple
684 C{(quotient, remainder)}.
686 @see: Method L{Fsum.__divmod__}.
687 '''
688 f = self._copy_2r(other, self.__rdivmod__)
689 return f._fdivmod2(self, _divmod_op_)
691# def __repr__(self):
692# '''Return the default C{repr(this)}.
693# '''
694# return self.toRepr(lenc=True)
696 def __rfloordiv__(self, other):
697 '''Return C{B{other} // B{self}} as an L{Fsum}.
699 @see: Method L{Fsum.__ifloordiv__}.
700 '''
701 f = self._copy_2r(other, self.__rfloordiv__)
702 return f._floordiv(self, _floordiv_op_)
704 def __rmatmul__(self, other): # PYCHOK no cover
705 '''Not implemented.'''
706 return _NotImplemented(self, other)
708 def __rmod__(self, other):
709 '''Return C{B{other} % B{self}} as an L{Fsum}.
711 @see: Method L{Fsum.__imod__}.
712 '''
713 f = self._copy_2r(other, self.__rmod__)
714 return f._fdivmod2(self, _mod_op_).mod
716 def __rmul__(self, other):
717 '''Return C{B{other} * B{self}} as an L{Fsum}.
719 @see: Method L{Fsum.__imul__}.
720 '''
721 f = self._copy_2r(other, self.__rmul__)
722 return f._fmul(self, _mul_op_)
724 def __round__(self, *ndigits): # PYCHOK Python 3+
725 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
727 @arg ndigits: Optional number of digits (C{int}).
728 '''
729 f = self._copy_2(self.__round__)
730 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
731 return f._fset(round(_Float(self), *ndigits)) # can be C{int}
733 def __rpow__(self, other, *mod):
734 '''Return C{B{other}**B{self}} as an L{Fsum}.
736 @see: Method L{Fsum.__ipow__}.
737 '''
738 f = self._copy_2r(other, self.__rpow__)
739 return f._fpow(self, _pow_op_, *mod)
741 def __rsub__(self, other):
742 '''Return C{B{other} - B{self}} as L{Fsum}.
744 @see: Method L{Fsum.__isub__}.
745 '''
746 f = self._copy_2r(other, self.__rsub__)
747 return f._fsub(self, _sub_op_)
749 def __rtruediv__(self, other, **raiser_RESIDUAL):
750 '''Return C{B{other} / B{self}} as an L{Fsum}.
752 @see: Method L{Fsum.__itruediv__}.
753 '''
754 f = self._copy_2r(other, self.__rtruediv__)
755 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
757 def __str__(self):
758 '''Return the default C{str(self)}.
759 '''
760 return self.toStr(lenc=True)
762 def __sub__(self, other):
763 '''Return C{B{self} - B{other}} as an L{Fsum}.
765 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
767 @return: The difference (L{Fsum}).
769 @see: Method L{Fsum.__isub__}.
770 '''
771 f = self._copy_2(self.__sub__)
772 return f._fsub(other, _sub_op_)
774 def __truediv__(self, other, **raiser_RESIDUAL):
775 '''Return C{B{self} / B{other}} as an L{Fsum}.
777 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
778 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
779 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
780 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
782 @return: The quotient (L{Fsum}).
784 @raise ResidualError: Non-zero, significant residual or invalid
785 B{C{RESIDUAL}}.
787 @see: Method L{Fsum.__itruediv__}.
788 '''
789 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
791 __trunc__ = __int__
793 if _sys_version_info2 < (3, 0): # PYCHOK no cover
794 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
795 __div__ = __truediv__
796 __idiv__ = __itruediv__
797 __long__ = __int__
798 __nonzero__ = __bool__
799 __rdiv__ = __rtruediv__
801 def as_integer_ratio(self):
802 '''Return this instance as the ratio of 2 integers.
804 @return: 2-Tuple C{(numerator, denominator)} both C{int}
805 with C{numerator} signed and C{denominator}
806 non-zero, positive.
808 @see: Standard C{float.as_integer_ratio} in Python 2.7+.
809 '''
810 n, r = self._fint2
811 if r:
812 i, d = _Float(r).as_integer_ratio()
813 n *= d
814 n += i
815 else: # PYCHOK no cover
816 d = 1
817 return n, d
819 @property_RO
820 def as_iscalar(self):
821 '''Get this instance I{as-is} (L{Fsum} or C{scalar}), the
822 latter only if the C{residual} equals C{zero}.
823 '''
824 s, r = self._fprs2
825 return self if r else s
827 @property_RO
828 def ceil(self):
829 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
830 C{float} in Python 2-).
832 @note: This C{ceil} takes the C{residual} into account.
834 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
835 L{Fsum.imag} and L{Fsum.real}.
836 '''
837 s, r = self._fprs2
838 c = _ceil(s) + int(r) - 1
839 while r > (c - s): # (s + r) > c
840 c += 1
841 return c
843 cmp = __cmp__
845 def _cmp_0(self, other, op):
846 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
847 '''
848 if _isFsumTuple(other):
849 s = self._ps_1sum(*other._ps)
850 elif self._scalar(other, op):
851 s = self._ps_1sum(other)
852 else:
853 s = self.signOf() # res=True
854 return s
856 def copy(self, deep=False, name=NN):
857 '''Copy this instance, C{shallow} or B{C{deep}}.
859 @return: The copy (L{Fsum}).
860 '''
861 f = _Named.copy(self, deep=deep, name=name)
862 if f._ps is self._ps:
863 f._ps = _List(self._ps) # separate list
864 if not deep:
865 f._n = 1
866 # assert f._Fsum is f
867 return f
869 def _copy_2(self, which, name=NN):
870 '''(INTERNAL) Copy for I{dyadic} operators.
871 '''
872 n = name or which.__name__
873 # NOT .classof due to .Fdot(a, *b) args, etc.
874 f = _Named.copy(self, deep=False, name=n)
875 f._ps = _List(self._ps) # separate list
876 # assert f._n == self._n
877 # assert f._Fsum is f
878 return f
880 def _copy_2r(self, other, which):
881 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
882 '''
883 return other._copy_2(which) if _isFsum(other) else \
884 self._copy_2(which)._fset(other)
886# def _copy_RESIDUAL(self, other):
887# '''(INTERNAL) Copy C{other._RESIDUAL}.
888# '''
889# R = other._RESIDUAL
890# if R is not Fsum._RESIDUAL:
891# self._RESIDUAL = R
893 divmod = __divmod__
895 def _Error(self, op, other, Error, **txt_cause):
896 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
897 '''
898 return Error(_SPACE_(self.as_iscalar, op, other), **txt_cause)
900 def _ErrorX(self, X, op, other, *mod):
901 '''(INTERNAL) Format the caught exception C{X}.
902 '''
903 E, t = _xError2(X)
904 if mod:
905 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
906 return self._Error(op, other, E, txt=t, cause=X)
908 def _ErrorXs(self, X, xs, **kwds): # in .fmath
909 '''(INTERNAL) Format the caught exception C{X}.
910 '''
911 E, t = _xError2(X)
912 u = unstr(self.named3, *xs[:3], _ELLIPSIS=_len(xs) > 3, **kwds)
913 return E(u, txt=t, cause=X)
915 def _facc(self, xs, up=True, **origin_X_x):
916 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s.
917 '''
918 if xs:
919 _xs = _2floats(xs, **origin_X_x) # PYCHOK yield
920 ps = self._ps
921 ps[:] = self._ps_acc(_List(ps), _xs, up=up)
922 return self
924 def _facc_1(self, xs, **up):
925 '''(INTERNAL) Accumulate 0, 1 or more C{scalars} or L{Fsum}s,
926 all positional C{xs} in the caller of this method.
927 '''
928 return self._fadd(xs[0], _add_op_, **up) if _len(xs) == 1 else \
929 self._facc(xs, origin=1, **up)
931 def _facc_neg(self, xs, **up_origin):
932 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s, negated.
933 '''
934 def _N(X):
935 return X._ps_neg
937 def _n(x):
938 return -_Float(x)
940 return self._facc(xs, _X=_N, _x=_n, **up_origin)
942 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
943 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
944 '''
945 def _Pow4(p):
946 r = 0
947 if _isFsumTuple(p):
948 s, r = p._fprs2
949 if r:
950 m = Fsum._pow
951 else: # scalar
952 return _Pow4(s)
953 elif isint(p, both=True) and int(p) >= 0:
954 p = s = int(p)
955 m = Fsum._pow_int
956 else:
957 p = s = _2float(power=p)
958 m = Fsum._pow_scalar
959 return m, p, s, r
961 _Pow, p, s, r = _Pow4(power)
962 if p: # and xs:
963 op = which.__name__
964 _Fs = Fsum
965 _is = _isAn
966 _pow = self._pow_2_3
968 def _P(X):
969 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
970 return f._ps if _is(f, _Fs) else (f,)
972 def _p(x):
973 x = _Float(x)
974 f = _pow(x, s, power, op, **raiser_RESIDUAL)
975 if f and r:
976 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
977 return f
979 f = self._facc(xs, origin=1, _X=_P, _x=_p)
980 else:
981 f = self._facc_scalar_(_Float(_len(xs))) # x**0 == 1
982 return f
984 def _facc_scalar(self, xs, **up):
985 '''(INTERNAL) Accumulate all C{xs}, known to be scalar.
986 '''
987 if xs:
988 _ = self._ps_acc(self._ps, xs, **up)
989 return self
991 def _facc_scalar_(self, *xs, **up):
992 '''(INTERNAL) Accumulate all positional C{xs}, known to be scalar.
993 '''
994 if xs:
995 _ = self._ps_acc(self._ps, xs, **up)
996 return self
998# def _facc_up(self, up=True):
999# '''(INTERNAL) Update the C{partials}, by removing
1000# and re-accumulating the final C{partial}.
1001# '''
1002# ps = self._ps
1003# while _len(ps) > 1:
1004# p = ps.pop()
1005# if p:
1006# n = self._n
1007# _ = self._ps_acc(ps, (p,), up=False)
1008# self._n = n
1009# break
1010# return self._update() if up else self
1012 def fadd(self, xs=()):
1013 '''Add an iterable's items to this instance.
1015 @arg xs: Iterable of items to add (each C{scalar}
1016 or an L{Fsum} or L{Fsum2Tuple} instance).
1018 @return: This instance (L{Fsum}).
1020 @raise OverflowError: Partial C{2sum} overflow.
1022 @raise TypeError: An invalid B{C{xs}} item.
1024 @raise ValueError: Invalid or non-finite B{C{xs}} value.
1025 '''
1026 if _isFsumTuple(xs):
1027 self._facc_scalar(xs._ps) # _Tuple(xs._ps)
1028 elif isscalar(xs): # for backward compatibility
1029 self._facc_scalar_(_2float(x=xs)) # PYCHOK no cover
1030 elif xs: # assert isiterable(xs)
1031 self._facc(xs)
1032 return self
1034 def fadd_(self, *xs):
1035 '''Add all positional items to this instance.
1037 @arg xs: Values to add (each C{scalar} or an L{Fsum}
1038 or L{Fsum2Tuple} instance), all positional.
1040 @see: Method L{Fsum.fadd} for further details.
1041 '''
1042 return self._facc_1(xs)
1044 def _fadd(self, other, op, **up): # in .fmath.Fhorner
1045 '''(INTERNAL) Apply C{B{self} += B{other}}.
1046 '''
1047 if not self._ps: # new Fsum(x)
1048 self._fset(other, as_is=False, **up)
1049 elif _isFsumTuple(other):
1050 self._facc_scalar(other._ps, **up) # _Tuple
1051 elif self._scalar(other, op):
1052 self._facc_scalar_(other, **up)
1053 return self
1055 fcopy = copy # for backward compatibility
1056 fdiv = __itruediv__
1057 fdivmod = __divmod__
1059 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1060 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1061 '''
1062 # result mostly follows CPython function U{float_divmod
1063 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1064 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1065 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1066 if q: # == float // other == floor(float / other)
1067 self -= Fsum(q) * other # NOT other * q!
1069 s = signOf(other) # make signOf(self) == signOf(other)
1070 if s and self.signOf() == -s: # PYCHOK no cover
1071 self += other
1072 q -= 1
1073# t = self.signOf()
1074# if t and t != s:
1075# raise self._Error(op, other, _AssertionError, txt=signOf.__name__)
1076 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1078 def _finite(self, other, op=None):
1079 '''(INTERNAL) Return B{C{other}} if C{finite}.
1080 '''
1081 if _isfinite(other):
1082 return other
1083 raise ValueError(_not_finite_) if op is None else \
1084 self._Error(op, other, _ValueError, txt=_not_finite_)
1086 def fint(self, name=NN, **raiser_RESIDUAL):
1087 '''Return this instance' current running sum as C{integer}.
1089 @kwarg name: Optional name (C{str}), overriding C{"fint"}.
1090 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
1091 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
1092 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
1094 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1095 with a zero or insignificant I{integer} residual.
1097 @raise ResidualError: Non-zero, significant residual or invalid
1098 B{C{RESIDUAL}}.
1100 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1101 '''
1102 i, r = self._fint2
1103 if r:
1104 R = self._raiser(r, i, **raiser_RESIDUAL)
1105 if R:
1106 t = _stresidual(_integer_, r, **R)
1107 raise ResidualError(_integer_, i, txt=t)
1108 f = self._copy_2(self.fint, name=name)
1109 return f._fset(i)
1111 def fint2(self, **name):
1112 '''Return this instance' current running sum as C{int} and the
1113 I{integer} residual.
1115 @kwarg name: Optional name (C{str}).
1117 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1118 an C{int} and I{integer} C{residual} a C{float} or
1119 C{INT0} if the C{fsum} is considered to be I{exact}.
1120 '''
1121 return Fsum2Tuple(*self._fint2, **name)
1123 @Property_RO
1124 def _fint2(self): # see ._fset
1125 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1126 '''
1127 s, r = self._fprs2
1128 i = int(s)
1129 n = _len(self._ps)
1130 r = self._ps_1sum(i) if r and n > 1 else _Float(s - i)
1131 return i, (r or INT0) # Fsum2Tuple?
1133 @deprecated_property_RO
1134 def float_int(self): # PYCHOK no cover
1135 '''DEPRECATED, use method C{Fsum.int_float}.'''
1136 return self.int_float() # raiser=False
1138 @property_RO
1139 def floor(self):
1140 '''Get this instance' C{floor} (C{int} in Python 3+, but
1141 C{float} in Python 2-).
1143 @note: This C{floor} takes the C{residual} into account.
1145 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1146 L{Fsum.imag} and L{Fsum.real}.
1147 '''
1148 s, r = self._fprs2
1149 f = _floor(s) + _floor(r) + 1
1150 while (f - s) > r: # f > (s + r)
1151 f -= 1
1152 return f
1154# ffloordiv = __ifloordiv__ # for naming consistency
1155# floordiv = __floordiv__ # for naming consistency
1157 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1158 '''Apply C{B{self} //= B{other}}.
1159 '''
1160 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1161 return self._fset(q.floor) # floor(q)
1163 fmul = __imul__
1165 def _fmul(self, other, op):
1166 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1167 '''
1168 if _isFsumTuple(other):
1169 if _len(self._ps) != 1:
1170 f = self._mul_Fsum(other, op)
1171 elif _len(other._ps) != 1: # and _len(self._ps) == 1
1172 f = other._mul_scalar(self._ps[0], op)
1173 else: # _len(other._ps) == _len(self._ps) == 1
1174 f = self._finite(self._ps[0] * other._ps[0])
1175 else:
1176 s = self._scalar(other, op)
1177 f = self._mul_scalar(s, op)
1178 return self._fset(f) # n=_len(self) + 1
1180 def fover(self, over, **raiser_RESIDUAL):
1181 '''Apply C{B{self} /= B{over}} and summate.
1183 @arg over: An L{Fsum} or C{scalar} denominator.
1184 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
1185 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
1186 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
1188 @return: Precision running sum (C{float}).
1190 @raise ResidualError: Non-zero, significant residual or invalid
1191 B{C{RESIDUAL}}.
1193 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1194 '''
1195 return _Float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1197 fpow = __ipow__
1199 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1200 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1201 '''
1202 if mod:
1203 if mod[0] is not None: # == 3-arg C{pow}
1204 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1205 elif self.is_integer():
1206 # return an exact C{int} for C{int}**C{int}
1207 i, _ = self._fint2 # assert _ == 0
1208 x, r = _2scalar2(other) # C{int}, C{float} or other
1209 f = _Psum_(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1210 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1211 else: # mod[0] is None, power(self, other)
1212 f = self._pow(other, other, op, **raiser_RESIDUAL)
1213 else: # pow(self, other)
1214 f = self._pow(other, other, op, **raiser_RESIDUAL)
1215 return self._fset(f, as_is=isint(f)) # n=max(_len(self), 1)
1217 @Property_RO
1218 def _fprs(self):
1219 '''(INTERNAL) Get and cache this instance' precision
1220 running sum (C{float} or C{int}), ignoring C{residual}.
1222 @note: The precision running C{fsum} after a C{//=} or
1223 C{//} C{floor} division is C{int} in Python 3+.
1224 '''
1225 return self._fprs2.fsum
1227 @Property_RO
1228 def _fprs2(self):
1229 '''(INTERNAL) Get and cache this instance' precision
1230 running sum and residual (L{Fsum2Tuple}).
1231 '''
1232 ps = self._ps
1233 n = _len(ps) - 2
1234 if n > 0: # _len(ps) > 2
1235 s = _psum(ps)
1236 n = _len(ps) - 2
1237 if n > 0:
1238 r = self._ps_1sum(s)
1239 return Fsum2Tuple(*_s_r(s, r))
1240 if n == 0: # _len(ps) == 2
1241 s, r = _s_r(*_2sum(*ps))
1242 ps[:] = (r, s) if r else (s,)
1243 elif ps: # _len(ps) == 1
1244 s, r = ps[0], INT0
1245 else: # _len(ps) == 0
1246 s, r = _0_0, INT0
1247 ps[:] = s,
1248 # assert self._ps is ps
1249 return Fsum2Tuple(s, r)
1251 def fset_(self, *xs):
1252 '''Replace this instance' value with all positional items.
1254 @arg xs: Optional, new values (each C{scalar} or
1255 an L{Fsum} or L{Fsum2Tuple} instance),
1256 all positional.
1258 @return: This instance, replaced (C{Fsum}).
1260 @see: Method L{Fsum.fadd} for further details.
1261 '''
1262 f = Fsum(*xs) if xs else _0_0
1263 return self._fset(f)
1265 def _fset(self, other, as_is=True, n=0, up=True):
1266 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1267 '''
1268 if other is self:
1269 pass # from ._fmul, ._ftruediv and ._pow_0_1
1270 elif _isFsumTuple(other):
1271 self._ps[:] = other._ps
1272 self._n = n or other._n
1273# self._copy_RESIDUAL(other)
1274 if up: # use or zap the C{Property_RO} values
1275 Fsum._fint2._update_from(self, other)
1276 Fsum._fprs ._update_from(self, other)
1277 Fsum._fprs2._update_from(self, other)
1278 elif isscalar(other):
1279 s = other if as_is else _Float(other)
1280 self._ps[:] = s,
1281 self._n = n or 1
1282 if up:
1283 i = int(s) # see ._fint2
1284 t = i, ((s - i) or INT0)
1285 # Property_ROs _fint2, _fprs and _fprs2 can't be a Property:
1286 # Property's _fset zaps the value just set by the @setter
1287 self.__dict__.update(_fint2=t, _fprs=s, _fprs2=Fsum2Tuple(s, INT0))
1288 else: # PYCHOK no cover
1289 raise self._Error(_fset_op_, other, _TypeError)
1290 return self
1292 def _fset_ps(self, other, n=0): # in .fmath
1293 '''(INTERNAL) Set partials from a known C{scalar}, L{Fsum} or L{Fsum2Tuple}.
1294 '''
1295 if _isFsumTuple(other):
1296 self._ps[:] = other._ps
1297 self._n = n or other._n
1298 else: # assert isscalar(other)
1299 self._ps[:] = other,
1300 self._n = n or 1
1301 return self
1303 def fsub(self, xs=()):
1304 '''Subtract an iterable's items from this instance.
1306 @see: Method L{Fsum.fadd} for further details.
1307 '''
1308 return self._facc_neg(xs)
1310 def fsub_(self, *xs):
1311 '''Subtract all positional items from this instance.
1313 @see: Method L{Fsum.fadd_} for further details.
1314 '''
1315 return self._fsub(xs[0], _sub_op_) if _len(xs) == 1 else \
1316 self._facc_neg(xs, origin=1)
1318 def _fsub(self, other, op):
1319 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1320 '''
1321 if _isFsumTuple(other):
1322 if other is self: # or other._fprs2 == self._fprs2:
1323 self._fset(_0_0, n=_len(self) * 2)
1324 elif other._ps:
1325 self._facc_scalar(other._ps_neg)
1326 elif self._scalar(other, op):
1327 self._facc_scalar_(-other)
1328 return self
1330 def fsum(self, xs=()):
1331 '''Add an iterable's items, summate and return the
1332 current precision running sum.
1334 @arg xs: Iterable of items to add (each item C{scalar}
1335 or an L{Fsum} or L{Fsum2Tuple} instance).
1337 @return: Precision running sum (C{float} or C{int}).
1339 @see: Method L{Fsum.fadd}.
1341 @note: Accumulation can continue after summation.
1342 '''
1343 return self._facc(xs)._fprs
1345 def fsum_(self, *xs):
1346 '''Add any positional items, summate and return the
1347 current precision running sum.
1349 @arg xs: Items to add (each C{scalar} or an L{Fsum}
1350 or L{Fsum2Tuple} instance), all positional.
1352 @return: Precision running sum (C{float} or C{int}).
1354 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1355 '''
1356 return self._facc_1(xs)._fprs
1358 @property_RO
1359 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, for C{_2floats}.
1360 return self # NOT @Property_RO, see .copy and ._copy_2
1362 def Fsum_(self, *xs, **name):
1363 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1365 @kwarg name: Optional name (C{str}).
1367 @return: Copy of this updated instance (L{Fsum}).
1368 '''
1369 return self._facc_1(xs)._copy_2(self.Fsum_, **name)
1371 def Fsum2Tuple_(self, *xs, **name):
1372 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1374 @kwarg name: Optional name (C{str}).
1376 @return: Precision running sum (L{Fsum2Tuple}).
1377 '''
1378 return Fsum2Tuple(self._facc_1(xs)._fprs2, **name)
1380 def fsum2(self, xs=(), name=NN):
1381 '''Add an iterable's items, summate and return the
1382 current precision running sum I{and} the C{residual}.
1384 @arg xs: Iterable of items to add (each item C{scalar}
1385 or an L{Fsum} or L{Fsum2Tuple} instance).
1386 @kwarg name: Optional name (C{str}).
1388 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1389 current precision running sum and C{residual}, the
1390 (precision) sum of the remaining C{partials}. The
1391 C{residual is INT0} if the C{fsum} is considered
1392 to be I{exact}.
1394 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1395 '''
1396 t = self._facc(xs)._fprs2
1397 return t.dup(name=name) if name else t
1399 def fsum2_(self, *xs):
1400 '''Add any positional items, summate and return the current
1401 precision running sum and the I{differential}.
1403 @arg xs: Values to add (each C{scalar} or an L{Fsum} or
1404 L{Fsum2Tuple} instance), all positional.
1406 @return: 2Tuple C{(fsum, delta)} with the current, precision
1407 running C{fsum} like method L{Fsum.fsum} and C{delta},
1408 the difference with previous running C{fsum}, C{float}.
1410 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1411 '''
1412 return self._fsum2(xs, self._facc_1)
1414 def _fsum2(self, xs, _f, **origin):
1415 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1416 '''
1417 p, q = self._fprs2
1418 if xs:
1419 s, r = _f(xs, **origin)._fprs2
1420 return s, _2delta(s - p, r - q) # _fsum(_1primed((s, -p, r, -q))
1421 else:
1422 return p, _0_0
1424 def fsumf_(self, *xs):
1425 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1426 '''
1427 return self._facc_scalar(xs)._fprs
1429 def Fsumf_(self, *xs):
1430 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1431 '''
1432 return self._facc_scalar(xs)._copy_2(self.Fsumf_)
1434 def fsum2f_(self, *xs):
1435 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}} are I{known to be scalar}.
1436 '''
1437 return self._fsum2(xs, self._facc_scalar, origin=1)
1439# ftruediv = __itruediv__ # for naming consistency?
1441 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1442 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1443 '''
1444 n = _1_0
1445 if _isFsumTuple(other):
1446 if other is self or self == other:
1447 return self._fset(n) # n=_len(self)
1448 d, r = other._fprs2
1449 if r:
1450 R = self._raiser(r, d, **raiser_RESIDUAL)
1451 if R:
1452 raise self._ResidualError(op, other, r, **R)
1453 d, n = other.as_integer_ratio()
1454 else:
1455 d = self._scalar(other, op)
1456 try:
1457 s = n / d
1458 except Exception as X:
1459 raise self._ErrorX(X, op, other)
1460 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1461 return self._fset(f) # as_is=False
1463 @property_RO
1464 def imag(self):
1465 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1467 @see: Property L{Fsum.real}.
1468 '''
1469 return _0_0
1471 def int_float(self, **raiser_RESIDUAL):
1472 '''Return this instance' current running sum as C{int} or C{float}.
1474 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
1475 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
1476 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
1478 @return: This C{integer} sum if this instance C{is_integer},
1479 otherwise return the C{float} sum if the residual is
1480 zero or not significant.
1482 @raise ResidualError: Non-zero, significant residual or invalid
1483 B{C{RESIDUAL}}.
1485 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.RESIDUAL} and
1486 property L{Fsum.as_iscalar}.
1487 '''
1488 s, r = self._fint2
1489 if r:
1490 s, r = self._fprs2
1491 if r: # PYCHOK no cover
1492 R = self._raiser(r, s, **raiser_RESIDUAL)
1493 if R:
1494 t = _stresidual(_non_zero_, r, **R)
1495 raise ResidualError(int_float=s, txt=t)
1496 s = _Float(s) # redundant
1497 return s
1499 def is_exact(self):
1500 '''Is this instance' running C{fsum} considered to be exact?
1501 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1502 '''
1503 return self.residual is INT0
1505 def is_integer(self):
1506 '''Is this instance' running sum C{integer}? (C{bool}).
1508 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1509 '''
1510 _, r = self._fint2
1511 return False if r else True
1513 def is_math_fsum(self):
1514 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and
1515 L{fsum1_} plus partials summation are based on Python's
1516 C{math.fsum} or not.
1518 @return: C{2} if all functions and partials summation
1519 are based on C{math.fsum}, C{True} if only
1520 the functions are based on C{math.fsum} (and
1521 partials summation is not) or C{False} if
1522 none are.
1523 '''
1524 f = Fsum._math_fsum
1525 return 2 if _psum is f else bool(f)
1527 def is_scalar(self, **raiser_RESIDUAL):
1528 '''Is this instance' running sum C{scalar} without residual or with
1529 a residual I{ratio} not exceeding the RESIDUAL threshold?
1531 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to ignore
1532 L{ResidualError}s and C{B{RESIDUAL}=scalar} to override
1533 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
1535 @return: C{True} if this instance' non-zero residual C{ratio} exceeds
1536 the L{RESIDUAL<Fsum.RESIDUAL>} threshold (C{bool}).
1538 @raise ResidualError: Non-zero, significant residual or invalid
1539 B{C{RESIDUAL}}.
1541 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property
1542 L{Fsum.as_iscalar}.
1543 '''
1544 s, r = self._fprs2
1545 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1547 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1548 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1549 '''
1550 # assert _isFsumTuple(other)
1551 if self._ps and other._ps:
1552 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
1553 else:
1554 f = _0_0
1555 return f
1557 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1558 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
1559 '''
1560 # assert isscalar(factor)
1561 if self._ps and self._finite(factor, op):
1562 f = self if factor == _1_0 else (
1563 self._neg if factor == _N_1_0 else
1564 self._ps_mul(op, factor).as_iscalar)
1565 else:
1566 f = _0_0
1567 return f
1569 @property_RO
1570 def _neg(self):
1571 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
1572 '''
1573 return _Psum(self._ps_neg) if self._ps else NEG0
1575 @property_RO
1576 def partials(self):
1577 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
1578 '''
1579 return _Tuple(self._ps)
1581 def pow(self, x, *mod, **raiser_RESIDUAL):
1582 '''Return C{B{self}**B{x}} as L{Fsum}.
1584 @arg x: The exponent (C{scalar} or L{Fsum}).
1585 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
1586 C{pow(B{self}, B{other}, B{mod})} version.
1587 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
1588 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
1589 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
1591 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
1592 result (L{Fsum}).
1594 @raise ResidualError: Non-zero, significant residual or invalid
1595 B{C{RESIDUAL}}.
1597 @note: If B{C{mod}} is given as C{None}, the result will be an
1598 C{integer} L{Fsum} provided this instance C{is_integer}
1599 or set to C{integer} by an L{Fsum.fint} call.
1601 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
1602 and L{Fsum.root}.
1603 '''
1604 f = self._copy_2(self.pow)
1605 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
1607 def _pow(self, other, unused, op, **raiser_RESIDUAL):
1608 '''Return C{B{self} ** B{other}}.
1609 '''
1610 if _isFsumTuple(other):
1611 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
1612 elif self._scalar(other, op):
1613 x = self._finite(other, op)
1614 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1615 else:
1616 f = self._pow_0_1(0, other)
1617 return f
1619 def _pow_0_1(self, x, other):
1620 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
1621 '''
1622 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
1624 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
1625 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
1626 B{x}, int B{mod} or C{None})}, embellishing errors.
1627 '''
1629 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
1630 m = mod[0]
1631 # assert _isFsumTuple(b)
1633 def _s(s, r):
1634 R = self._raiser(r, s, **raiser_RESIDUAL)
1635 if R:
1636 raise self._ResidualError(op, other, r, mod=m, **R)
1637 return s
1639 b = _s(*(b._fprs2 if m is None else b._fint2))
1640 x = _s(*_2scalar2(x))
1642 try:
1643 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
1644 s = pow(b, x, *mod)
1645 if iscomplex(s):
1646 # neg**frac == complex in Python 3+, but ValueError in 2-
1647 raise ValueError(_strcomplex(s, b, x, *mod))
1648 return self._finite(s)
1649 except Exception as X:
1650 raise self._ErrorX(X, op, other, *mod)
1652 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
1653 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsumTuple(other)}.
1654 '''
1655 # assert _isFsumTuple(other)
1656 x, r = other._fprs2
1657 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1658 if f and r:
1659 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
1660 return f
1662 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
1663 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
1664 '''
1665 # assert isint(x) and x >= 0
1666 ps = self._ps
1667 if _len(ps) > 1:
1668 _mul_Fsum = Fsum._mul_Fsum
1669 if x > 4:
1670 p = self
1671 f = self if (x & 1) else _Psum_(_1_0)
1672 m = x >> 1 # // 2
1673 while m:
1674 p = _mul_Fsum(p, p, op) # p **= 2
1675 if (m & 1):
1676 f = _mul_Fsum(f, p, op) # f *= p
1677 m >>= 1 # //= 2
1678 elif x > 1: # self**2, 3, or 4
1679 f = _mul_Fsum(self, self, op)
1680 if x > 2: # self**3 or 4
1681 p = self if x < 4 else f
1682 f = _mul_Fsum(f, p, op)
1683 else: # self**1 or self**0 == 1 or _1_0
1684 f = self._pow_0_1(x, other)
1685 elif ps: # self._ps[0]**x
1686 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
1687 else: # PYCHOK no cover
1688 # 0**pos_int == 0, but 0**0 == 1
1689 f = 0 if x else 1
1690 return f
1692 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
1693 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
1694 '''
1695 s, r = self._fprs2
1696 if r:
1697 # assert s != 0
1698 if isint(x, both=True): # self**int
1699 x = int(x)
1700 y = _abs(x)
1701 if y > 1:
1702 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
1703 if x > 0: # i.e. > 1
1704 return f # Fsum or scalar
1705 # assert x < 0 # i.e. < -1
1706 if _isFsum(f):
1707 s, r = f._fprs2
1708 if r:
1709 return _1_Over(f, op, **raiser_RESIDUAL)
1710 else: # scalar
1711 s = f
1712 # use s**(-1) to get the CPython
1713 # float_pow error iff s is zero
1714 x = -1
1715 elif x < 0: # self**(-1)
1716 return _1_Over(self, op, **raiser_RESIDUAL) # 1 / self
1717 else: # self**1 or self**0
1718 return self._pow_0_1(x, other) # self, 1 or 1.0
1719 else: # self**fractional
1720 R = self._raiser(r, s, **raiser_RESIDUAL)
1721 if R:
1722 raise self._ResidualError(op, other, r, **R)
1723 n, d = self.as_integer_ratio()
1724 if _abs(n) > _abs(d):
1725 n, d, x = d, n, (-x)
1726 s = n / d
1727 # assert isscalar(s) and isscalar(x)
1728 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
1730 def _ps_acc(self, ps, xs, up=True, **unused):
1731 '''(INTERNAL) Accumulate C{xs} scalars into list C{ps}.
1732 '''
1733 n = 0
1734 _2s = _2sum
1735 for x in (_Tuple(xs) if xs is ps else xs):
1736 # assert isscalar(x) and _isfinite(x)
1737 if x:
1738 i = 0
1739 for p in ps:
1740 x, p = _2s(x, p)
1741 if p:
1742 ps[i] = p
1743 i += 1
1744 ps[i:] = (x,) if x else ()
1745 n += 1
1746 if n:
1747 self._n += n
1748 # Fsum._ps_max = max(Fsum._ps_max, _len(ps))
1749 if up:
1750 self._update()
1751 return ps
1753 def _ps_mul(self, op, *factors):
1754 '''(INTERNAL) Multiply this instance' C{partials} with each
1755 of the scalar B{C{factors}} and accumulate.
1756 '''
1757 def _pfs(ps, fs):
1758 if _len(ps) < _len(fs):
1759 ps, fs = fs, ps
1760 _fin = _isfinite
1761 for f in fs:
1762 for p in ps:
1763 p *= f
1764 yield p if _fin(p) else self._finite(p, op)
1766 return _Psum(self._ps_acc([], _pfs(self._ps, factors), up=False))
1768 @property_RO
1769 def _ps_neg(self):
1770 '''(INTERNAL) Yield the partials, I{negated}.
1771 '''
1772 for p in self._ps:
1773 yield -p
1775 def _ps_1sum(self, *less):
1776 '''(INTERNAL) Return the partials sum, 1-primed C{less} any scalars.
1777 '''
1778 def _1pls(ps, ls):
1779 yield _1_0
1780 for p in ps:
1781 yield p
1782 for p in ls:
1783 yield -p
1784 yield _N_1_0
1786 return _fsum(_1pls(self._ps, less))
1788 def _raiser(self, r, s, raiser=True, **RESIDUAL):
1789 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
1790 I{and} is residual C{r} I{non-zero} or I{significant} (for a
1791 negative respectively positive C{RESIDUAL} threshold)?
1792 '''
1793 if r and raiser:
1794 t = self._RESIDUAL
1795 if RESIDUAL:
1796 t = _threshold(_xkwds_get(RESIDUAL, RESIDUAL=t))
1797 if t < 0 or (s + r) != s:
1798 q = (r / s) if s else s # == 0.
1799 if fabs(q) > fabs(t):
1800 return dict(ratio=q, R=t)
1801 return {}
1803 @property_RO
1804 def real(self):
1805 '''Get the C{real} part of this instance (C{float}).
1807 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
1808 and properties L{Fsum.ceil}, L{Fsum.floor},
1809 L{Fsum.imag} and L{Fsum.residual}.
1810 '''
1811 return _Float(self._fprs)
1813 @property_RO
1814 def residual(self):
1815 '''Get this instance' residual (C{float} or C{int}): the
1816 C{sum(partials)} less the precision running sum C{fsum}.
1818 @note: The C{residual is INT0} iff the precision running
1819 C{fsum} is considered to be I{exact}.
1821 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
1822 '''
1823 return self._fprs2.residual
1825 def RESIDUAL(self, *threshold):
1826 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
1827 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
1829 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
1830 L{ResidualError}s in division and exponention, if
1831 C{None} restore the default set with env variable
1832 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
1833 current setting.
1835 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
1837 @raise ResidualError: Invalid B{C{threshold}}.
1839 @note: L{ResidualError}s may be thrown if the non-zero I{ratio}
1840 C{residual / fsum} exceeds the given B{C{threshold}} and
1841 if the C{residual} is non-zero and I{significant} vs the
1842 C{fsum}, i.e. C{(fsum + residual) != fsum} and if optional
1843 keyword argument C{raiser=False} is missing. Specify a
1844 negative B{C{threshold}} for only non-zero C{residual}
1845 testing without I{significant}.
1846 '''
1847 r = self._RESIDUAL
1848 if threshold:
1849 t = threshold[0]
1850 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
1851 (_0_0 if t else _1_0) if isbool(t) else
1852 _threshold(t)) # ... backward compatibility
1853 return r
1855 def _ResidualError(self, op, other, residual, **mod_R):
1856 '''(INTERNAL) Non-zero B{C{residual}} etc.
1857 '''
1858 def _p(mod=None, R=0, **unused): # ratio=0
1859 return (_non_zero_ if R < 0 else _significant_) \
1860 if mod is None else _integer_
1862 t = _stresidual(_p(**mod_R), residual, **mod_R)
1863 return self._Error(op, other, ResidualError, txt=t)
1865 def root(self, root, **raiser_RESIDUAL):
1866 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
1868 @arg root: The order (C{scalar} or L{Fsum}), non-zero.
1869 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to
1870 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}
1871 to override the L{RESIDUAL<Fsum.RESIDUAL>}.
1873 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
1875 @raise ResidualError: Non-zero, significant residual or invalid
1876 B{C{RESIDUAL}}.
1878 @see: Method L{Fsum.pow}.
1879 '''
1880 x = _1_Over(root, _truediv_op_, **raiser_RESIDUAL)
1881 f = self._copy_2(self.root)
1882 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
1884 def _scalar(self, other, op, **txt):
1885 '''(INTERNAL) Return scalar C{other}.
1886 '''
1887 if isscalar(other):
1888 return other
1889 raise self._Error(op, other, _TypeError, **txt) # _invalid_
1891 def signOf(self, res=True):
1892 '''Determine the sign of this instance.
1894 @kwarg res: If C{True} consider, otherwise
1895 ignore the residual (C{bool}).
1897 @return: The sign (C{int}, -1, 0 or +1).
1898 '''
1899 s, r = self._fprs2
1900 r = (-r) if res else 0
1901 return _signOf(s, r)
1903 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
1904 '''Return this C{Fsum} instance as representation.
1906 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
1907 for method L{Fsum.toStr}.
1909 @return: This instance (C{repr}).
1910 '''
1911 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
1913 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
1914 '''Return this C{Fsum} instance as string.
1916 @kwarg lenc: If C{True} include the current C{[len]} of this
1917 L{Fsum} enclosed in I{[brackets]} (C{bool}).
1918 @kwarg prec_sep_fmt: Optional keyword arguments for method
1919 L{Fsum2Tuple.toStr}.
1921 @return: This instance (C{str}).
1922 '''
1923 p = self.classname
1924 if lenc:
1925 p = Fmt.SQUARE(p, _len(self))
1926 n = _enquote(self.name, white=_UNDER_)
1927 t = self._fprs2.toStr(**prec_sep_fmt)
1928 return NN(p, _SPACE_, n, t)
1930 def _truediv(self, other, op, **raiser_RESIDUAL):
1931 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
1932 '''
1933 f = self._copy_2(self.__truediv__)
1934 return f._ftruediv(other, op, **raiser_RESIDUAL)
1936 def _update(self, updated=True): # see ._fset
1937 '''(INTERNAL) Zap all cached C{Property_RO} values.
1938 '''
1939 if updated:
1940 _pop = self.__dict__.pop
1941 for p in _ROs:
1942 _ = _pop(p, None)
1943# Fsum._fint2._update(self)
1944# Fsum._fprs ._update(self)
1945# Fsum._fprs2._update(self)
1946 return self # for .fset_
1948_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
1951def _Float_Int(arg, **name_Error):
1952 '''(INTERNAL) Unit of L{Fsum2Tuple} items.
1953 '''
1954 U = Int if isint(arg) else Float
1955 return U(arg, **name_Error)
1958class DivMod2Tuple(_NamedTuple):
1959 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
1960 C{mod} results of a C{divmod} operation.
1962 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
1963 in Python 2-. Remainder C{mod} an L{Fsum} instance.
1964 '''
1965 _Names_ = (_div_, _mod_)
1966 _Units_ = (_Float_Int, Fsum)
1969class Fsum2Tuple(_NamedTuple):
1970 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
1971 and the C{residual}, the sum of the remaining partials. Each
1972 item is C{float} or C{int}.
1974 @note: If the C{residual is INT0}, the C{fsum} is considered
1975 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
1976 '''
1977 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
1978 _Units_ = (_Float_Int, _Float_Int)
1980 def __abs__(self): # in .fmath
1981 return self._Fsum.__abs__()
1983 def __bool__(self): # PYCHOK Python 3+
1984 return bool(self._Fsum)
1986 def __eq__(self, other):
1987 return self._other_op(other, self.__eq__)
1989 def __float__(self):
1990 return self._Fsum.__float__()
1992 def __ge__(self, other):
1993 return self._other_op(other, self.__ge__)
1995 def __gt__(self, other):
1996 return self._other_op(other, self.__gt__)
1998 def __le__(self, other):
1999 return self._other_op(other, self.__le__)
2001 def __lt__(self, other):
2002 return self._other_op(other, self.__lt__)
2004 def __int__(self):
2005 return self._Fsum.__int__()
2007 def __ne__(self, other):
2008 return self._other_op(other, self.__ne__)
2010 def __neg__(self):
2011 return self._Fsum.__neg__()
2013 __nonzero__ = __bool__ # Python 2-
2015 def __pos__(self):
2016 return self._Fsum.__pos__()
2018 def as_integer_ratio(self):
2019 '''Return this instance as the ratio of 2 integers.
2021 @see: Method L{Fsum.as_integer_ratio} for further details.
2022 '''
2023 return self._Fsum.as_integer_ratio()
2025 @property_RO
2026 def _fint2(self):
2027 return self._Fsum._fint2
2029 @property_RO
2030 def _fprs2(self):
2031 return self._Fsum._fprs2
2033 @Property_RO
2034 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}
2035 s, r = _s_r(*self)
2036 ps = (r, s) if r else (s,)
2037 return _Psum(ps, name=self.name)
2039 def Fsum_(self, *xs, **name_RESIDUAL):
2040 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2041 '''
2042 f = _Psum(self._Fsum._ps, **name_RESIDUAL)
2043 return f._facc_1(xs, up=False) if xs else f
2045 def is_exact(self):
2046 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2047 '''
2048 return self._Fsum.is_exact()
2050 def is_integer(self):
2051 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2052 '''
2053 return self._Fsum.is_integer()
2055 def _mul_scalar(self, other, op): # for Fsum._fmul
2056 return self._Fsum._mul_scalar(other, op)
2058 @property_RO
2059 def _n(self):
2060 return self._Fsum._n
2062 def _other_op(self, other, which):
2063 C, s = (_Tuple, self) if _isAn(other, _Tuple) else (Fsum, self._Fsum)
2064 return getattr(C, which.__name__)(s, other)
2066 @property_RO
2067 def _ps(self):
2068 return self._Fsum._ps
2070 @property_RO
2071 def _ps_neg(self):
2072 return self._Fsum._ps_neg
2074 def signOf(self, **res):
2075 '''Like method L{Fsum.signOf}.
2076 '''
2077 return self._Fsum.signOf(**res)
2079 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2080 '''Return this L{Fsum2Tuple} as string (C{str}).
2082 @kwarg fmt: Optional C{float} format (C{letter}).
2083 @kwarg prec_sep: Optional keyword arguments for function
2084 L{fstr<streprs.fstr>}.
2085 '''
2086 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2088_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK in .fstats
2091class ResidualError(_ValueError):
2092 '''Error raised for a division, power or root operation of
2093 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2094 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2096 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2097 '''
2098 pass
2101try:
2102 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2104 # make sure _fsum works as expected (XXX check
2105 # float.__getformat__('float')[:4] == 'IEEE'?)
2106 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2107 del _fsum # nope, remove _fsum ...
2108 raise ImportError # ... use _fsum below
2110 Fsum._math_fsum = _sum = _fsum # PYCHOK exported
2111except ImportError:
2112 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic
2114 def _fsum(xs):
2115 '''(INTERNAL) Precision summation, Python 2.5-.
2116 '''
2117 F = Fsum()
2118 F.name = _fsum.__name__
2119 return F._facc(xs, up=False)._fprs2.fsum
2122def fsum(xs, floats=False):
2123 '''Precision floating point summation based on/like Python's C{math.fsum}.
2125 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2126 instance).
2127 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2128 be scalar} (C{bool}).
2130 @return: Precision C{fsum} (C{float}).
2132 @raise OverflowError: Partial C{2sum} overflow.
2134 @raise TypeError: Non-scalar B{C{xs}} item.
2136 @raise ValueError: Invalid or non-finite B{C{xs}} item.
2138 @note: Exception and I{non-finite} handling may differ if not based
2139 on Python's C{math.fsum}.
2141 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.
2142 '''
2143 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield
2146def fsum_(*xs, **floats):
2147 '''Precision floating point summation of all positional items.
2149 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2150 all positional.
2151 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2152 be scalar} (C{bool}).
2154 @see: Function L{fsum<fsums.fsum>} for further details.
2155 '''
2156 return _fsum(xs if _xkwds_get(floats, floats=False) is True else
2157 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield
2160def fsumf_(*xs):
2161 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2163 @see: Function L{fsum_<fsums.fsum_>} for further details.
2164 '''
2165 return _fsum(xs) if xs else _0_0
2168def fsum1(xs, floats=False):
2169 '''Precision floating point summation, 1-primed.
2171 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2172 instance).
2173 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2174 be scalar} (C{bool}).
2176 @see: Function L{fsum<fsums.fsum>} for further details.
2177 '''
2178 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield
2181def fsum1_(*xs, **floats):
2182 '''Precision floating point summation, 1-primed of all positional items.
2184 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2185 all positional.
2186 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2187 be scalar} (C{bool}).
2189 @see: Function L{fsum_<fsums.fsum_>} for further details.
2190 '''
2191 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) is True else
2192 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield
2195def fsum1f_(*xs):
2196 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2198 @see: Function L{fsum_<fsums.fsum_>} for further details.
2199 '''
2200 return _fsum(_1primed(xs)) if xs else _0_0
2203if __name__ == '__main__':
2205 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums
2207 if _getenv(_psum.__name__, NN) == _fsum.__name__:
2208 _psum = _fsum
2210 def _test(n):
2211 # copied from Hettinger, see L{Fsum} reference
2212 from pygeodesy import frandoms, printf
2214 printf(_fsum.__name__, end=_COMMASPACE_)
2215 printf(_psum.__name__, end=_COMMASPACE_)
2217 F = Fsum()
2218 if F.is_math_fsum():
2219 for t in frandoms(n, seeded=True):
2220 assert _Float(F.fset_(*t)) == _fsum(t)
2221 printf(_DOT_, end=NN)
2222 printf(NN)
2224 _test(128)
2226# **) MIT License
2227#
2228# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
2229#
2230# Permission is hereby granted, free of charge, to any person obtaining a
2231# copy of this software and associated documentation files (the "Software"),
2232# to deal in the Software without restriction, including without limitation
2233# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2234# and/or sell copies of the Software, and to permit persons to whom the
2235# Software is furnished to do so, subject to the following conditions:
2236#
2237# The above copyright notice and this permission notice shall be included
2238# in all copies or substantial portions of the Software.
2239#
2240# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2241# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2242# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2243# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2244# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2245# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2246# OTHER DEALINGS IN THE SOFTWARE.