Coverage for pygeodesy/fsums.py: 95%
949 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-09-11 15:06 -0400
« prev ^ index » next coverage.py v7.6.0, created at 2024-09-11 15:06 -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}.
7Class L{Fsum} also supports accurate multiplication for Python 3.13 and
8later, but as an option for older Python versions. For more details, see
9method L{f2product<Fsum.f2product>}, class L{Fsum2product} and U{Accurate
10Sum and Dot Product<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.
12Generally, an L{Fsum} instance is considered a C{float} plus a small or zero
13C{residual} value, see property L{Fsum.residual}. However, there are several
14C{integer} L{Fsum} cases, for example the result of C{ceil}, C{floor},
15C{Fsum.__floordiv__} and methods L{Fsum.fint} and L{Fsum.fint2}.
17Also, L{Fsum} methods L{Fsum.pow}, L{Fsum.__ipow__}, L{Fsum.__pow__} and
18L{Fsum.__rpow__} return a (very long) C{int} if invoked with optional argument
19C{mod} set to C{None}. The C{residual} of an C{integer} L{Fsum} may be between
20C{-1.0} and C{+1.0}, including C{INT0} if considered to be I{exact}.
22Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater than
23C{"0.0"} as the threshold to throw a L{ResidualError} for a division, power or
24root operation of an L{Fsum} instance with a C{residual} I{ratio} exceeding
25the threshold. See methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
26and L{Fsum.__itruediv__}.
27'''
28# make sure int/int division yields float quotient, see .basics
29from __future__ import division as _; del _ # PYCHOK semicolon
31from pygeodesy.basics import isbool, iscomplex, isint, isscalar, \
32 _signOf, itemsorted, signOf, _xiterable, \
33 _xiterablen
34from pygeodesy.constants import INT0, _isfinite, MANT_DIG, NEG0, _pos_self, \
35 _0_0, _1_0, _N_1_0, Float, Int
36from pygeodesy.errors import _OverflowError, _TypeError, _UnexpectedError, \
37 _ValueError, _xError, _xError2, _xkwds_get1, \
38 _xkwds_pop2
39from pygeodesy.internals import _enquote, _passarg
40from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _DOT_, \
41 _EQUAL_, _from_, _LANGLE_, _NOTEQUAL_, \
42 _not_finite_, _PERCENT_, _PLUS_, \
43 _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_
44from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
45from pygeodesy.named import _name__, _name2__, _Named, _NamedTuple, \
46 _NotImplemented
47from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \
48 Property, Property_RO, property_RO
49from pygeodesy.streprs import Fmt, fstr, unstr
50# from pygeodesy.units import Float, Int # from .constants
52from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp
54__all__ = _ALL_LAZY.fsums
55__version__ = '24.09.10'
57_add_op_ = _PLUS_ # in .auxilats.auxAngle
58_eq_op_ = _EQUAL_ * 2 # _DEQUAL_
59_div_ = 'div'
60_floordiv_op_ = _SLASH_ * 2 # _DSLASH_
61_fset_op_ = _EQUAL_
62_ge_op_ = _RANGLE_ + _EQUAL_
63_gt_op_ = _RANGLE_
64_iadd_op_ = _add_op_ + _EQUAL_ # in .auxilats.auxAngle, .fstats
65_integer_ = 'integer'
66_le_op_ = _LANGLE_ + _EQUAL_
67_lt_op_ = _LANGLE_
68_mod_ = 'mod'
69_mod_op_ = _PERCENT_
70_mul_op_ = _STAR_
71_ne_op_ = _NOTEQUAL_
72_non_zero_ = 'non-zero'
73_pow_op_ = _STAR_ * 2 # _DSTAR_
74_significant_ = 'significant'
75_sub_op_ = _DASH_ # in .auxilats.auxAngle
76_threshold_ = 'threshold'
77_truediv_op_ = _SLASH_
78_divmod_op_ = _floordiv_op_ + _mod_op_
79_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle
82def _2delta(*ab):
83 '''(INTERNAL) Helper for C{Fsum._fsum2}.
84 '''
85 try:
86 a, b = _2sum(*ab)
87 except _OverflowError:
88 a, b = ab
89 return float(a if fabs(a) > fabs(b) else b)
92def _2error(unused): # in .fstats
93 '''(INTERNAL) Throw a C{not-finite} exception.
94 '''
95 raise ValueError(_not_finite_)
98def _2finite(x):
99 '''(INTERNAL) return C{float(x)} if finite.
100 '''
101 x = float(x)
102 return x if _isfinite(x) else _2error(x)
105def _2float(index=None, **name_value): # in .fmath, .fstats
106 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.
107 '''
108 n, v = name_value.popitem() # _xkwds_item2(name_value)
109 try:
110 return _2finite(v)
111 except Exception as X:
112 raise _xError(X, Fmt.INDEX(n, index), v)
115def _X_ps(X): # for _2floats only
116 return X._ps
119def _2floats(xs, origin=0, _X=_X_ps, _x=float):
120 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
121 '''
122 try:
123 i, x = origin, _X
124 _fin = _isfinite
125 _FsT = _Fsum_Fsum2Tuple_types
126 _isa = isinstance
127 for x in _xiterable(xs):
128 if _isa(x, _FsT):
129 for p in _X(x._Fsum):
130 yield p
131 else:
132 f = _x(x)
133 yield f if _fin(f) else _2error(f)
134 i += 1
135 except Exception as X:
136 raise _xError(X, xs=xs) if x is _X else \
137 _xError(X, Fmt.INDEX(xs=i), x)
140try: # MCCABE 14
141 from math import fma as _fma
143 def _2products(x, ys, **unused):
144 # TwoProductFMA U{Algorithm 3.5
145 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
146 for y in ys:
147 f = x * y
148 yield f
149 yield _fma(x, y, -f)
151 _2split3s = _passarg # NOP
153except ImportError: # Python 3.12-
155 def _fma(*a_b_c): # in .fmath
156 # mimick C{math.fma} from Python 3.13+
157 # <https://MomentsInGraphics.De/FMA.html>
158 # >>> a = 1.00000011920929
159 # >>> b = 53400708
160 # >>> c = -b
161 # >>> _fma(a, b, c)
162 # 6.365860485903399
163 # >>> (a * b) + c
164 # 6.3658604845404625
166 def _as_n_d(x):
167 try:
168 if _isfinite(x):
169 # int.as_integer_ratio since 3.8
170 return x.as_integer_ratio()
171 except (AttributeError, OverflowError, TypeError, ValueError):
172 pass
173 return float(x), 1
175 (na, da), (nb, db), (nc, dc) = map(_as_n_d, a_b_c)
176 n = na * nb * dc + da * db * nc
177 d = da * db * dc
178 return float(n / d)
180 def _2products(x, y3s, two=False): # PYCHOK redef
181 # TwoProduct U{Algorithm 3.3
182 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
183 _, a, b = _2split3(x)
184 for y, c, d in y3s:
185 y *= x
186 yield y
187 if two:
188 yield b * d - (((y - a * c) - b * c) - a * d)
189# = b * d + (a * d - ((y - a * c) - b * c))
190# = b * d + (a * d + (b * c - (y - a * c)))
191# = b * d + (a * d + (b * c + (a * c - y)))
192 else:
193 yield a * c - y
194 yield b * c
195 if d:
196 yield a * d
197 yield b * d
199 _2FACTOR = pow(2, (MANT_DIG + 1) // 2) + 1
201 def _2split3(x):
202 # Split U{Algorithm 3.2
203 # <ttps://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
204 a = c = x * _2FACTOR
205 a -= c - x
206 b = x - a
207 return x, a, b
209 def _2split3s(xs): # PYCHOK redef
210 return map(_2split3, xs)
212del MANT_DIG
215def _Fsumf_(*xs): # floats=True, in .auxLat, ...
216 '''(INTERNAL) An C{Fsum} of I{known scalars}.
217 '''
218 return Fsum()._facc_scalar(xs, up=False)
221def _Fsum1f_(*xs): # floats=True, in .albers, ...
222 '''(INTERNAL) An C{Fsum} of I{known scalars}, 1-primed.
223 '''
224 return Fsum()._facc_scalar(_1primed(xs), up=False)
227def _2halfeven(s, r, p):
228 '''(INTERNAL) Round half-even.
229 '''
230 if (p > 0 and r > 0) or \
231 (p < 0 and r < 0): # signs match
232 r *= 2
233 t = s + r
234 if r == (t - s):
235 s = t
236 return s
239def _isFsum(x): # in .fmath
240 '''(INTERNAL) Is C{x} an C{Fsum} instance?
241 '''
242 return isinstance(x, Fsum)
245def _isFsumTuple(x): # in .fmath
246 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance?
247 '''
248 return isinstance(x, _Fsum_Fsum2Tuple_types)
251def _1_Over(x, op, **raiser_RESIDUAL): # vs _1_over
252 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
253 '''
254 return _Psum_(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
257def _1primed(xs): # in .fmath
258 '''(INTERNAL) 1-Primed summation of iterable C{xs}
259 items, all I{known} to be C{scalar}.
260 '''
261 yield _1_0
262 for x in xs:
263 yield x
264 yield _N_1_0
267def _psum(ps): # PYCHOK used!
268 '''(INTERNAL) Partials summation, updating C{ps}.
269 '''
270 # assert isinstance(ps, list)
271 i = len(ps) - 1
272 s = _0_0 if i < 0 else ps[i]
273 _2s = _2sum
274 while i > 0:
275 i -= 1
276 s, r = _2s(s, ps[i])
277 if r: # sum(ps) became inexact
278 if s:
279 ps[i:] = r, s
280 if i > 0:
281 s = _2halfeven(s, r, ps[i-1])
282 break # return s
283 s = r # PYCHOK no cover
284 ps[i:] = s,
285 return s
288def _Psum(ps, **name_RESIDUAL):
289 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
290 '''
291 f = Fsum(**name_RESIDUAL) if name_RESIDUAL else Fsum()
292 if ps:
293 f._ps[:] = ps
294 f._n = len(f._ps)
295 return f
298def _Psum_(*ps, **name_RESIDUAL):
299 '''(INTERNAL) Return an C{Fsum} from 1 or 2 known scalar(s) C{ps}.
300 '''
301 return _Psum(ps, **name_RESIDUAL)
304def _2scalar2(other):
305 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
306 C{float} or C{as-is} and C{r} the residual of C{as-is}.
307 '''
308 if _isFsumTuple(other):
309 s, r = other._fint2
310 if r:
311 s, r = other._fprs2
312 if r: # PYCHOK no cover
313 s = other # L{Fsum} as-is
314 else:
315 r = 0
316 s = other # C{type} as-is
317 if isint(s, both=True):
318 s = int(s)
319 return s, r
322def _s_r(s, r):
323 '''(INTERNAL) Return C{(s, r)}, I{ordered}.
324 '''
325 if r:
326 if fabs(s) < fabs(r):
327 s, r = r, (s or INT0)
328 else:
329 r = INT0
330 return s, r
333def _strcomplex(s, *args):
334 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
335 '''
336 c = _strcomplex.__name__[4:]
337 n = _DASH_(len(args), _arg_)
338 t = unstr(pow, *args)
339 return _SPACE_(c, s, _from_, n, t)
342def _stresidual(prefix, residual, R=0, **mod_ratio):
343 '''(INTERNAL) Residual error txt C{str}.
344 '''
345 p = _stresidual.__name__[3:]
346 t = Fmt.PARENSPACED(p, Fmt(residual))
347 for n, v in itemsorted(mod_ratio):
348 p = Fmt.PARENSPACED(n, Fmt(v))
349 t = _COMMASPACE_(t, p)
350 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_)
353def _2sum(a, b): # by .testFmath
354 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual).
355 '''
356 # Neumaier, A. U{Rundungsfehleranalyse einiger Verfahren zur Summation endlicher
357 # Summen<https://OnlineLibrary.Wiley.com/doi/epdf/10.1002/zamm.19740540106>},
358 # 1974, Zeitschrift für Angewandte Mathmatik und Mechanik, vol 51, nr 1, p 39-51
359 # <https://StackOverflow.com/questions/78633770/can-neumaier-summation-be-sped-up>
360 s = a + b
361 if _isfinite(s):
362 if fabs(a) < fabs(b):
363 r = (b - s) + a
364 else:
365 r = (a - s) + b
366 return s, r
367 u = unstr(_2sum, a, b)
368 t = Fmt.PARENSPACED(_not_finite_, s)
369 raise _OverflowError(u, txt=t)
372def _threshold(threshold=_0_0, **kwds):
373 '''(INTERNAL) Get the L{ResidualError}s threshold,
374 optionally from single kwds C{B{RESIDUAL}=scalar}.
375 '''
376 if kwds:
377 threshold, kwds = _xkwds_pop2(kwds, RESIDUAL=threshold)
378# threshold = kwds.pop('RESIDUAL', threshold)
379 if kwds:
380 raise _UnexpectedError(**kwds)
381 try:
382 return _2finite(threshold) # PYCHOK None
383 except Exception as x:
384 raise ResidualError(threshold=threshold, cause=x)
387class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase
388 '''Precision floating point summation and I{running} summation.
390 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
391 I{running}, precision floating point summations. Accumulation may continue after any
392 intermediate, I{running} summuation.
394 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances,
395 any C{type} having method C{__float__} to convert the C{scalar} to a single
396 C{float}, except C{complex}.
398 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from
399 Python's C{math.fsum}.
401 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/
402 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>},
403 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
404 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
405 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
406 <https://Bugs.Python.org/issue2819>}.
407 '''
408 _f2product = _2split3s is _passarg # True for 3.13+
409 _math_fma = _fma if _f2product else None
410 _math_fsum = None
411 _n = 0
412# _ps = [] # partial sums
413# _ps_max = 0 # max(Fsum._ps_max, len(Fsum._ps))
414 _RESIDUAL = _threshold(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0))
416 def __init__(self, *xs, **name_RESIDUAL):
417 '''New L{Fsum} for I{running} precision floating point summation.
419 @arg xs: No, one or more initial items to add (each C{scalar} or
420 an L{Fsum} or L{Fsum2Tuple} instance), all positional.
421 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) for this
422 L{Fsum} and the C{B{RESIDUAL}=0.0} threshold for
423 L{ResidualError}s (C{scalar}).
425 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.
426 '''
427 if name_RESIDUAL:
428 n, kwds = _name2__(**name_RESIDUAL)
429 if kwds:
430 R = Fsum._RESIDUAL
431 t = _threshold(R, **kwds)
432 if t != R:
433 self._RESIDUAL = t
434 if n:
435 self.name = n
437 self._ps = [] # [_0_0], see L{Fsum._fprs}
438 if xs:
439 self._facc_1(xs, up=False)
441 def __abs__(self):
442 '''Return this instance' absolute value as an L{Fsum}.
443 '''
444 s = self.signOf() # == self._cmp_0(0)
445 return (-self) if s < 0 else self._copy_2(self.__abs__)
447 def __add__(self, other):
448 '''Return C{B{self} + B{other}} as an L{Fsum}.
450 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
452 @return: The sum (L{Fsum}).
454 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
455 '''
456 f = self._copy_2(self.__add__)
457 return f._fadd(other, _add_op_)
459 def __bool__(self): # PYCHOK Python 3+
460 '''Return C{True} if this instance is I{exactly} non-zero.
461 '''
462 s, r = self._fprs2
463 return bool(s or r) and s != -r # == self != 0
465 def __ceil__(self): # PYCHOK not special in Python 2-
466 '''Return this instance' C{math.ceil} as C{int} or C{float}.
468 @return: An C{int} in Python 3+, but C{float} in Python 2-.
470 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
471 '''
472 return self.ceil
474 def __cmp__(self, other): # PYCHOK no cover
475 '''Compare this with an other instance or C{scalar}, Python 2-.
477 @return: -1, 0 or +1 (C{int}).
479 @raise TypeError: Incompatible B{C{other}} C{type}.
480 '''
481 s = self._cmp_0(other, self.cmp.__name__)
482 return _signOf(s, 0)
484 def __divmod__(self, other, **raiser_RESIDUAL):
485 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
486 with quotient C{div} an C{int} in Python 3+ or C{float}
487 in Python 2- and remainder C{mod} an L{Fsum} instance.
489 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
490 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
491 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
492 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
494 @raise ResidualError: Non-zero, significant residual or invalid
495 B{C{RESIDUAL}}.
497 @see: Method L{Fsum.fdiv}.
498 '''
499 f = self._copy_2(self.__divmod__)
500 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
502 def __eq__(self, other):
503 '''Compare this with an other instance or C{scalar}.
504 '''
505 return self._cmp_0(other, _eq_op_) == 0
507 def __float__(self):
508 '''Return this instance' current, precision running sum as C{float}.
510 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
511 '''
512 return float(self._fprs)
514 def __floor__(self): # PYCHOK not special in Python 2-
515 '''Return this instance' C{math.floor} as C{int} or C{float}.
517 @return: An C{int} in Python 3+, but C{float} in Python 2-.
519 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
520 '''
521 return self.floor
523 def __floordiv__(self, other):
524 '''Return C{B{self} // B{other}} as an L{Fsum}.
526 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
528 @return: The C{floor} quotient (L{Fsum}).
530 @see: Methods L{Fsum.__ifloordiv__}.
531 '''
532 f = self._copy_2(self.__floordiv__)
533 return f._floordiv(other, _floordiv_op_)
535 def __format__(self, *other): # PYCHOK no cover
536 '''Not implemented.'''
537 return _NotImplemented(self, *other)
539 def __ge__(self, other):
540 '''Compare this with an other instance or C{scalar}.
541 '''
542 return self._cmp_0(other, _ge_op_) >= 0
544 def __gt__(self, other):
545 '''Compare this with an other instance or C{scalar}.
546 '''
547 return self._cmp_0(other, _gt_op_) > 0
549 def __hash__(self): # PYCHOK no cover
550 '''Return this instance' C{hash}.
551 '''
552 # @see: U{Notes for type implementors<https://docs.Python.org/
553 # 3/library/numbers.html#numbers.Rational>}
554 return hash(self.partials) # tuple.__hash__()
556 def __iadd__(self, other):
557 '''Apply C{B{self} += B{other}} to this instance.
559 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
560 an iterable of several of the former.
562 @return: This instance, updated (L{Fsum}).
564 @raise TypeError: Invalid B{C{other}}, not
565 C{scalar} nor L{Fsum}.
567 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
568 '''
569 try:
570 return self._fadd(other, _iadd_op_)
571 except TypeError:
572 return self._facc_inplace(other, _iadd_op_, self._facc)
574 def __ifloordiv__(self, other):
575 '''Apply C{B{self} //= B{other}} to this instance.
577 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
579 @return: This instance, updated (L{Fsum}).
581 @raise ResidualError: Non-zero, significant residual
582 in B{C{other}}.
584 @raise TypeError: Invalid B{C{other}} type.
586 @raise ValueError: Invalid or non-finite B{C{other}}.
588 @raise ZeroDivisionError: Zero B{C{other}}.
590 @see: Methods L{Fsum.__itruediv__}.
591 '''
592 return self._floordiv(other, _floordiv_op_ + _fset_op_)
594 def __imatmul__(self, other): # PYCHOK no cover
595 '''Not implemented.'''
596 return _NotImplemented(self, other)
598 def __imod__(self, other):
599 '''Apply C{B{self} %= B{other}} to this instance.
601 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
603 @return: This instance, updated (L{Fsum}).
605 @see: Method L{Fsum.__divmod__}.
606 '''
607 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
609 def __imul__(self, other):
610 '''Apply C{B{self} *= B{other}} to this instance.
612 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
614 @return: This instance, updated (L{Fsum}).
616 @raise OverflowError: Partial C{2sum} overflow.
618 @raise TypeError: Invalid B{C{other}} type.
620 @raise ValueError: Invalid or non-finite B{C{other}}.
621 '''
622 return self._fmul(other, _mul_op_ + _fset_op_)
624 def __int__(self):
625 '''Return this instance as an C{int}.
627 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
628 and L{Fsum.floor}.
629 '''
630 i, _ = self._fint2
631 return i
633 def __invert__(self): # PYCHOK no cover
634 '''Not implemented.'''
635 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
636 return _NotImplemented(self)
638 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
639 '''Apply C{B{self} **= B{other}} to this instance.
641 @arg other: The exponent (C{scalar}, L{Fsum} or L{Fsum2Tuple}).
642 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
643 C{pow(B{self}, B{other}, B{mod})} version.
644 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
645 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
646 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
648 @return: This instance, updated (L{Fsum}).
650 @note: If B{C{mod}} is given, the result will be an C{integer}
651 L{Fsum} in Python 3+ if this instance C{is_integer} or
652 set to C{as_integer} and B{C{mod}} is given and C{None}.
654 @raise OverflowError: Partial C{2sum} overflow.
656 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
657 is non-zero and significant and either
658 B{C{other}} is a fractional or negative
659 C{scalar} or B{C{mod}} is given and not
660 C{None}.
662 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
663 invocation failed.
665 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
666 instance is C{0} or B{C{other}} is a fractional
667 C{scalar} and this instance is negative or has a
668 non-zero and significant residual or B{C{mod}}
669 is given as C{0}.
671 @see: CPython function U{float_pow<https://GitHub.com/
672 python/cpython/blob/main/Objects/floatobject.c>}.
673 '''
674 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
676 def __isub__(self, other):
677 '''Apply C{B{self} -= B{other}} to this instance.
679 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
680 an iterable of several of the former.
682 @return: This instance, updated (L{Fsum}).
684 @raise TypeError: Invalid B{C{other}} type.
686 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
687 '''
688 try:
689 return self._fsub(other, _isub_op_)
690 except TypeError:
691 return self._facc_inplace(other, _isub_op_, self._facc_neg)
693 def __iter__(self):
694 '''Return an C{iter}ator over a C{partials} duplicate.
695 '''
696 return iter(self.partials)
698 def __itruediv__(self, other, **raiser_RESIDUAL):
699 '''Apply C{B{self} /= B{other}} to this instance.
701 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
702 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
703 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
704 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
706 @return: This instance, updated (L{Fsum}).
708 @raise OverflowError: Partial C{2sum} overflow.
710 @raise ResidualError: Non-zero, significant residual or invalid
711 B{C{RESIDUAL}}.
713 @raise TypeError: Invalid B{C{other}} type.
715 @raise ValueError: Invalid or non-finite B{C{other}}.
717 @raise ZeroDivisionError: Zero B{C{other}}.
719 @see: Method L{Fsum.__ifloordiv__}.
720 '''
721 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
723 def __le__(self, other):
724 '''Compare this with an other instance or C{scalar}.
725 '''
726 return self._cmp_0(other, _le_op_) <= 0
728 def __len__(self):
729 '''Return the number of values accumulated (C{int}).
730 '''
731 return self._n
733 def __lt__(self, other):
734 '''Compare this with an other instance or C{scalar}.
735 '''
736 return self._cmp_0(other, _lt_op_) < 0
738 def __matmul__(self, other): # PYCHOK no cover
739 '''Not implemented.'''
740 return _NotImplemented(self, other)
742 def __mod__(self, other):
743 '''Return C{B{self} % B{other}} as an L{Fsum}.
745 @see: Method L{Fsum.__imod__}.
746 '''
747 f = self._copy_2(self.__mod__)
748 return f._fdivmod2(other, _mod_op_).mod
750 def __mul__(self, other):
751 '''Return C{B{self} * B{other}} as an L{Fsum}.
753 @see: Method L{Fsum.__imul__}.
754 '''
755 f = self._copy_2(self.__mul__)
756 return f._fmul(other, _mul_op_)
758 def __ne__(self, other):
759 '''Compare this with an other instance or C{scalar}.
760 '''
761 return self._cmp_0(other, _ne_op_) != 0
763 def __neg__(self):
764 '''Return I{a copy of} this instance, I{negated}.
765 '''
766 f = self._copy_2(self.__neg__)
767 return f._fset(self._neg)
769 def __pos__(self):
770 '''Return this instance I{as-is}, like C{float.__pos__()}.
771 '''
772 return self if _pos_self else self._copy_2(self.__pos__)
774 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
775 '''Return C{B{self}**B{other}} as an L{Fsum}.
777 @see: Method L{Fsum.__ipow__}.
778 '''
779 f = self._copy_2(self.__pow__)
780 return f._fpow(other, _pow_op_, *mod)
782 def __radd__(self, other):
783 '''Return C{B{other} + B{self}} as an L{Fsum}.
785 @see: Method L{Fsum.__iadd__}.
786 '''
787 f = self._copy_2r(other, self.__radd__)
788 return f._fadd(self, _add_op_)
790 def __rdivmod__(self, other):
791 '''Return C{divmod(B{other}, B{self})} as 2-tuple
792 C{(quotient, remainder)}.
794 @see: Method L{Fsum.__divmod__}.
795 '''
796 f = self._copy_2r(other, self.__rdivmod__)
797 return f._fdivmod2(self, _divmod_op_)
799# def __repr__(self):
800# '''Return the default C{repr(this)}.
801# '''
802# return self.toRepr(lenc=True)
804 def __rfloordiv__(self, other):
805 '''Return C{B{other} // B{self}} as an L{Fsum}.
807 @see: Method L{Fsum.__ifloordiv__}.
808 '''
809 f = self._copy_2r(other, self.__rfloordiv__)
810 return f._floordiv(self, _floordiv_op_)
812 def __rmatmul__(self, other): # PYCHOK no cover
813 '''Not implemented.'''
814 return _NotImplemented(self, other)
816 def __rmod__(self, other):
817 '''Return C{B{other} % B{self}} as an L{Fsum}.
819 @see: Method L{Fsum.__imod__}.
820 '''
821 f = self._copy_2r(other, self.__rmod__)
822 return f._fdivmod2(self, _mod_op_).mod
824 def __rmul__(self, other):
825 '''Return C{B{other} * B{self}} as an L{Fsum}.
827 @see: Method L{Fsum.__imul__}.
828 '''
829 f = self._copy_2r(other, self.__rmul__)
830 return f._fmul(self, _mul_op_)
832 def __round__(self, *ndigits): # PYCHOK Python 3+
833 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
835 @arg ndigits: Optional number of digits (C{int}).
836 '''
837 f = self._copy_2(self.__round__)
838 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
839 return f._fset(round(float(self), *ndigits)) # can be C{int}
841 def __rpow__(self, other, *mod):
842 '''Return C{B{other}**B{self}} as an L{Fsum}.
844 @see: Method L{Fsum.__ipow__}.
845 '''
846 f = self._copy_2r(other, self.__rpow__)
847 return f._fpow(self, _pow_op_, *mod)
849 def __rsub__(self, other):
850 '''Return C{B{other} - B{self}} as L{Fsum}.
852 @see: Method L{Fsum.__isub__}.
853 '''
854 f = self._copy_2r(other, self.__rsub__)
855 return f._fsub(self, _sub_op_)
857 def __rtruediv__(self, other, **raiser_RESIDUAL):
858 '''Return C{B{other} / B{self}} as an L{Fsum}.
860 @see: Method L{Fsum.__itruediv__}.
861 '''
862 f = self._copy_2r(other, self.__rtruediv__)
863 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
865 def __str__(self):
866 '''Return the default C{str(self)}.
867 '''
868 return self.toStr(lenc=True)
870 def __sub__(self, other):
871 '''Return C{B{self} - B{other}} as an L{Fsum}.
873 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
875 @return: The difference (L{Fsum}).
877 @see: Method L{Fsum.__isub__}.
878 '''
879 f = self._copy_2(self.__sub__)
880 return f._fsub(other, _sub_op_)
882 def __truediv__(self, other, **raiser_RESIDUAL):
883 '''Return C{B{self} / B{other}} as an L{Fsum}.
885 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
886 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
887 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
888 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
890 @return: The quotient (L{Fsum}).
892 @raise ResidualError: Non-zero, significant residual or invalid
893 B{C{RESIDUAL}}.
895 @see: Method L{Fsum.__itruediv__}.
896 '''
897 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
899 __trunc__ = __int__
901 if _sys_version_info2 < (3, 0): # PYCHOK no cover
902 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
903 __div__ = __truediv__
904 __idiv__ = __itruediv__
905 __long__ = __int__
906 __nonzero__ = __bool__
907 __rdiv__ = __rtruediv__
909 def as_integer_ratio(self):
910 '''Return this instance as the ratio of 2 integers.
912 @return: 2-Tuple C{(numerator, denominator)} both C{int}
913 with C{numerator} signed and C{denominator}
914 non-zero, positive.
916 @see: Standard C{float.as_integer_ratio} in Python 2.7+.
917 '''
918 n, r = self._fint2
919 if r:
920 i, d = float(r).as_integer_ratio()
921 n *= d
922 n += i
923 else: # PYCHOK no cover
924 d = 1
925 return n, d
927 @property_RO
928 def as_iscalar(self):
929 '''Get this instance I{as-is} (L{Fsum} or C{scalar}), the
930 latter only if the C{residual} equals C{zero}.
931 '''
932 s, r = self._fprs2
933 return self if r else s
935 @property_RO
936 def ceil(self):
937 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
938 C{float} in Python 2-).
940 @note: This C{ceil} takes the C{residual} into account.
942 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
943 L{Fsum.imag} and L{Fsum.real}.
944 '''
945 s, r = self._fprs2
946 c = _ceil(s) + int(r) - 1
947 while r > (c - s): # (s + r) > c
948 c += 1
949 return c # _ceil(self._n_d)
951 cmp = __cmp__
953 def _cmp_0(self, other, op):
954 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
955 '''
956 if _isFsumTuple(other):
957 s = self._ps_1sum(*other._ps)
958 elif self._scalar(other, op):
959 s = self._ps_1sum(other)
960 else:
961 s = self.signOf() # res=True
962 return s
964 def copy(self, deep=False, **name):
965 '''Copy this instance, C{shallow} or B{C{deep}}.
967 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}).
969 @return: The copy (L{Fsum}).
970 '''
971 n = _name__(name, name__=self.copy)
972 f = _Named.copy(self, deep=deep, name=n)
973 if f._ps is self._ps:
974 f._ps = list(self._ps) # separate list
975 if not deep:
976 f._n = 1
977 # assert f._f2product == self._f2product
978 # assert f._Fsum is f
979 return f
981 def _copy_2(self, which, name=NN):
982 '''(INTERNAL) Copy for I{dyadic} operators.
983 '''
984 n = name or which.__name__ # _dunder_nameof
985 # NOT .classof due to .Fdot(a, *b) args, etc.
986 f = _Named.copy(self, deep=False, name=n)
987 f._ps = list(self._ps) # separate list
988 # assert f._n == self._n
989 # assert f._f2product == self._f2product
990 # assert f._Fsum is f
991 return f
993 def _copy_2r(self, other, which):
994 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
995 '''
996 return other._copy_2(which) if _isFsum(other) else \
997 self._copy_2(which)._fset(other)
999# def _copy_RESIDUAL(self, other):
1000# '''(INTERNAL) Copy C{other._RESIDUAL}.
1001# '''
1002# R = other._RESIDUAL
1003# if R is not Fsum._RESIDUAL:
1004# self._RESIDUAL = R
1006 divmod = __divmod__
1008 def _Error(self, op, other, Error, **txt_cause):
1009 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
1010 '''
1011 return Error(_SPACE_(self.as_iscalar, op, other), **txt_cause)
1013 def _ErrorX(self, X, op, other, *mod):
1014 '''(INTERNAL) Format the caught exception C{X}.
1015 '''
1016 E, t = _xError2(X)
1017 if mod:
1018 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
1019 return self._Error(op, other, E, txt=t, cause=X)
1021 def _ErrorXs(self, X, xs, **kwds): # in .fmath
1022 '''(INTERNAL) Format the caught exception C{X}.
1023 '''
1024 E, t = _xError2(X)
1025 u = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
1026 return E(u, txt=t, cause=X)
1028 def _facc(self, xs, up=True, **origin_X_x):
1029 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s.
1030 '''
1031 if xs:
1032 _xs = _2floats(xs, **origin_X_x) # PYCHOK yield
1033 ps = self._ps
1034 ps[:] = self._ps_acc(list(ps), _xs, up=up)
1035 return self
1037 def _facc_1(self, xs, **up):
1038 '''(INTERNAL) Accumulate 0, 1 or more C{scalars} or L{Fsum}s,
1039 all positional C{xs} in the caller of this method.
1040 '''
1041 return self._fadd(xs[0], _add_op_, **up) if len(xs) == 1 else \
1042 self._facc(xs, origin=1, **up)
1044 def _facc_inplace(self, other, op, _facc):
1045 '''(INTERNAL) Accumulate from an iterable.
1046 '''
1047 try:
1048 return _facc(other, origin=1) if _xiterable(other) else self
1049 except Exception as X:
1050 raise self._ErrorX(X, op, other)
1052 def _facc_neg(self, xs, **up_origin):
1053 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s, negated.
1054 '''
1055 def _N(X):
1056 return X._ps_neg
1058 def _n(x):
1059 return -float(x)
1061 return self._facc(xs, _X=_N, _x=_n, **up_origin)
1063 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
1064 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
1065 '''
1066 def _Pow4(p):
1067 r = 0
1068 if _isFsumTuple(p):
1069 s, r = p._fprs2
1070 if r:
1071 m = Fsum._pow
1072 else: # scalar
1073 return _Pow4(s)
1074 elif isint(p, both=True) and int(p) >= 0:
1075 p = s = int(p)
1076 m = Fsum._pow_int
1077 else:
1078 p = s = _2float(power=p)
1079 m = Fsum._pow_scalar
1080 return m, p, s, r
1082 _Pow, p, s, r = _Pow4(power)
1083 if p: # and xs:
1084 op = which.__name__
1085 _flt = float
1086 _Fs = Fsum
1087 _isa = isinstance
1088 _pow = self._pow_2_3
1090 def _P(X):
1091 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
1092 return f._ps if _isa(f, _Fs) else (f,)
1094 def _p(x):
1095 x = _flt(x)
1096 f = _pow(x, s, power, op, **raiser_RESIDUAL)
1097 if f and r:
1098 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
1099 return f
1101 f = self._facc(xs, origin=1, _X=_P, _x=_p)
1102 else:
1103 f = self._facc_scalar_(float(len(xs))) # x**0 == 1
1104 return f
1106 def _facc_scalar(self, xs, **up):
1107 '''(INTERNAL) Accumulate all C{xs}, known to be scalar.
1108 '''
1109 if xs:
1110 _ = self._ps_acc(self._ps, xs, **up)
1111 return self
1113 def _facc_scalar_(self, *xs, **up):
1114 '''(INTERNAL) Accumulate all positional C{xs}, known to be scalar.
1115 '''
1116 if xs:
1117 _ = self._ps_acc(self._ps, xs, **up)
1118 return self
1120# def _facc_up(self, up=True):
1121# '''(INTERNAL) Update the C{partials}, by removing
1122# and re-accumulating the final C{partial}.
1123# '''
1124# ps = self._ps
1125# while len(ps) > 1:
1126# p = ps.pop()
1127# if p:
1128# n = self._n
1129# _ = self._ps_acc(ps, (p,), up=False)
1130# self._n = n
1131# break
1132# return self._update() if up else self
1134 def fadd(self, xs=()):
1135 '''Add an iterable's items to this instance.
1137 @arg xs: Iterable of items to add (each C{scalar}
1138 or an L{Fsum} or L{Fsum2Tuple} instance).
1140 @return: This instance (L{Fsum}).
1142 @raise OverflowError: Partial C{2sum} overflow.
1144 @raise TypeError: An invalid B{C{xs}} item.
1146 @raise ValueError: Invalid or non-finite B{C{xs}} value.
1147 '''
1148 if _isFsumTuple(xs):
1149 self._facc_scalar(xs._ps)
1150 elif isscalar(xs): # for backward compatibility
1151 self._facc_scalar_(_2float(x=xs)) # PYCHOK no cover
1152 elif xs: # _xiterable(xs)
1153 self._facc(xs)
1154 return self
1156 def fadd_(self, *xs):
1157 '''Add all positional items to this instance.
1159 @arg xs: Values to add (each C{scalar} or an L{Fsum}
1160 or L{Fsum2Tuple} instance), all positional.
1162 @see: Method L{Fsum.fadd} for further details.
1163 '''
1164 return self._facc_1(xs)
1166 def _fadd(self, other, op, **up): # in .fmath.Fhorner
1167 '''(INTERNAL) Apply C{B{self} += B{other}}.
1168 '''
1169 if not self._ps: # new Fsum(x)
1170 self._fset(other, op=op, **up)
1171 elif _isFsumTuple(other):
1172 self._facc_scalar(other._ps, **up)
1173 elif self._scalar(other, op):
1174 self._facc_scalar_(other, **up)
1175 return self
1177 fcopy = copy # for backward compatibility
1178 fdiv = __itruediv__
1179 fdivmod = __divmod__
1181 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1182 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1183 '''
1184 # result mostly follows CPython function U{float_divmod
1185 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1186 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1187 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1188 if q: # == float // other == floor(float / other)
1189 self -= Fsum(q) * other # NOT other * q!
1191 s = signOf(other) # make signOf(self) == signOf(other)
1192 if s and self.signOf() == -s: # PYCHOK no cover
1193 self += other
1194 q -= 1
1195# t = self.signOf()
1196# if t and t != s:
1197# raise self._Error(op, other, _AssertionError, txt__=signOf)
1198 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1200 def _fhorner(self, x, cs, op, incx=True): # in .fmath
1201 '''(INTERNAL) Add an L{Fhorner} evaluation of polynomial
1202 C{sum(cs[i] * B{x}**i for i=0..len(cs)-1) if B{incx}
1203 else sum(... i=len(cs)-1..0)}.
1204 '''
1205 if _xiterablen(cs):
1206 H = Fsum(name__=self._fhorner)
1207 if _isFsumTuple(x):
1208 _mul = H._mul_Fsum
1209 else:
1210 _mul = H._mul_scalar
1211 x = _2float(x=x)
1212 if len(cs) > 1 and x:
1213 for c in (reversed(cs) if incx else cs):
1214 H._fset_ps(_mul(x, op))
1215 H._fadd(c, op, up=False)
1216 else: # x == 0
1217 H = cs[0] if cs else _0_0
1218 self._fadd(H, op)
1219 return self
1221 def _finite(self, other, op=None):
1222 '''(INTERNAL) Return B{C{other}} if C{finite}.
1223 '''
1224 if _isfinite(other):
1225 return other
1226 raise ValueError(_not_finite_) if op is None else \
1227 self._Error(op, other, _ValueError, txt=_not_finite_)
1229 def fint(self, name=NN, **raiser_RESIDUAL):
1230 '''Return this instance' current running sum as C{integer}.
1232 @kwarg name: Optional, overriding C{B{name}="fint"} (C{str}).
1233 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1234 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1235 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1237 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1238 with a zero or insignificant I{integer} residual.
1240 @raise ResidualError: Non-zero, significant residual or invalid
1241 B{C{RESIDUAL}}.
1243 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1244 '''
1245 i, r = self._fint2
1246 if r:
1247 R = self._raiser(r, i, **raiser_RESIDUAL)
1248 if R:
1249 t = _stresidual(_integer_, r, **R)
1250 raise ResidualError(_integer_, i, txt=t)
1251 return _Psum_(i, name=_name__(name, name__=self.fint))
1253 def fint2(self, **name):
1254 '''Return this instance' current running sum as C{int} and the
1255 I{integer} residual.
1257 @kwarg name: Optional name (C{str}).
1259 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1260 an C{int} and I{integer} C{residual} a C{float} or
1261 C{INT0} if the C{fsum} is considered to be I{exact}.
1262 '''
1263 return Fsum2Tuple(*self._fint2, **name)
1265 @Property
1266 def _fint2(self): # see ._fset
1267 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1268 '''
1269 s, r = self._fprs2
1270 i = int(s)
1271 n = len(self._ps)
1272 r = self._ps_1sum(i) if r and n > 1 else float(s - i)
1273 return i, (r or INT0) # Fsum2Tuple?
1275 @_fint2.setter_ # PYCHOK setter_underscore!
1276 def _fint2(self, s):
1277 '''(INTERNAL) Replace the C{_fint2} value.
1278 '''
1279 i = int(s)
1280 return i, ((s - i) or INT0)
1282 @deprecated_property_RO
1283 def float_int(self): # PYCHOK no cover
1284 '''DEPRECATED, use method C{Fsum.int_float}.'''
1285 return self.int_float() # raiser=False
1287 @property_RO
1288 def floor(self):
1289 '''Get this instance' C{floor} (C{int} in Python 3+, but
1290 C{float} in Python 2-).
1292 @note: This C{floor} takes the C{residual} into account.
1294 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1295 L{Fsum.imag} and L{Fsum.real}.
1296 '''
1297 s, r = self._fprs2
1298 f = _floor(s) + _floor(r) + 1
1299 while (f - s) > r: # f > (s + r)
1300 f -= 1
1301 return f # _floor(self._n_d)
1303# ffloordiv = __ifloordiv__ # for naming consistency
1304# floordiv = __floordiv__ # for naming consistency
1306 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1307 '''Apply C{B{self} //= B{other}}.
1308 '''
1309 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1310 return self._fset(q.floor) # floor(q)
1312 def fma(self, other1, other2): #
1313 '''Fused-multiply-add C{self *= B{other1}; self += B{other2}}.
1315 @arg other1: A C{scalar}, an L{Fsum} or L{Fsum2Tuple} instance.
1316 @arg other2: A C{scalar}, an L{Fsum} or L{Fsum2Tuple} instance.
1318 @note: Uses C{math.fma} in Python 3.13+, provided C{self},
1319 B{C{other1}} and B{C{other2}} are all C{scalar}.
1320 '''
1321 if len(self._ps) == 1 and isscalar(other1, both=True) \
1322 and isscalar(other2, both=True):
1323 p = _fma(self._ps[0], other1, other2)
1324 self._ps[:] = self._finite(p, self.fma.__name__),
1325 if other2:
1326 self._n += 1
1327 else:
1328 self._f2mul(self.fma.__name__, other1)
1329 self += other2
1330 return self
1332# def _fma_scalar(self, op, x, *ys): # in .karney
1333# '''(INTERNAL) Apply C{self.fma(B{x}, B{y}) for B{y} in B{ys}}
1334# for scalar C{x} and C{y}s.
1335# '''
1336# ps = self._ps
1337# if ps and ys:
1338# for y in ys:
1339# ps[:] = self._ps_acc(list(y), _2products(x, _2split3s(ps)))
1340# for p in (ps if op else()):
1341# self._finite(p, op)
1342# return self
1344 fmul = __imul__
1346 def _fmul(self, other, op):
1347 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1348 '''
1349 if _isFsumTuple(other):
1350 if len(self._ps) != 1:
1351 f = self._mul_Fsum(other, op)
1352 elif len(other._ps) != 1: # and len(self._ps) == 1
1353 f = other._mul_scalar(self._ps[0], op)
1354 elif self._f2product: # len(other._ps) == 1
1355 f = self._mul_scalar(other._ps[0], op)
1356 else: # len(other._ps) == len(self._ps) == 1
1357 f = self._finite(self._ps[0] * other._ps[0])
1358 else:
1359 s = self._scalar(other, op)
1360 f = self._mul_scalar(s, op)
1361 return self._fset(f) # n=len(self) + 1
1363 def f2mul(self, *others):
1364 '''Apply C{B{self} *= B{other} for B{other} in B{others}} where each B{other}
1365 is C{scalar}, an L{Fsum} or L{Fsum2Tuple} applying accurate multiplication
1366 as if L{f2product<Fsum.f2product>}C{=True}.
1368 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
1369 '''
1370 return self._f2mul(self.f2mul.__name__, *others)
1372 def _f2mul(self, op, *others):
1373 '''(INTERNAL) See method C{f2mul}.
1374 '''
1375 P = _Psum(self._ps)
1376 ps = P._ps
1377 if ps and others:
1378 for p in self._ps_other(op, *others):
1379 pfs = _2products(p, _2split3s(ps))
1380 ps[:] = P._ps_acc([], pfs, up=False)
1381 for p in ps:
1382 self._finite(p, op)
1383 self._fset(P, op=op)
1384 return self
1386 def fover(self, over, **raiser_RESIDUAL):
1387 '''Apply C{B{self} /= B{over}} and summate.
1389 @arg over: An L{Fsum} or C{scalar} denominator.
1390 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1391 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1392 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1394 @return: Precision running sum (C{float}).
1396 @raise ResidualError: Non-zero, significant residual or invalid
1397 B{C{RESIDUAL}}.
1399 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1400 '''
1401 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1403 fpow = __ipow__
1405 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1406 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1407 '''
1408 if mod:
1409 if mod[0] is not None: # == 3-arg C{pow}
1410 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1411 elif self.is_integer():
1412 # return an exact C{int} for C{int}**C{int}
1413 i, _ = self._fint2 # assert _ == 0
1414 x, r = _2scalar2(other) # C{int}, C{float} or other
1415 f = _Psum_(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1416 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1417 else: # mod[0] is None, power(self, other)
1418 f = self._pow(other, other, op, **raiser_RESIDUAL)
1419 else: # pow(self, other)
1420 f = self._pow(other, other, op, **raiser_RESIDUAL)
1421 return self._fset(f) # n=max(len(self), 1)
1423 def f2product(self, *two):
1424 '''Turn this instance' accurate I{TwoProduct} multiplication or or off.
1426 @arg two: If C{True}, turn I{TwoProduct} on, if C{False} off or if
1427 C{None} or if omitted, keep the current setting.
1429 @return: The previous C{f2product} setting (C{bool}).
1431 @see: On Python 3.13 and later I{TwoProduct} is based on I{TwoProductFMA}
1432 U{Algorithm 3.5<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
1433 otherwise on the slower I{TwoProduct} and I{Split} U{Algorithms
1434 3.3 and 3.2<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.
1435 '''
1436 t = self._f2product
1437 if two and two[0] is not None:
1438 self._f2product = bool(two[0])
1439 return t
1441 @Property
1442 def _fprs(self):
1443 '''(INTERNAL) Get and cache this instance' precision
1444 running sum (C{float} or C{int}), ignoring C{residual}.
1446 @note: The precision running C{fsum} after a C{//=} or
1447 C{//} C{floor} division is C{int} in Python 3+.
1448 '''
1449 s, _ = self._fprs2
1450 return s # ._fprs2.fsum
1452 @_fprs.setter_ # PYCHOK setter_underscore!
1453 def _fprs(self, s):
1454 '''(INTERNAL) Replace the C{_fprs} value.
1455 '''
1456 return s
1458 @Property
1459 def _fprs2(self):
1460 '''(INTERNAL) Get and cache this instance' precision
1461 running sum and residual (L{Fsum2Tuple}).
1462 '''
1463 ps = self._ps
1464 n = len(ps) - 2
1465 if n > 0: # len(ps) > 2
1466 s = _psum(ps)
1467 n = len(ps) - 2
1468 if n > 0:
1469 r = self._ps_1sum(s)
1470 return Fsum2Tuple(*_s_r(s, r))
1471 if n == 0: # len(ps) == 2
1472 s, r = _s_r(*_2sum(*ps))
1473 ps[:] = (r, s) if r else (s,)
1474 elif ps: # len(ps) == 1
1475 s, r = ps[0], INT0
1476 else: # len(ps) == 0
1477 s, r = _0_0, INT0
1478 ps[:] = s,
1479 # assert self._ps is ps
1480 return Fsum2Tuple(s, r)
1482 @_fprs2.setter_ # PYCHOK setter_underscore!
1483 def _fprs2(self, s_r):
1484 '''(INTERNAL) Replace the C{_fprs2} value.
1485 '''
1486 return Fsum2Tuple(s_r)
1488 def fset_(self, *xs):
1489 '''Replace this instance' value with all positional items.
1491 @arg xs: Optional, new values (each C{scalar} or
1492 an L{Fsum} or L{Fsum2Tuple} instance),
1493 all positional.
1495 @return: This instance, replaced (C{Fsum}).
1497 @see: Method L{Fsum.fadd} for further details.
1498 '''
1499 f = xs[0] if len(xs) == 1 else (
1500 Fsum(*xs) if xs else _0_0)
1501 return self._fset(f)
1503 def _fset(self, other, n=0, up=True, **op):
1504 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1505 '''
1506 if other is self:
1507 pass # from ._fmul, ._ftruediv and ._pow_0_1
1508 elif _isFsumTuple(other):
1509 self._ps[:] = other._ps
1510 self._n = n or other._n
1511# self._copy_RESIDUAL(other)
1512 if up: # use or zap the C{Property_RO} values
1513 Fsum._fint2._update_from(self, other)
1514 Fsum._fprs ._update_from(self, other)
1515 Fsum._fprs2._update_from(self, other)
1516 elif isscalar(other):
1517 s = float(self._finite(other, **op)) if op else other
1518 self._ps[:] = s,
1519 self._n = n or 1
1520 if up: # Property _fint2, _fprs and _fprs2 all have
1521 # @.setter_underscore and NOT @.setter because the
1522 # latter's _fset zaps the value set by @.setter
1523 self._fint2 = s
1524 self._fprs = s
1525 self._fprs2 = s, INT0
1526 # assert self._fprs is s
1527 else: # PYCHOK no cover
1528 op = _xkwds_get1(op, op=_fset_op_)
1529 raise self._Error(op, other, _TypeError)
1530 return self
1532 def _fset_ps(self, other): # in .fmath
1533 '''(INTERNAL) Set partials from a known C{scalar}, L{Fsum} or L{Fsum2Tuple}.
1534 '''
1535 return self._fset(other, up=False)
1537 def fsub(self, xs=()):
1538 '''Subtract an iterable's items from this instance.
1540 @see: Method L{Fsum.fadd} for further details.
1541 '''
1542 return self._facc_neg(xs)
1544 def fsub_(self, *xs):
1545 '''Subtract all positional items from this instance.
1547 @see: Method L{Fsum.fadd_} for further details.
1548 '''
1549 return self._fsub(xs[0], _sub_op_) if len(xs) == 1 else \
1550 self._facc_neg(xs, origin=1)
1552 def _fsub(self, other, op):
1553 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1554 '''
1555 if _isFsumTuple(other):
1556 if other is self: # or other._fprs2 == self._fprs2:
1557 self._fset(_0_0, n=len(self) * 2)
1558 elif other._ps:
1559 self._facc_scalar(other._ps_neg)
1560 elif self._scalar(other, op):
1561 self._facc_scalar_(-other)
1562 return self
1564 def fsum(self, xs=()):
1565 '''Add an iterable's items, summate and return the
1566 current precision running sum.
1568 @arg xs: Iterable of items to add (each item C{scalar}
1569 or an L{Fsum} or L{Fsum2Tuple} instance).
1571 @return: Precision running sum (C{float} or C{int}).
1573 @see: Method L{Fsum.fadd}.
1575 @note: Accumulation can continue after summation.
1576 '''
1577 return self._facc(xs)._fprs
1579 def fsum_(self, *xs):
1580 '''Add any positional items, summate and return the
1581 current precision running sum.
1583 @arg xs: Items to add (each C{scalar} or an L{Fsum}
1584 or L{Fsum2Tuple} instance), all positional.
1586 @return: Precision running sum (C{float} or C{int}).
1588 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1589 '''
1590 return self._facc_1(xs)._fprs
1592 @property_RO
1593 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, for C{_2floats}, .fstats
1594 return self # NOT @Property_RO, see .copy and ._copy_2
1596 def Fsum_(self, *xs, **name):
1597 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1599 @kwarg name: Optional name (C{str}).
1601 @return: Copy of this updated instance (L{Fsum}).
1602 '''
1603 return self._facc_1(xs)._copy_2(self.Fsum_, **name)
1605 def Fsum2Tuple_(self, *xs, **name):
1606 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1608 @kwarg name: Optional name (C{str}).
1610 @return: Precision running sum (L{Fsum2Tuple}).
1611 '''
1612 return Fsum2Tuple(self._facc_1(xs)._fprs2, **name)
1614 def fsum2(self, xs=(), **name):
1615 '''Add an iterable's items, summate and return the
1616 current precision running sum I{and} the C{residual}.
1618 @arg xs: Iterable of items to add (each item C{scalar}
1619 or an L{Fsum} or L{Fsum2Tuple} instance).
1620 @kwarg name: Optional C{B{name}=NN} (C{str}).
1622 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1623 current precision running sum and C{residual}, the
1624 (precision) sum of the remaining C{partials}. The
1625 C{residual is INT0} if the C{fsum} is considered
1626 to be I{exact}.
1628 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1629 '''
1630 t = self._facc(xs)._fprs2
1631 return t.dup(name=name) if name else t
1633 def fsum2_(self, *xs):
1634 '''Add any positional items, summate and return the current
1635 precision running sum and the I{differential}.
1637 @arg xs: Values to add (each C{scalar} or an L{Fsum} or
1638 L{Fsum2Tuple} instance), all positional.
1640 @return: 2Tuple C{(fsum, delta)} with the current, precision
1641 running C{fsum} like method L{Fsum.fsum} and C{delta},
1642 the difference with previous running C{fsum}, C{float}.
1644 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1645 '''
1646 return self._fsum2(xs, self._facc_1)
1648 def _fsum2(self, xs, _facc, **origin):
1649 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1650 '''
1651 p, q = self._fprs2
1652 if xs:
1653 s, r = _facc(xs, **origin)._fprs2
1654 return s, _2delta(s - p, r - q) # _fsum(_1primed((s, -p, r, -q))
1655 else:
1656 return p, _0_0
1658 def fsumf_(self, *xs):
1659 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1660 '''
1661 return self._facc_scalar(xs)._fprs
1663 def Fsumf_(self, *xs):
1664 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1665 '''
1666 return self._facc_scalar(xs)._copy_2(self.Fsumf_)
1668 def fsum2f_(self, *xs):
1669 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}} are I{known to be scalar}.
1670 '''
1671 return self._fsum2(xs, self._facc_scalar, origin=1)
1673# ftruediv = __itruediv__ # for naming consistency?
1675 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1676 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1677 '''
1678 n = _1_0
1679 if _isFsumTuple(other):
1680 if other is self or self == other:
1681 return self._fset(n, n=len(self))
1682 d, r = other._fprs2
1683 if r:
1684 R = self._raiser(r, d, **raiser_RESIDUAL)
1685 if R:
1686 raise self._ResidualError(op, other, r, **R)
1687 d, n = other.as_integer_ratio()
1688 else:
1689 d = self._scalar(other, op)
1690 try:
1691 s = n / d
1692 except Exception as X:
1693 raise self._ErrorX(X, op, other)
1694 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1695 return self._fset(f)
1697 @property_RO
1698 def imag(self):
1699 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1701 @see: Property L{Fsum.real}.
1702 '''
1703 return _0_0
1705 def int_float(self, **raiser_RESIDUAL):
1706 '''Return this instance' current running sum as C{int} or C{float}.
1708 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1709 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1710 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1712 @return: This C{integer} sum if this instance C{is_integer},
1713 otherwise return the C{float} sum if the residual is
1714 zero or not significant.
1716 @raise ResidualError: Non-zero, significant residual or invalid
1717 B{C{RESIDUAL}}.
1719 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.RESIDUAL} and
1720 property L{Fsum.as_iscalar}.
1721 '''
1722 s, r = self._fint2
1723 if r:
1724 s, r = self._fprs2
1725 if r: # PYCHOK no cover
1726 R = self._raiser(r, s, **raiser_RESIDUAL)
1727 if R:
1728 t = _stresidual(_non_zero_, r, **R)
1729 raise ResidualError(int_float=s, txt=t)
1730 s = float(s)
1731 return s
1733 def is_exact(self):
1734 '''Is this instance' running C{fsum} considered to be exact?
1735 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1736 '''
1737 return self.residual is INT0
1739 def is_integer(self):
1740 '''Is this instance' running sum C{integer}? (C{bool}).
1742 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1743 '''
1744 _, r = self._fint2
1745 return False if r else True
1747 def is_math_fsum(self):
1748 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and
1749 L{fsum1_} plus partials summation are based on Python's
1750 C{math.fsum} or not.
1752 @return: C{2} if all functions and partials summation
1753 are based on C{math.fsum}, C{True} if only
1754 the functions are based on C{math.fsum} (and
1755 partials summation is not) or C{False} if
1756 none are.
1757 '''
1758 f = Fsum._math_fsum
1759 return 2 if _psum is f else bool(f)
1761 def is_scalar(self, **raiser_RESIDUAL):
1762 '''Is this instance' running sum C{scalar} without residual or with
1763 a residual I{ratio} not exceeding the RESIDUAL threshold?
1765 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1766 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1767 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1769 @return: C{True} if this instance' non-zero residual C{ratio} exceeds
1770 the L{RESIDUAL<Fsum.RESIDUAL>} threshold (C{bool}).
1772 @raise ResidualError: Non-zero, significant residual or invalid
1773 B{C{RESIDUAL}}.
1775 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property
1776 L{Fsum.as_iscalar}.
1777 '''
1778 s, r = self._fprs2
1779 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1781 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1782 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1783 '''
1784 # assert _isFsumTuple(other)
1785 if self._ps and other._ps:
1786 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
1787 else:
1788 f = _0_0
1789 return f
1791 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1792 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
1793 '''
1794 # assert isscalar(factor)
1795 if self._ps and self._finite(factor, op):
1796 f = self if factor == _1_0 else (
1797 self._neg if factor == _N_1_0 else
1798 self._ps_mul(op, factor).as_iscalar)
1799 else:
1800 f = _0_0
1801 return f
1803# @property_RO
1804# def _n_d(self):
1805# n, d = self.as_integer_ratio()
1806# return n / d
1808 @property_RO
1809 def _neg(self):
1810 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
1811 '''
1812 return _Psum(self._ps_neg) if self._ps else NEG0
1814 @property_RO
1815 def partials(self):
1816 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
1817 '''
1818 return tuple(self._ps)
1820 def pow(self, x, *mod, **raiser_RESIDUAL):
1821 '''Return C{B{self}**B{x}} as L{Fsum}.
1823 @arg x: The exponent (C{scalar} or L{Fsum}).
1824 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
1825 C{pow(B{self}, B{other}, B{mod})} version.
1826 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1827 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1828 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1830 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
1831 result (L{Fsum}).
1833 @raise ResidualError: Non-zero, significant residual or invalid
1834 B{C{RESIDUAL}}.
1836 @note: If B{C{mod}} is given and C{None}, the result will be an
1837 C{integer} L{Fsum} provided this instance C{is_integer}
1838 or set to C{integer} by an L{Fsum.fint} call.
1840 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
1841 and L{Fsum.root}.
1842 '''
1843 f = self._copy_2(self.pow)
1844 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
1846 def _pow(self, other, unused, op, **raiser_RESIDUAL):
1847 '''Return C{B{self} ** B{other}}.
1848 '''
1849 if _isFsumTuple(other):
1850 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
1851 elif self._scalar(other, op):
1852 x = self._finite(other, op)
1853 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1854 else:
1855 f = self._pow_0_1(0, other)
1856 return f
1858 def _pow_0_1(self, x, other):
1859 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
1860 '''
1861 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
1863 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
1864 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
1865 B{x}, int B{mod} or C{None})}, embellishing errors.
1866 '''
1868 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
1869 m = mod[0]
1870 # assert _isFsumTuple(b)
1872 def _s(s, r):
1873 R = self._raiser(r, s, **raiser_RESIDUAL)
1874 if R:
1875 raise self._ResidualError(op, other, r, mod=m, **R)
1876 return s
1878 b = _s(*(b._fprs2 if m is None else b._fint2))
1879 x = _s(*_2scalar2(x))
1881 try:
1882 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
1883 s = pow(b, x, *mod)
1884 if iscomplex(s):
1885 # neg**frac == complex in Python 3+, but ValueError in 2-
1886 raise ValueError(_strcomplex(s, b, x, *mod))
1887 return self._finite(s)
1888 except Exception as X:
1889 raise self._ErrorX(X, op, other, *mod)
1891 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
1892 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsumTuple(other)}.
1893 '''
1894 # assert _isFsumTuple(other)
1895 x, r = other._fprs2
1896 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
1897 if f and r:
1898 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
1899 return f
1901 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
1902 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
1903 '''
1904 # assert isint(x) and x >= 0
1905 ps = self._ps
1906 if len(ps) > 1:
1907 _mul_Fsum = Fsum._mul_Fsum
1908 if x > 4:
1909 p = self
1910 f = self if (x & 1) else _Psum_(_1_0)
1911 m = x >> 1 # // 2
1912 while m:
1913 p = _mul_Fsum(p, p, op) # p **= 2
1914 if (m & 1):
1915 f = _mul_Fsum(f, p, op) # f *= p
1916 m >>= 1 # //= 2
1917 elif x > 1: # self**2, 3, or 4
1918 f = _mul_Fsum(self, self, op)
1919 if x > 2: # self**3 or 4
1920 p = self if x < 4 else f
1921 f = _mul_Fsum(f, p, op)
1922 else: # self**1 or self**0 == 1 or _1_0
1923 f = self._pow_0_1(x, other)
1924 elif ps: # self._ps[0]**x
1925 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
1926 else: # PYCHOK no cover
1927 # 0**pos_int == 0, but 0**0 == 1
1928 f = 0 if x else 1
1929 return f
1931 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
1932 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
1933 '''
1934 s, r = self._fprs2
1935 if r:
1936 # assert s != 0
1937 if isint(x, both=True): # self**int
1938 x = int(x)
1939 y = abs(x)
1940 if y > 1:
1941 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
1942 if x > 0: # i.e. > 1
1943 return f # Fsum or scalar
1944 # assert x < 0 # i.e. < -1
1945 if _isFsum(f):
1946 s, r = f._fprs2
1947 if r:
1948 return _1_Over(f, op, **raiser_RESIDUAL)
1949 else: # scalar
1950 s = f
1951 # use s**(-1) to get the CPython
1952 # float_pow error iff s is zero
1953 x = -1
1954 elif x < 0: # self**(-1)
1955 return _1_Over(self, op, **raiser_RESIDUAL) # 1 / self
1956 else: # self**1 or self**0
1957 return self._pow_0_1(x, other) # self, 1 or 1.0
1958 else: # self**fractional
1959 R = self._raiser(r, s, **raiser_RESIDUAL)
1960 if R:
1961 raise self._ResidualError(op, other, r, **R)
1962 n, d = self.as_integer_ratio()
1963 if abs(n) > abs(d):
1964 n, d, x = d, n, (-x)
1965 s = n / d
1966 # assert isscalar(s) and isscalar(x)
1967 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
1969 def _ps_acc(self, ps, xs, up=True, **unused):
1970 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.
1971 '''
1972 n = 0
1973 _2s = _2sum
1974 for x in (tuple(xs) if xs is ps else xs):
1975 # assert isscalar(x) and _isfinite(x)
1976 if x:
1977 i = 0
1978 for p in ps:
1979 x, p = _2s(x, p)
1980 if p:
1981 ps[i] = p
1982 i += 1
1983 ps[i:] = (x,) if x else ()
1984 n += 1
1985 if n:
1986 self._n += n
1987 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
1988 if up:
1989 self._update()
1990 return ps
1992 def _ps_mul(self, op, *factors):
1993 '''(INTERNAL) Multiply this instance' C{partials} with
1994 each scalar C{factor} and accumulate into an C{Fsum}.
1995 '''
1996 def _pfs(ps, fs):
1997 if len(ps) < len(fs):
1998 ps, fs = fs, ps
1999 if self._f2product:
2000 ps = tuple(_2split3s(ps))
2001 _xys = _2products
2002 else:
2003 def _xys(x, ys):
2004 return (x * y for y in ys)
2006 _fin = _isfinite
2007 for f in fs:
2008 for p in _xys(f, ps):
2009 yield p if _fin(p) else self._finite(p, op)
2011 return Fsum()._facc_scalar(_pfs(self._ps, factors), up=False)
2013 @property_RO
2014 def _ps_neg(self):
2015 '''(INTERNAL) Yield the partials, I{negated}.
2016 '''
2017 for p in self._ps:
2018 yield -p
2020 def _ps_other(self, op, *others):
2021 '''(INTERNAL) Yield the partials of all C{other}s.
2022 '''
2023 for other in others:
2024 if _isFsumTuple(other):
2025 for p in other._ps:
2026 yield p
2027 else:
2028 yield self._scalar(other, op)
2030 def _ps_1sum(self, *less):
2031 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
2032 '''
2033 def _1pls(ps, ls):
2034 yield _1_0
2035 for p in ps:
2036 yield p
2037 for p in ls:
2038 yield -p
2039 yield _N_1_0
2041 return _fsum(_1pls(self._ps, less))
2043 def _raiser(self, r, s, raiser=True, **RESIDUAL):
2044 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
2045 I{and} is residual C{r} I{non-zero} or I{significant} (for a
2046 negative respectively positive C{RESIDUAL} threshold)?
2047 '''
2048 if r and raiser:
2049 t = self._RESIDUAL
2050 if RESIDUAL:
2051 t = _threshold(t, **RESIDUAL)
2052 if t < 0 or (s + r) != s:
2053 q = (r / s) if s else s # == 0.
2054 if fabs(q) > fabs(t):
2055 return dict(ratio=q, R=t)
2056 return {}
2058 rdiv = __rtruediv__
2060 @property_RO
2061 def real(self):
2062 '''Get the C{real} part of this instance (C{float}).
2064 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
2065 and properties L{Fsum.ceil}, L{Fsum.floor},
2066 L{Fsum.imag} and L{Fsum.residual}.
2067 '''
2068 return float(self._fprs)
2070 @property_RO
2071 def residual(self):
2072 '''Get this instance' residual (C{float} or C{int}): the
2073 C{sum(partials)} less the precision running sum C{fsum}.
2075 @note: The C{residual is INT0} iff the precision running
2076 C{fsum} is considered to be I{exact}.
2078 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
2079 '''
2080 return self._fprs2.residual
2082 def RESIDUAL(self, *threshold):
2083 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
2084 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
2086 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
2087 L{ResidualError}s in division and exponention, if
2088 C{None} restore the default set with env variable
2089 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
2090 current setting.
2092 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
2094 @raise ResidualError: Invalid B{C{threshold}}.
2096 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}
2097 C{residual / fsum} exceeds the given B{C{threshold}} and (2)
2098 the C{residual} is non-zero and (3) I{significant} vs the
2099 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional
2100 keyword argument C{raiser=False} is missing. Specify a
2101 negative B{C{threshold}} for only non-zero C{residual}
2102 testing without I{significant}.
2103 '''
2104 r = self._RESIDUAL
2105 if threshold:
2106 t = threshold[0]
2107 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
2108 (_0_0 if t else _1_0) if isbool(t) else
2109 _threshold(t)) # ... backward compatibility
2110 return r
2112 def _ResidualError(self, op, other, residual, **mod_R):
2113 '''(INTERNAL) Non-zero B{C{residual}} etc.
2114 '''
2115 def _p(mod=None, R=0, **unused): # ratio=0
2116 return (_non_zero_ if R < 0 else _significant_) \
2117 if mod is None else _integer_
2119 t = _stresidual(_p(**mod_R), residual, **mod_R)
2120 return self._Error(op, other, ResidualError, txt=t)
2122 def root(self, root, **raiser_RESIDUAL):
2123 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
2125 @arg root: The order (C{scalar} or L{Fsum}), non-zero.
2126 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
2127 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
2128 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2130 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
2132 @raise ResidualError: Non-zero, significant residual or invalid
2133 B{C{RESIDUAL}}.
2135 @see: Method L{Fsum.pow}.
2136 '''
2137 x = _1_Over(root, _truediv_op_, **raiser_RESIDUAL)
2138 f = self._copy_2(self.root)
2139 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
2141 def _scalar(self, other, op, **txt):
2142 '''(INTERNAL) Return scalar C{other}.
2143 '''
2144 if isscalar(other):
2145 return other
2146 raise self._Error(op, other, _TypeError, **txt) # _invalid_
2148 def signOf(self, res=True):
2149 '''Determine the sign of this instance.
2151 @kwarg res: If C{True}, consider, otherwise ignore
2152 the residual (C{bool}).
2154 @return: The sign (C{int}, -1, 0 or +1).
2155 '''
2156 s, r = self._fprs2
2157 r = (-r) if res else 0
2158 return _signOf(s, r)
2160 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
2161 '''Return this C{Fsum} instance as representation.
2163 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
2164 for method L{Fsum.toStr}.
2166 @return: This instance (C{repr}).
2167 '''
2168 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
2170 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
2171 '''Return this C{Fsum} instance as string.
2173 @kwarg lenc: If C{True}, include the current C{[len]} of this
2174 L{Fsum} enclosed in I{[brackets]} (C{bool}).
2175 @kwarg prec_sep_fmt: Optional keyword arguments for method
2176 L{Fsum2Tuple.toStr}.
2178 @return: This instance (C{str}).
2179 '''
2180 p = self.classname
2181 if lenc:
2182 p = Fmt.SQUARE(p, len(self))
2183 n = _enquote(self.name, white=_UNDER_)
2184 t = self._fprs2.toStr(**prec_sep_fmt)
2185 return NN(p, _SPACE_, n, t)
2187 def _truediv(self, other, op, **raiser_RESIDUAL):
2188 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
2189 '''
2190 f = self._copy_2(self.__truediv__)
2191 return f._ftruediv(other, op, **raiser_RESIDUAL)
2193 def _update(self, updated=True): # see ._fset
2194 '''(INTERNAL) Zap all cached C{Property_RO} values.
2195 '''
2196 if updated:
2197 _pop = self.__dict__.pop
2198 for p in _ROs:
2199 _ = _pop(p, None)
2200# Fsum._fint2._update(self)
2201# Fsum._fprs ._update(self)
2202# Fsum._fprs2._update(self)
2203 return self # for .fset_
2205_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
2208def _Float_Int(arg, **name_Error):
2209 '''(INTERNAL) Unit of L{Fsum2Tuple} items.
2210 '''
2211 U = Int if isint(arg) else Float
2212 return U(arg, **name_Error)
2215def Fsum2product(*xs, **name_RESIDUAL):
2216 '''Return an L{Fsum} with L{f2product<Fsum.f2product>} accurate
2217 multiplication I{turned on}.
2218 '''
2219 F = Fsum(*xs, **name_RESIDUAL)
2220 F.f2product(True)
2221 return F
2224class DivMod2Tuple(_NamedTuple):
2225 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
2226 C{mod} results of a C{divmod} operation.
2228 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2229 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2230 '''
2231 _Names_ = (_div_, _mod_)
2232 _Units_ = (_Float_Int, Fsum)
2235class Fsum2Tuple(_NamedTuple): # in .fstats
2236 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2237 and the C{residual}, the sum of the remaining partials. Each
2238 item is C{float} or C{int}.
2240 @note: If the C{residual is INT0}, the C{fsum} is considered
2241 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2242 '''
2243 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2244 _Units_ = (_Float_Int, _Float_Int)
2246 def __abs__(self): # in .fmath
2247 return self._Fsum.__abs__()
2249 def __bool__(self): # PYCHOK Python 3+
2250 return bool(self._Fsum)
2252 def __eq__(self, other):
2253 return self._other_op(other, self.__eq__)
2255 def __float__(self):
2256 return self._Fsum.__float__()
2258 def __ge__(self, other):
2259 return self._other_op(other, self.__ge__)
2261 def __gt__(self, other):
2262 return self._other_op(other, self.__gt__)
2264 def __le__(self, other):
2265 return self._other_op(other, self.__le__)
2267 def __lt__(self, other):
2268 return self._other_op(other, self.__lt__)
2270 def __int__(self):
2271 return self._Fsum.__int__()
2273 def __ne__(self, other):
2274 return self._other_op(other, self.__ne__)
2276 def __neg__(self):
2277 return self._Fsum.__neg__()
2279 __nonzero__ = __bool__ # Python 2-
2281 def __pos__(self):
2282 return self._Fsum.__pos__()
2284 def as_integer_ratio(self):
2285 '''Return this instance as the ratio of 2 integers.
2287 @see: Method L{Fsum.as_integer_ratio} for further details.
2288 '''
2289 return self._Fsum.as_integer_ratio()
2291 @property_RO
2292 def _fint2(self):
2293 return self._Fsum._fint2
2295 @property_RO
2296 def _fprs2(self):
2297 return self._Fsum._fprs2
2299 @Property_RO
2300 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2301 s, r = _s_r(*self)
2302 ps = (r, s) if r else (s,)
2303 return _Psum(ps, name=self.name)
2305 def Fsum_(self, *xs, **name_RESIDUAL):
2306 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2307 '''
2308 f = _Psum(self._Fsum._ps, **name_RESIDUAL)
2309 return f._facc_1(xs, up=False) if xs else f
2311 def is_exact(self):
2312 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2313 '''
2314 return self._Fsum.is_exact()
2316 def is_integer(self):
2317 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2318 '''
2319 return self._Fsum.is_integer()
2321 def _mul_scalar(self, other, op): # for Fsum._fmul
2322 return self._Fsum._mul_scalar(other, op)
2324 @property_RO
2325 def _n(self):
2326 return self._Fsum._n
2328 def _other_op(self, other, which):
2329 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2330 return getattr(C, which.__name__)(s, other)
2332 @property_RO
2333 def _ps(self):
2334 return self._Fsum._ps
2336 @property_RO
2337 def _ps_neg(self):
2338 return self._Fsum._ps_neg
2340 def signOf(self, **res):
2341 '''Like method L{Fsum.signOf}.
2342 '''
2343 return self._Fsum.signOf(**res)
2345 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2346 '''Return this L{Fsum2Tuple} as string (C{str}).
2348 @kwarg fmt: Optional C{float} format (C{letter}).
2349 @kwarg prec_sep: Optional keyword arguments for function
2350 L{fstr<streprs.fstr>}.
2351 '''
2352 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2354_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2357class ResidualError(_ValueError):
2358 '''Error raised for a division, power or root operation of
2359 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2360 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2362 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2363 '''
2364 pass
2367try:
2368 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2370 # make sure _fsum works as expected (XXX check
2371 # float.__getformat__('float')[:4] == 'IEEE'?)
2372 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2373 del _fsum # nope, remove _fsum ...
2374 raise ImportError() # ... use _fsum below
2376 Fsum._math_fsum = _sum = _fsum # PYCHOK exported
2377except ImportError:
2378 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic
2380 def _fsum(xs):
2381 '''(INTERNAL) Precision summation, Python 2.5-.
2382 '''
2383 F = Fsum()
2384 F.name = _fsum.__name__
2385 return F._facc(xs, up=False)._fprs2.fsum
2388def fsum(xs, floats=False):
2389 '''Precision floating point summation based on/like Python's C{math.fsum}.
2391 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2392 instance).
2393 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2394 be scalar} (C{bool}).
2396 @return: Precision C{fsum} (C{float}).
2398 @raise OverflowError: Partial C{2sum} overflow.
2400 @raise TypeError: Non-scalar B{C{xs}} item.
2402 @raise ValueError: Invalid or non-finite B{C{xs}} item.
2404 @note: Exception and I{non-finite} handling may differ if not based
2405 on Python's C{math.fsum}.
2407 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.
2408 '''
2409 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield
2412def fsum_(*xs, **floats):
2413 '''Precision floating point summation of all positional items.
2415 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2416 all positional.
2417 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2418 be scalar} (C{bool}).
2420 @see: Function L{fsum<fsums.fsum>} for further details.
2421 '''
2422 return _fsum(xs if _xkwds_get1(floats, floats=False) is True else
2423 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield
2426def fsumf_(*xs):
2427 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2429 @see: Function L{fsum_<fsums.fsum_>} for further details.
2430 '''
2431 return _fsum(xs) if xs else _0_0
2434def fsum1(xs, floats=False):
2435 '''Precision floating point summation, 1-primed.
2437 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}
2438 instance).
2439 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2440 be scalar} (C{bool}).
2442 @see: Function L{fsum<fsums.fsum>} for further details.
2443 '''
2444 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield
2447def fsum1_(*xs, **floats):
2448 '''Precision floating point summation, 1-primed of all positional items.
2450 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),
2451 all positional.
2452 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to
2453 be scalar} (C{bool}).
2455 @see: Function L{fsum_<fsums.fsum_>} for further details.
2456 '''
2457 return _fsum(_1primed(xs if _xkwds_get1(floats, floats=False) is True else
2458 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield
2461def fsum1f_(*xs):
2462 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.
2464 @see: Function L{fsum_<fsums.fsum_>} for further details.
2465 '''
2466 return _fsum(_1primed(xs)) if xs else _0_0
2469if __name__ == '__main__':
2471 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums
2473 if _getenv(_psum.__name__, NN) == _fsum.__name__:
2474 _psum = _fsum
2476 def _test(n):
2477 # copied from Hettinger, see L{Fsum} reference
2478 from pygeodesy import frandoms, printf
2480 printf(_fsum.__name__, end=_COMMASPACE_)
2481 printf(_psum.__name__, end=_COMMASPACE_)
2483 F = Fsum()
2484 if F.is_math_fsum():
2485 for t in frandoms(n, seeded=True):
2486 assert float(F.fset_(*t)) == _fsum(t)
2487 printf(_DOT_, end=NN)
2488 printf(NN)
2490 _test(128)
2492# **) MIT License
2493#
2494# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
2495#
2496# Permission is hereby granted, free of charge, to any person obtaining a
2497# copy of this software and associated documentation files (the "Software"),
2498# to deal in the Software without restriction, including without limitation
2499# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2500# and/or sell copies of the Software, and to permit persons to whom the
2501# Software is furnished to do so, subject to the following conditions:
2502#
2503# The above copyright notice and this permission notice shall be included
2504# in all copies or substantial portions of the Software.
2505#
2506# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2507# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2508# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2509# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2510# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2511# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2512# OTHER DEALINGS IN THE SOFTWARE.