Coverage for pygeodesy/fsums.py: 94%
1093 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-09-30 14:00 -0400
« prev ^ index » next coverage.py v7.6.0, created at 2024-09-30 14:00 -0400
2# -*- coding: utf-8 -*-
4u'''Class L{Fsum} for precision floating point summation similar to
5Python's C{math.fsum} enhanced with I{running} summation and as an
6option, accurate I{TwoProduct} multiplication.
8Accurate multiplication is based on the C{math.fma} function for
9Python 3.13 and newer or one of two equivalent C{fma} implementations
10for Python 3.12 and older. To enable accurate multiplication, set
11env variable C{PYGEODESY_FSUM_F2PRODUCT} to C{"std"} or any non-empty
12string or invoke function C{pygeodesy.f2product(True)} or set. With
13C{"std"} the C{fma} implemention follows the C{math.fma} function,
14otherwise the C{PyGeodesy 24.09.09} release.
16Generally, an L{Fsum} instance is considered a C{float} plus a small or
17zero C{residue} aka C{residual} value, see property L{Fsum.residual}.
19Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater
20than C{"0.0"} as the threshold to throw a L{ResidualError} for a division,
21power or root operation of an L{Fsum} with a C{residual} I{ratio} exceeding
22the threshold. See methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
23and L{Fsum.__itruediv__}.
25There are several C{integer} L{Fsum} cases, for example the result from
26functions C{ceil}, C{floor}, C{Fsum.__floordiv__} and methods L{Fsum.fint},
27L{Fsum.fint2} and L{Fsum.is_integer}. Also, L{Fsum} methods L{Fsum.pow},
28L{Fsum.__ipow__}, L{Fsum.__pow__} and L{Fsum.__rpow__} return a (very long)
29C{int} if invoked with optional argument C{mod} set to C{None}. The
30C{residual} of an C{integer} L{Fsum} is between C{-1.0} and C{+1.0} and
31will be C{INT0} if that is considered to be I{exact}.
33Set env variable C{PYGEODESY_FSUM_NONFINITES} to C{"std"} or use function
34C{pygeodesy.nonfiniterrors(False)} to allow I{non-finite} C{float}s like
35C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} and to ignore C{OverflowError}
36respectively C{ValueError} exceptions. However, in that case I{non-finite}
37results may differ from Python's C{math.fsum} results.
38'''
39# make sure int/int division yields float quotient, see .basics
40from __future__ import division as _; del _ # PYCHOK semicolon
42from pygeodesy.basics import isbool, iscomplex, isint, isscalar, \
43 _signOf, itemsorted, signOf, _xiterable, \
44 _xiterablen
45from pygeodesy.constants import INF, INT0, MANT_DIG, NEG0, NINF, _0_0, \
46 _1_0, _N_1_0, _isfinite, _pos_self, \
47 Float, Int
48from pygeodesy.errors import _AssertionError, _OverflowError, _TypeError, \
49 _ValueError, _xError, _xError2, _xkwds_get, \
50 _xkwds, _xkwds_get1, _xkwds_not, _xkwds_pop, \
51 _xsError
52from pygeodesy.internals import _enquote, _passarg
53from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DOT_, _from_, \
54 _not_finite_, _SPACE_, _std_, _UNDER_
55from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
56from pygeodesy.named import _name__, _name2__, _Named, _NamedTuple, \
57 _NotImplemented
58from pygeodesy.props import _allPropertiesOf_n, deprecated_method, \
59 deprecated_property_RO, Property, \
60 Property_RO, property_RO
61from pygeodesy.streprs import Fmt, fstr, unstr
62# from pygeodesy.units import Float, Int # from .constants
64from math import fabs, isinf, isnan, \
65 ceil as _ceil, floor as _floor # PYCHOK used! .ltp
67__all__ = _ALL_LAZY.fsums
68__version__ = '24.09.29'
70from pygeodesy.interns import (
71 _PLUS_ as _add_op_, # in .auxilats.auxAngle
72 _EQUAL_ as _fset_op_,
73 _RANGLE_ as _gt_op_,
74 _LANGLE_ as _lt_op_,
75 _PERCENT_ as _mod_op_,
76 _STAR_ as _mul_op_,
77 _NOTEQUAL_ as _ne_op_,
78 _DASH_ as _sub_op_, # in .auxilats.auxAngle
79 _SLASH_ as _truediv_op_
80)
81_eq_op_ = _fset_op_ * 2 # _DEQUAL_
82_floordiv_op_ = _truediv_op_ * 2 # _DSLASH_
83_divmod_op_ = _floordiv_op_ + _mod_op_
84_F2PRODUCT = _getenv('PYGEODESY_FSUM_F2PRODUCT', NN)
85_ge_op_ = _gt_op_ + _fset_op_
86_iadd_op_ = _add_op_ + _fset_op_ # in .auxilats.auxAngle, .fstats
87_integer_ = 'integer'
88_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle
89_le_op_ = _lt_op_ + _fset_op_
90_NONFINITEr = _0_0
91_NONFINITES = _getenv('PYGEODESY_FSUM_NONFINITES', NN)
92_non_zero_ = 'non-zero'
93_pow_op_ = _mul_op_ * 2 # _DSTAR_
94_RESIDUAL_0_0 = _getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)
95_significant_ = 'significant'
96_threshold_ = 'threshold'
99def _2finite(x): # in .fstats
100 '''(INTERNAL) return C{float(x)} if finite.
101 '''
102 return (float(x) if _isfinite(x) # and isscalar(x)
103 else _nfError(x))
106def _2float(index=None, _isfine=_isfinite, **name_x): # in .fmath, .fstats
107 '''(INTERNAL) Raise C{TypeError} or C{Overflow-/ValueError} if not finite.
108 '''
109 n, x = name_x.popitem() # _xkwds_item2(name_x)
110 try:
111 f = float(x)
112 return f if _isfine(f) else _nfError(x)
113 except Exception as X:
114 raise _xError(X, Fmt.INDEX(n, index), x)
117def _X_ps(X): # for _2floats only
118 return X._ps
121def _2floats(xs, origin=0, _X=_X_ps, _x=float, _isfine=_isfinite):
122 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
123 '''
124 try:
125 i, x = origin, xs
126 _FsT = _Fsum_2Tuple_types
127 for x in _xiterable(xs):
128 if isinstance(x, _FsT):
129 for p in _X(x._Fsum):
130 yield p
131 else:
132 f = _x(x)
133 yield f if _isfine(f) else _nfError(f)
134 i += 1
135 except Exception as X:
136 raise _xsError(X, xs, i, x)
139try: # MCCABE 26
140 from math import fma as _fma
142 def _2products(x, ys, *zs):
143 # yield(x * y for y in ys) + yield(z in zs)
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)
150 for z in zs:
151 yield z
153# _2split3 = \
154 _2split3s = _passarg # in Fsum.is_math_fma
156except ImportError: # PYCHOK DSPACE! Python 3.12-
158 if _F2PRODUCT and _F2PRODUCT != _std_:
159 # back to PyGeodesy 24.09.09, with _fmaX
161 def _fma(*a_b_c): # PYCHOK no cover
162 # mimick C{math.fma} from Python 3.13+,
163 # the same accuracy, but ~14x slower
164 (na, da), (nb, db), (nc, dc) = map(_2n_d, a_b_c)
165 n = na * nb * dc
166 n += da * db * nc
167 d = da * db * dc
168 try:
169 r = float(n / d)
170 except OverflowError: # "integer division result too large ..."
171 r = NINF if (_signOf(n, 0) * _signOf(d, 0)) < 0 else INF
172 return r if _isfinite(r) else _fmaX(r, *a_b_c) # "overflow in fma"
174 def _2n_d(x):
175 try: # int.as_integer_ratio in 3.8+
176 return x.as_integer_ratio()
177 except (AttributeError, OverflowError, TypeError, ValueError):
178 return (x if isint(x) else float(x)), 1
179 else:
181 def _fma(a, b, c): # PYCHOK redef
182 # mimick C{math.fma} from Python 3.13+,
183 # the same accuracy, but ~13x slower
184 b3s = _2split3(b), # 1-tuple of 3-tuple
185 r = _fsum(_2products(a, b3s, c))
186 return r if _isfinite(r) else _fmaX(r, a, b, c)
188 _2n_d = None # redef
190 def _fmaX(r, *a_b_c): # like Python 3.13+ I{Modules/mathmodule.c}:
191 # raise a ValueError for a NAN result from non-NAN C{a_b_c}s or
192 # OverflowError for a non-NAN result from all finite C{a_b_c}s.
193 if isnan(r):
194 def _x(x):
195 return not isnan(x)
196 else:
197 _x = _isfinite
198 if all(map(_x, a_b_c)):
199 raise _nfError(r, unstr(_fma, *a_b_c))
200 return r
202 def _2products(x, y3s, *zs): # PYCHOK in Fsum._f2mul
203 # yield(x * y3 for y3 in y3s) + yield(z in zs)
204 # TwoProduct U{Algorithm 3.3
205 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
206 # also in Python 3.13+ C{Modules/mathmodule.c} under
207 # #ifndef UNRELIABLE_FMA ... #else ... #endif
208 _, a, b = _2split3(x)
209 for y, c, d in y3s:
210 y *= x
211 yield y
212 if False: # no cover
213 yield b * d - (((y - a * c) - b * c) - a * d)
214 # = b * d + (a * d - ((y - a * c) - b * c))
215 # = b * d + (a * d + (b * c - (y - a * c)))
216 # = b * d + (a * d + (b * c + (a * c - y)))
217 elif a:
218 yield a * c - y
219 yield b * c
220 if d:
221 yield a * d
222 yield b * d
223 else:
224 yield b * c - y
225 yield b * d
226 for z in zs:
227 yield z
229 _2FACTOR = pow(2, (MANT_DIG + 1) // 2) + _1_0 # 134217729 if MANT_DIG == 53
231 def _2split3(x):
232 # Split U{Algorithm 3.2
233 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
234 a = c = x * _2FACTOR
235 a -= c - x
236 b = x - a
237 return x, a, b
239 def _2split3s(xs): # in Fsum.is_math_fma
240 return map(_2split3, xs)
243def f2product(*two):
244 '''Turn accurate I{TwoProduct} multiplication on or off.
246 @arg two: If C{True}, turn I{TwoProduct} on, if C{False} off or
247 if C{None} or omitted, keep the current setting.
249 @return: The previous setting (C{bool}).
251 @see: I{TwoProduct} multiplication is based on the I{TwoProductFMA}
252 U{Algorithm 3.5 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
253 using function C{math.fma} from Python 3.13 and later or an
254 equivalent, slower implementation when not available.
255 '''
256 t = Fsum._f2product
257 if two and two[0] is not None:
258 Fsum._f2product = bool(two[0])
259 return t
262def _Fsumf_(*xs): # in .auxLat, .ltp, ...
263 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
264 '''
265 return Fsum()._facc_scalarf(xs, up=False)
268def _Fsum1f_(*xs): # in .albers
269 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}, 1-primed.
270 '''
271 return Fsum()._facc_scalarf(_1primed(xs), up=False)
274def _2halfeven(s, r, p):
275 '''(INTERNAL) Round half-even.
276 '''
277 if (p > 0 and r > 0) or \
278 (p < 0 and r < 0): # signs match
279 r *= 2
280 t = s + r
281 if r == (t - s):
282 s = t
283 return s
286def _isFsum(x): # in .fmath
287 '''(INTERNAL) Is C{x} an C{Fsum} instance?
288 '''
289 return isinstance(x, Fsum)
292def _isFsum_2Tuple(x): # in .basics, .constants, .fmath, .fstats
293 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance?
294 '''
295 return isinstance(x, _Fsum_2Tuple_types)
298def _isOK(unused):
299 '''(INTERNAL) Helper for C{Fsum._fsum2} and C{Fsum.nonfinites}.
300 '''
301 return True
304def _isOK_or_finite(x, _isfine=_isfinite):
305 '''(INTERNAL) Is C{x} finite or is I{non-finite} OK?.
306 '''
307 # assert _isfine in (_isOK, _isfinite)
308 return _isfine(x)
311def _ixError(X, xs, i, x, origin=0, which=None):
312 '''(INTERNAL) Error for C{xs} or C{x}, item C{xs[i]}.
313 '''
314 t = _xsError(X, xs, i + origin, x)
315 if which:
316 t = _COMMASPACE_(unstr(which, _Cdot=Fsum), t)
317 return _xError(X, t, txt=None)
320def _nfError(x, *args):
321 '''(INTERNAL) Throw a C{not-finite} exception.
322 '''
323 E = _NonfiniteError(x)
324 t = Fmt.PARENSPACED(_not_finite_, x)
325 if args: # in _fmaX, _2sum
326 return E(txt=t, *args)
327 raise E(t, txt=None)
330def nonfiniterrors(*raiser):
331 '''Throw C{OverflowError} and C{ValueError} exceptions for or
332 handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF},
333 C{nan} and C{NAN} in summations and multiplications.
335 @arg raiser: If C{True}, throw exceptions, if C{False} handle
336 I{non-finites} or if C{None} or omitted, leave
337 the setting unchanged.
339 @return: Previous setting (C{bool}).
341 @note: C{inf}, C{INF} and C{NINF} throw an C{OverflowError},
342 C{nan} and C{NAN} a C{ValueError}.
343 '''
344 d = Fsum._isfine
345 if raiser and raiser[0] is not None:
346 Fsum._isfine = {} if bool(raiser[0]) else Fsum._nonfinites_isfine_kwds[True]
347 return _xkwds_get1(d, _isfine=_isfinite) is _isfinite
350def _NonfiniteError(x):
351 '''(INTERNAL) Return the Error class for C{x}, I{non-finite}.
352 '''
353 return _OverflowError if isinf(x) else (
354 _ValueError if isnan(x) else _AssertionError)
357def _1primed(xs): # in .fmath
358 '''(INTERNAL) 1-Primed summation of iterable C{xs}
359 items, all I{known} to be C{scalar}.
360 '''
361 yield _1_0
362 for x in xs:
363 yield x
364 yield _N_1_0
367def _psum(ps, **_isfine): # PYCHOK used!
368 '''(INTERNAL) Partials summation, updating C{ps}.
369 '''
370 # assert isinstance(ps, list)
371 i = len(ps) - 1
372 s = _0_0 if i < 0 else ps[i]
373 while i > 0:
374 i -= 1
375 s, r = _2sum(s, ps[i], **_isfine)
376 if r: # sum(ps) became inexact
377 if s:
378 ps[i:] = r, s
379 if i > 0:
380 s = _2halfeven(s, r, ps[i-1])
381 break # return s
382 s = r # PYCHOK no cover
383 elif not _isfinite(s): # non-finite OK
384 i = 0 # collapse ps
385 if ps:
386 s += sum(ps)
387 ps[i:] = s,
388 return s
391def _Psum(ps, **name_f2product_nonfinites_RESIDUAL):
392 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
393 '''
394 F = Fsum(**name_f2product_nonfinites_RESIDUAL)
395 if ps:
396 F._ps[:] = ps
397 F._n = len(F._ps)
398 return F
401def _Psum_(*ps, **name_f2product_nonfinites_RESIDUAL): # in .fmath
402 '''(INTERNAL) Return an C{Fsum} from I{known scalar} C{ps}.
403 '''
404 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL)
407def _2scalar2(other):
408 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
409 C{float} or C{as-is} and C{r} the residual of C{as-is}.
410 '''
411 if _isFsum_2Tuple(other):
412 s, r = other._fint2
413 if r:
414 s, r = other._fprs2
415 if r: # PYCHOK no cover
416 s = other # L{Fsum} as-is
417 else:
418 r = 0
419 s = other # C{type} as-is
420 if isint(s, both=True):
421 s = int(s)
422 return s, r
425def _s_r(s, r):
426 '''(INTERNAL) Return C{(s, r)}, I{ordered}.
427 '''
428 if r and _isfinite(s):
429 if fabs(s) < fabs(r):
430 s, r = r, (s or INT0)
431 else:
432 r = INT0
433 return s, r
436def _strcomplex(s, *args):
437 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
438 '''
439 c = _strcomplex.__name__[4:]
440 n = _sub_op_(len(args), _arg_)
441 t = unstr(pow, *args)
442 return _SPACE_(c, s, _from_, n, t)
445def _stresidual(prefix, residual, R=0, **mod_ratio):
446 '''(INTERNAL) Residual error txt C{str}.
447 '''
448 p = _stresidual.__name__[3:]
449 t = Fmt.PARENSPACED(p, Fmt(residual))
450 for n, v in itemsorted(mod_ratio):
451 p = Fmt.PARENSPACED(n, Fmt(v))
452 t = _COMMASPACE_(t, p)
453 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_)
456def _2sum(a, b, _isfine=_isfinite): # in .testFmath
457 '''(INTERNAL) Return C{a + b} as 2-tuple C{(sum, residual)} with finite C{sum},
458 otherwise as 2-tuple C{(nonfinite, 0)} iff I{non-finites} are OK.
459 '''
460 # FastTwoSum U{Algorithm 1.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
462 # Neumaier, A. U{Rundungsfehleranalyse einiger Verfahren zur Summation endlicher
463 # Summen<https://OnlineLibrary.Wiley.com/doi/epdf/10.1002/zamm.19740540106>},
464 # 1974, Zeitschrift für Angewandte Mathmatik und Mechanik, vol 51, nr 1, p 39-51
465 # <https://StackOverflow.com/questions/78633770/can-neumaier-summation-be-sped-up>
466 s = a + b
467 if _isfinite(s):
468 if fabs(a) < fabs(b):
469 r = (b - s) + a
470 else:
471 r = (a - s) + b
472 elif _isfine(s):
473 r = _NONFINITEr
474 else: # non-finite and not OK
475 t = unstr(_2sum, a, b)
476 raise _nfError(s, t)
477 return s, r
480def _threshold(threshold=_0_0, **kwds):
481 '''(INTERNAL) Get the L{ResidualError}s threshold,
482 optionally from single kwds C{B{RESIDUAL}=scalar}.
483 '''
484 if kwds:
485 threshold = _xkwds_get1(kwds, RESIDUAL=threshold)
486 try:
487 return _2finite(threshold) # PYCHOK None
488 except Exception as x:
489 raise ResidualError(threshold=threshold, cause=x)
492class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase, .fstats, ...
493 '''Precision floating point summation, I{running} summation and accurate multiplication.
495 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
496 I{running}, precision floating point summations. Accumulation may continue after any
497 intermediate, I{running} summuation.
499 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances,
500 i.e. any C{type} having method C{__float__}.
502 @note: Handling of I{non-finites} as C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} is
503 determined by function L{nonfiniterrors<fsums.nonfiniterrors>} for the default
504 and by method L{nonfinites<Fsum.nonfinites>} for individual C{Fsum} instances,
505 overruling the default. For backward compatibility, I{non-finites} raise
506 exceptions by default.
508 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/
509 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>},
510 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
511 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
512 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
513 <https://Bugs.Python.org/issue2819>}.
515 @see: Method L{f2product<Fsum.f2product>} for details about accurate I{TwoProduct}
516 multiplication.
518 @see: Module L{fsums<pygeodesy.fsums>} for env variables C{PYGEODESY_FSUM_F2PRODUCT},
519 C{PYGEODESY_FSUM_NONFINITES} and C{PYGEODESY_FSUM_RESIDUAL}.
520 '''
521 _f2product = _sys_version_info2 > (3, 12) or bool(_F2PRODUCT)
522 _isfine = {} # == _isfinite
523 _n = 0
524# _ps = [] # partial sums
525# _ps_max = 0 # max(Fsum._ps_max, len(Fsum._ps)) # 41
526 _RESIDUAL = _threshold(_RESIDUAL_0_0)
528 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL):
529 '''New L{Fsum}.
531 @arg xs: No, one or more initial items to accumulate (each C{scalar}, an
532 L{Fsum} or L{Fsum2Tuple}), all positional.
533 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str})
534 and settings C{B{f2product}=None} (C{bool}), C{B{nonfinites}=None}
535 (C{bool}) and C{B{RESIDUAL}=0.0} threshold (C{scalar}) for this
536 L{Fsum}.
538 @see: Methods L{Fsum.f2product}, L{Fsum.nonfinites}, L{Fsum.RESIDUAL},
539 L{Fsum.fadd} and L{Fsum.fadd_}.
540 '''
541 if name_f2product_nonfinites_RESIDUAL:
542 self._optionals(**name_f2product_nonfinites_RESIDUAL)
543 self._ps = [] # [_0_0], see L{Fsum._fprs}
544 if xs:
545 self._facc_args(xs, up=False)
547 def __abs__(self):
548 '''Return C{abs(self)} as an L{Fsum}.
549 '''
550 s = self.signOf() # == self._cmp_0(0)
551 return (-self) if s < 0 else self._copy_2(self.__abs__)
553 def __add__(self, other):
554 '''Return C{B{self} + B{other}} as an L{Fsum}.
556 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
558 @return: The sum (L{Fsum}).
560 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
561 '''
562 f = self._copy_2(self.__add__)
563 return f._fadd(other, _add_op_)
565 def __bool__(self): # PYCHOK Python 3+
566 '''Return C{bool(B{self})}, C{True} iff C{residual} is zero.
567 '''
568 s, r = self._fprs2
569 return bool(s or r) and s != -r # == self != 0
571 def __ceil__(self): # PYCHOK not special in Python 2-
572 '''Return this instance' C{math.ceil} as C{int} or C{float}.
574 @return: An C{int} in Python 3+, but C{float} in Python 2-.
576 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
577 '''
578 return self.ceil
580 def __cmp__(self, other): # PYCHOK no cover
581 '''Compare this with an other instance or C{scalar}, Python 2-.
583 @return: -1, 0 or +1 (C{int}).
585 @raise TypeError: Incompatible B{C{other}} C{type}.
586 '''
587 s = self._cmp_0(other, self.cmp.__name__)
588 return _signOf(s, 0)
590 def __divmod__(self, other, **raiser_RESIDUAL):
591 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
592 with quotient C{div} an C{int} in Python 3+ or C{float}
593 in Python 2- and remainder C{mod} an L{Fsum} instance.
595 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
596 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
597 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
598 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
600 @raise ResidualError: Non-zero, significant residual or invalid
601 B{C{RESIDUAL}}.
603 @see: Method L{Fsum.fdiv}.
604 '''
605 f = self._copy_2(self.__divmod__)
606 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
608 def __eq__(self, other):
609 '''Return C{(B{self} == B{other})} as C{bool} where B{C{other}}
610 is C{scalar}, an other L{Fsum} or L{Fsum2Tuple}.
611 '''
612 return self._cmp_0(other, _eq_op_) == 0
614 def __float__(self):
615 '''Return this instance' current, precision running sum as C{float}.
617 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
618 '''
619 return float(self._fprs)
621 def __floor__(self): # PYCHOK not special in Python 2-
622 '''Return this instance' C{math.floor} as C{int} or C{float}.
624 @return: An C{int} in Python 3+, but C{float} in Python 2-.
626 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
627 '''
628 return self.floor
630 def __floordiv__(self, other):
631 '''Return C{B{self} // B{other}} as an L{Fsum}.
633 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
635 @return: The C{floor} quotient (L{Fsum}).
637 @see: Methods L{Fsum.__ifloordiv__}.
638 '''
639 f = self._copy_2(self.__floordiv__)
640 return f._floordiv(other, _floordiv_op_)
642 def __format__(self, *other): # PYCHOK no cover
643 '''Not implemented.'''
644 return _NotImplemented(self, *other)
646 def __ge__(self, other):
647 '''Return C{(B{self} >= B{other})}, see C{__eq__}.
648 '''
649 return self._cmp_0(other, _ge_op_) >= 0
651 def __gt__(self, other):
652 '''Return C{(B{self} > B{other})}, see C{__eq__}.
653 '''
654 return self._cmp_0(other, _gt_op_) > 0
656 def __hash__(self): # PYCHOK no cover
657 '''Return C{hash(B{self})} as C{float}.
658 '''
659 # @see: U{Notes for type implementors<https://docs.Python.org/
660 # 3/library/numbers.html#numbers.Rational>}
661 return hash(self.partials) # tuple.__hash__()
663 def __iadd__(self, other):
664 '''Apply C{B{self} += B{other}} to this instance.
666 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
667 an iterable of several of the former.
669 @return: This instance, updated (L{Fsum}).
671 @raise TypeError: Invalid B{C{other}}, not
672 C{scalar} nor L{Fsum}.
674 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
675 '''
676 try:
677 return self._fadd(other, _iadd_op_)
678 except TypeError:
679 pass
680 _xiterable(other)
681 return self._facc(other)
683 def __ifloordiv__(self, other):
684 '''Apply C{B{self} //= B{other}} to this instance.
686 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
688 @return: This instance, updated (L{Fsum}).
690 @raise ResidualError: Non-zero, significant residual
691 in B{C{other}}.
693 @raise TypeError: Invalid B{C{other}} type.
695 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
697 @raise ZeroDivisionError: Zero B{C{other}}.
699 @see: Methods L{Fsum.__itruediv__}.
700 '''
701 return self._floordiv(other, _floordiv_op_ + _fset_op_)
703 def __imatmul__(self, other): # PYCHOK no cover
704 '''Not implemented.'''
705 return _NotImplemented(self, other)
707 def __imod__(self, other):
708 '''Apply C{B{self} %= B{other}} to this instance.
710 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
712 @return: This instance, updated (L{Fsum}).
714 @see: Method L{Fsum.__divmod__}.
715 '''
716 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
718 def __imul__(self, other):
719 '''Apply C{B{self} *= B{other}} to this instance.
721 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
723 @return: This instance, updated (L{Fsum}).
725 @raise OverflowError: Partial C{2sum} overflow.
727 @raise TypeError: Invalid B{C{other}} type.
729 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
730 '''
731 return self._fmul(other, _mul_op_ + _fset_op_)
733 def __int__(self):
734 '''Return this instance as an C{int}.
736 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
737 and L{Fsum.floor}.
738 '''
739 i, _ = self._fint2
740 return i
742 def __invert__(self): # PYCHOK no cover
743 '''Not implemented.'''
744 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
745 return _NotImplemented(self)
747 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
748 '''Apply C{B{self} **= B{other}} to this instance.
750 @arg other: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
751 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
752 C{pow(B{self}, B{other}, B{mod})} version.
753 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
754 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
755 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
757 @return: This instance, updated (L{Fsum}).
759 @note: If B{C{mod}} is given, the result will be an C{integer}
760 L{Fsum} in Python 3+ if this instance C{is_integer} or
761 set to C{as_integer} and B{C{mod}} is given and C{None}.
763 @raise OverflowError: Partial C{2sum} overflow.
765 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
766 is non-zero and significant and either
767 B{C{other}} is a fractional or negative
768 C{scalar} or B{C{mod}} is given and not
769 C{None}.
771 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
772 invocation failed.
774 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
775 instance is C{0} or B{C{other}} is a fractional
776 C{scalar} and this instance is negative or has a
777 non-zero and significant residual or B{C{mod}}
778 is given as C{0}.
780 @see: CPython function U{float_pow<https://GitHub.com/
781 python/cpython/blob/main/Objects/floatobject.c>}.
782 '''
783 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
785 def __isub__(self, other):
786 '''Apply C{B{self} -= B{other}} to this instance.
788 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
789 an iterable of several of the former.
791 @return: This instance, updated (L{Fsum}).
793 @raise TypeError: Invalid B{C{other}} type.
795 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
796 '''
797 try:
798 return self._fsub(other, _isub_op_)
799 except TypeError:
800 pass
801 _xiterable(other)
802 return self._facc_neg(other)
804 def __iter__(self):
805 '''Return an C{iter}ator over a C{partials} duplicate.
806 '''
807 return iter(self.partials)
809 def __itruediv__(self, other, **raiser_RESIDUAL):
810 '''Apply C{B{self} /= B{other}} to this instance.
812 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
813 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
814 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
815 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
817 @return: This instance, updated (L{Fsum}).
819 @raise OverflowError: Partial C{2sum} overflow.
821 @raise ResidualError: Non-zero, significant residual or invalid
822 B{C{RESIDUAL}}.
824 @raise TypeError: Invalid B{C{other}} type.
826 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
828 @raise ZeroDivisionError: Zero B{C{other}}.
830 @see: Method L{Fsum.__ifloordiv__}.
831 '''
832 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
834 def __le__(self, other):
835 '''Return C{(B{self} <= B{other})}, see C{__eq__}.
836 '''
837 return self._cmp_0(other, _le_op_) <= 0
839 def __len__(self):
840 '''Return the number of values accumulated (C{int}).
841 '''
842 return self._n
844 def __lt__(self, other):
845 '''Return C{(B{self} < B{other})}, see C{__eq__}.
846 '''
847 return self._cmp_0(other, _lt_op_) < 0
849 def __matmul__(self, other): # PYCHOK no cover
850 '''Not implemented.'''
851 return _NotImplemented(self, other)
853 def __mod__(self, other):
854 '''Return C{B{self} % B{other}} as an L{Fsum}.
856 @see: Method L{Fsum.__imod__}.
857 '''
858 f = self._copy_2(self.__mod__)
859 return f._fdivmod2(other, _mod_op_).mod
861 def __mul__(self, other):
862 '''Return C{B{self} * B{other}} as an L{Fsum}.
864 @see: Method L{Fsum.__imul__}.
865 '''
866 f = self._copy_2(self.__mul__)
867 return f._fmul(other, _mul_op_)
869 def __ne__(self, other):
870 '''Return C{(B{self} != B{other})}, see C{__eq__}.
871 '''
872 return self._cmp_0(other, _ne_op_) != 0
874 def __neg__(self):
875 '''Return C{copy(B{self})}, I{negated}.
876 '''
877 f = self._copy_2(self.__neg__)
878 return f._fset(self._neg)
880 def __pos__(self):
881 '''Return this instance I{as-is}, like C{float.__pos__()}.
882 '''
883 return self if _pos_self else self._copy_2(self.__pos__)
885 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
886 '''Return C{B{self}**B{other}} as an L{Fsum}.
888 @see: Method L{Fsum.__ipow__}.
889 '''
890 f = self._copy_2(self.__pow__)
891 return f._fpow(other, _pow_op_, *mod)
893 def __radd__(self, other):
894 '''Return C{B{other} + B{self}} as an L{Fsum}.
896 @see: Method L{Fsum.__iadd__}.
897 '''
898 f = self._copy_2r(other, self.__radd__)
899 return f._fadd(self, _add_op_)
901 def __rdivmod__(self, other):
902 '''Return C{divmod(B{other}, B{self})} as 2-tuple
903 C{(quotient, remainder)}.
905 @see: Method L{Fsum.__divmod__}.
906 '''
907 f = self._copy_2r(other, self.__rdivmod__)
908 return f._fdivmod2(self, _divmod_op_)
910# def __repr__(self):
911# '''Return the default C{repr(this)}.
912# '''
913# return self.toRepr(lenc=True)
915 def __rfloordiv__(self, other):
916 '''Return C{B{other} // B{self}} as an L{Fsum}.
918 @see: Method L{Fsum.__ifloordiv__}.
919 '''
920 f = self._copy_2r(other, self.__rfloordiv__)
921 return f._floordiv(self, _floordiv_op_)
923 def __rmatmul__(self, other): # PYCHOK no cover
924 '''Not implemented.'''
925 return _NotImplemented(self, other)
927 def __rmod__(self, other):
928 '''Return C{B{other} % B{self}} as an L{Fsum}.
930 @see: Method L{Fsum.__imod__}.
931 '''
932 f = self._copy_2r(other, self.__rmod__)
933 return f._fdivmod2(self, _mod_op_).mod
935 def __rmul__(self, other):
936 '''Return C{B{other} * B{self}} as an L{Fsum}.
938 @see: Method L{Fsum.__imul__}.
939 '''
940 f = self._copy_2r(other, self.__rmul__)
941 return f._fmul(self, _mul_op_)
943 def __round__(self, *ndigits): # PYCHOK Python 3+
944 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
946 @arg ndigits: Optional number of digits (C{int}).
947 '''
948 f = self._copy_2(self.__round__)
949 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
950 return f._fset(round(float(self), *ndigits)) # can be C{int}
952 def __rpow__(self, other, *mod):
953 '''Return C{B{other}**B{self}} as an L{Fsum}.
955 @see: Method L{Fsum.__ipow__}.
956 '''
957 f = self._copy_2r(other, self.__rpow__)
958 return f._fpow(self, _pow_op_, *mod)
960 def __rsub__(self, other):
961 '''Return C{B{other} - B{self}} as L{Fsum}.
963 @see: Method L{Fsum.__isub__}.
964 '''
965 f = self._copy_2r(other, self.__rsub__)
966 return f._fsub(self, _sub_op_)
968 def __rtruediv__(self, other, **raiser_RESIDUAL):
969 '''Return C{B{other} / B{self}} as an L{Fsum}.
971 @see: Method L{Fsum.__itruediv__}.
972 '''
973 f = self._copy_2r(other, self.__rtruediv__)
974 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
976 def __str__(self):
977 '''Return the default C{str(self)}.
978 '''
979 return self.toStr(lenc=True)
981 def __sub__(self, other):
982 '''Return C{B{self} - B{other}} as an L{Fsum}.
984 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
986 @return: The difference (L{Fsum}).
988 @see: Method L{Fsum.__isub__}.
989 '''
990 f = self._copy_2(self.__sub__)
991 return f._fsub(other, _sub_op_)
993 def __truediv__(self, other, **raiser_RESIDUAL):
994 '''Return C{B{self} / B{other}} as an L{Fsum}.
996 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
997 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
998 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
999 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1001 @return: The quotient (L{Fsum}).
1003 @raise ResidualError: Non-zero, significant residual or invalid
1004 B{C{RESIDUAL}}.
1006 @see: Method L{Fsum.__itruediv__}.
1007 '''
1008 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
1010 __trunc__ = __int__
1012 if _sys_version_info2 < (3, 0): # PYCHOK no cover
1013 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
1014 __div__ = __truediv__
1015 __idiv__ = __itruediv__
1016 __long__ = __int__
1017 __nonzero__ = __bool__
1018 __rdiv__ = __rtruediv__
1020 def as_integer_ratio(self):
1021 '''Return this instance as the ratio of 2 integers.
1023 @return: 2-Tuple C{(numerator, denominator)} both C{int} with
1024 C{numerator} signed and C{denominator} non-zero and
1025 positive. The C{numerator} is I{non-finite} if this
1026 instance is.
1028 @see: Method L{Fsum.fint2} and C{float.as_integer_ratio} in
1029 Python 2.7+.
1030 '''
1031 n, r = self._fint2
1032 if r:
1033 i, d = float(r).as_integer_ratio()
1034 n *= d
1035 n += i
1036 else: # PYCHOK no cover
1037 d = 1
1038 return n, d
1040 @property_RO
1041 def as_iscalar(self):
1042 '''Get this instance I{as-is} (L{Fsum} with C{non-zero residual},
1043 C{scalar} or I{non-finite}).
1044 '''
1045 s, r = self._fprs2
1046 return self if r else s
1048 @property_RO
1049 def ceil(self):
1050 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
1051 C{float} in Python 2-).
1053 @note: This C{ceil} takes the C{residual} into account.
1055 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
1056 L{Fsum.imag} and L{Fsum.real}.
1057 '''
1058 s, r = self._fprs2
1059 c = _ceil(s) + int(r) - 1
1060 while r > (c - s): # (s + r) > c
1061 c += 1
1062 return c # _ceil(self._n_d)
1064 cmp = __cmp__
1066 def _cmp_0(self, other, op):
1067 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
1068 '''
1069 if _isFsum_2Tuple(other):
1070 s = self._ps_1sum(*other._ps)
1071 elif self._scalar(other, op):
1072 s = self._ps_1sum(other)
1073 else:
1074 s = self.signOf() # res=True
1075 return s
1077 def copy(self, deep=False, **name):
1078 '''Copy this instance, C{shallow} or B{C{deep}}.
1080 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}).
1082 @return: The copy (L{Fsum}).
1083 '''
1084 n = _name__(name, name__=self.copy)
1085 f = _Named.copy(self, deep=deep, name=n)
1086 if f._ps is self._ps:
1087 f._ps = list(self._ps) # separate list
1088 if not deep:
1089 f._n = 1
1090 # assert f._f2product == self._f2product
1091 # assert f._Fsum is f
1092 return f
1094 def _copy_2(self, which, name=NN):
1095 '''(INTERNAL) Copy for I{dyadic} operators.
1096 '''
1097 n = name or which.__name__ # _dunder_nameof
1098 # NOT .classof due to .Fdot(a, *b) args, etc.
1099 f = _Named.copy(self, deep=False, name=n)
1100 f._ps = list(self._ps) # separate list
1101 # assert f._n == self._n
1102 # assert f._f2product == self._f2product
1103 # assert f._Fsum is f
1104 return f
1106 def _copy_2r(self, other, which):
1107 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
1108 '''
1109 return other._copy_2(which) if _isFsum(other) else \
1110 self._copy_2(which)._fset(other)
1112 divmod = __divmod__
1114 def _Error(self, op, other, Error, **txt_cause):
1115 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
1116 '''
1117 # self.as_iscalar causes RecursionError for ._fprs2 errors
1118 s = _Psum(self._ps, nonfinites=True, name=self.name)
1119 return Error(_SPACE_(s.as_iscalar, op, other), **txt_cause)
1121 def _ErrorX(self, X, op, other, *mod):
1122 '''(INTERNAL) Format the caught exception C{X}.
1123 '''
1124 E, t = _xError2(X)
1125 if mod:
1126 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
1127 return self._Error(op, other, E, txt=t, cause=X)
1129 def _ErrorXs(self, X, xs, **kwds): # in .fmath
1130 '''(INTERNAL) Format the caught exception C{X}.
1131 '''
1132 E, t = _xError2(X)
1133 u = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
1134 return E(u, txt=t, cause=X)
1136 def _facc(self, xs, up=True, **origin_X_x):
1137 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s.
1138 '''
1139 if xs:
1140 kwds = _xkwds(self._isfine, **origin_X_x)
1141 fs = _2floats(xs, **kwds) # PYCHOK yield
1142 ps = self._ps
1143 ps[:] = self._ps_acc(list(ps), fs, up=up)
1144 return self
1146 def _facc_args(self, xs, **up):
1147 '''(INTERNAL) Accumulate 0, 1 or more C{xs}, all positional
1148 arguments in the caller of this method.
1149 '''
1150 return self._facc(xs, origin=1, **up) if len(xs) != 1 else \
1151 self._fadd(xs[0], _add_op_, **up)
1153 def _facc_neg(self, xs, **up_origin):
1154 '''(INTERNAL) Accumulate more C{xs}, negated.
1155 '''
1156 def _N(X):
1157 return X._ps_neg
1159 def _n(x):
1160 return -float(x)
1162 return self._facc(xs, _X=_N, _x=_n, **up_origin)
1164 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
1165 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
1166 '''
1167 def _Pow4(p):
1168 r = 0
1169 if _isFsum_2Tuple(p):
1170 s, r = p._fprs2
1171 if r:
1172 m = Fsum._pow
1173 else: # scalar
1174 return _Pow4(s)
1175 elif isint(p, both=True) and int(p) >= 0:
1176 p = s = int(p)
1177 m = Fsum._pow_int
1178 else:
1179 p = s = _2float(power=p, **self._isfine)
1180 m = Fsum._pow_scalar
1181 return m, p, s, r
1183 _Pow, p, s, r = _Pow4(power)
1184 if p: # and xs:
1185 op = which.__name__
1186 _FsT = _Fsum_2Tuple_types
1187 _pow = self._pow_2_3
1189 def _P(X):
1190 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
1191 return f._ps if isinstance(f, _FsT) else (f,)
1193 def _p(x):
1194 x = float(x)
1195 f = _pow(x, s, power, op, **raiser_RESIDUAL)
1196 if f and r:
1197 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
1198 return f
1200 f = self._facc(xs, origin=1, _X=_P, _x=_p)
1201 else:
1202 f = self._facc_scalar_(float(len(xs))) # x**0 == 1
1203 return f
1205 def _facc_scalar(self, xs, **up):
1206 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}.
1207 '''
1208 if xs:
1209 _ = self._ps_acc(self._ps, xs, **up)
1210 return self
1212 def _facc_scalar_(self, *xs, **up):
1213 '''(INTERNAL) Accumulate all positional C{xs}, each C{scalar}.
1214 '''
1215 return self._facc_scalar(xs, **up)
1217 def _facc_scalarf(self, xs, **origin_which):
1218 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}, an L{Fsum} or
1219 L{Fsum2Tuple}, like function C{_xsum}.
1220 '''
1221 i_x = [0, xs]
1222 try:
1223 nf = self.nonfinitesOK
1224 return self._facc_scalar(_xs(xs, i_x, nf))
1225 except (OverflowError, TypeError, ValueError) as X:
1226 raise _ixError(X, xs, *i_x, **origin_which)
1228# def _facc_up(self, up=True):
1229# '''(INTERNAL) Update the C{partials}, by removing
1230# and re-accumulating the final C{partial}.
1231# '''
1232# ps = self._ps
1233# while len(ps) > 1:
1234# p = ps.pop()
1235# if p:
1236# n = self._n
1237# _ = self._ps_acc(ps, (p,), up=False)
1238# self._n = n
1239# break
1240# return self._update() if up else self
1242 def fadd(self, xs=()):
1243 '''Add an iterable's items to this instance.
1245 @arg xs: Iterable of items to add (each C{scalar}
1246 or an L{Fsum} or L{Fsum2Tuple} instance).
1248 @return: This instance (L{Fsum}).
1250 @raise OverflowError: Partial C{2sum} overflow.
1252 @raise TypeError: An invalid B{C{xs}} item.
1254 @raise ValueError: Invalid or I{non-finite} B{C{xs}} value.
1255 '''
1256 if _isFsum_2Tuple(xs):
1257 self._facc_scalar(xs._ps)
1258 elif isscalar(xs): # for backward compatibility # PYCHOK no cover
1259 x = _2float(x=xs, **self._isfine)
1260 self._facc_scalar_(x)
1261 elif xs: # _xiterable(xs)
1262 self._facc(xs)
1263 return self
1265 def fadd_(self, *xs):
1266 '''Add all positional items to this instance.
1268 @arg xs: Values to add (each C{scalar} or an L{Fsum}
1269 or L{Fsum2Tuple} instance), all positional.
1271 @see: Method L{Fsum.fadd} for further details.
1272 '''
1273 return self._facc_args(xs)
1275 def _fadd(self, other, op, **up): # in .fmath.Fhorner
1276 '''(INTERNAL) Apply C{B{self} += B{other}}.
1277 '''
1278 if _isFsum_2Tuple(other):
1279 if self._ps:
1280 self._facc_scalar(other._ps, **up)
1281 else:
1282 self._fset(other, op=op, **up)
1283 elif self._scalar(other, op):
1284 if self._ps:
1285 self._facc_scalar_(other, **up)
1286 else:
1287 self._fset(other, op=op, **up)
1288 return self
1290 fcopy = copy # for backward compatibility
1291 fdiv = __itruediv__
1292 fdivmod = __divmod__
1294 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1295 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1296 '''
1297 # result mostly follows CPython function U{float_divmod
1298 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1299 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1300 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1301 if q: # == float // other == floor(float / other)
1302 self -= self._Fsum_as(q) * other # NOT other * q!
1304 s = signOf(other) # make signOf(self) == signOf(other)
1305 if s and self.signOf() == -s: # PYCHOK no cover
1306 self += other
1307 q -= 1
1308# t = self.signOf()
1309# if t and t != s:
1310# raise self._Error(op, other, _AssertionError, txt__=signOf)
1311 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1313 def _fhorner(self, x, cs, op, incx=True): # in .fmath
1314 '''(INTERNAL) Add an L{Fhorner} evaluation of polynomial
1315 C{sum(cs[i] * B{x}**i for i=0..len(cs)-1) if B{incx}
1316 else sum(... i=len(cs)-1..0)}.
1317 '''
1318 if _xiterablen(cs):
1319 H = self._Fsum_as(name__=self._fhorner)
1320 if _isFsum_2Tuple(x):
1321 _mul = H._mul_Fsum
1322 else:
1323 _mul = H._mul_scalar
1324 x = _2float(x=x, **self._isfine)
1325 if len(cs) > 1 and x:
1326 for c in (reversed(cs) if incx else cs):
1327 H._fset_ps(_mul(x, op))
1328 H._fadd(c, op, up=False)
1329 else: # x == 0
1330 H = cs[0] if cs else _0_0
1331 self._fadd(H, op)
1332 return self
1334 def _finite(self, other, op=None):
1335 '''(INTERNAL) Return B{C{other}} if C{finite}.
1336 '''
1337 if _isOK_or_finite(other, **self._isfine):
1338 return other
1339 E = _NonfiniteError(other)
1340 raise self._Error(op, other, E, txt=_not_finite_)
1342 def fint(self, name=NN, **raiser_RESIDUAL):
1343 '''Return this instance' current running sum as C{integer}.
1345 @kwarg name: Optional, overriding C{B{name}="fint"} (C{str}).
1346 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1347 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1348 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1350 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1351 with a zero or insignificant I{integer} residual.
1353 @raise ResidualError: Non-zero, significant residual or invalid
1354 B{C{RESIDUAL}}.
1356 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1357 '''
1358 i, r = self._fint2
1359 if r:
1360 R = self._raiser(r, i, **raiser_RESIDUAL)
1361 if R:
1362 t = _stresidual(_integer_, r, **R)
1363 raise ResidualError(_integer_, i, txt=t)
1364 return self._Fsum_as(i, name=_name__(name, name__=self.fint))
1366 def fint2(self, **name):
1367 '''Return this instance' current running sum as C{int} and the
1368 I{integer} residual.
1370 @kwarg name: Optional name (C{str}).
1372 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1373 an C{int} and I{integer} C{residual} a C{float} or
1374 C{INT0} if the C{fsum} is considered to be I{exact}.
1375 The C{fsum} is I{non-finite} if this instance is.
1376 '''
1377 return Fsum2Tuple(*self._fint2, **name)
1379 @Property
1380 def _fint2(self): # see ._fset
1381 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1382 '''
1383 s, _ = self._fprs2
1384 try:
1385 i = int(s)
1386 r = (self._ps_1sum(i) if len(self._ps) > 1 else
1387 float(s - i)) or INT0
1388 except (OverflowError, ValueError) as X:
1389 r = _NONFINITEr # INF, NAN, NINF
1390 i = self._fintX(X, sum(self._ps))
1391 return i, r # Fsum2Tuple?
1393 @_fint2.setter_ # PYCHOK setter_UNDERscore!
1394 def _fint2(self, s): # in _fset
1395 '''(INTERNAL) Replace the C{_fint2} value.
1396 '''
1397 try:
1398 i = int(s)
1399 r = (s - i) or INT0
1400 except (OverflowError, ValueError) as X:
1401 r = _NONFINITEr # INF, NAN, NINF
1402 i = self._fintX(X, float(s))
1403 return i, r # like _fint2.getter
1405 def _fintX(self, X, i): # PYCHOK X
1406 '''(INTERNAL) Handle I{non-finite} C{int}.
1407 '''
1408 # "cannot convert float infinity to integer"
1409 return i # ignore such Overflow-/ValueErrors
1410 # op = int.__name__
1411 # return self._nonfiniteX(X, op, i)
1413 @deprecated_property_RO
1414 def float_int(self): # PYCHOK no cover
1415 '''DEPRECATED, use method C{Fsum.int_float}.'''
1416 return self.int_float() # raiser=False
1418 @property_RO
1419 def floor(self):
1420 '''Get this instance' C{floor} (C{int} in Python 3+, but
1421 C{float} in Python 2-).
1423 @note: This C{floor} takes the C{residual} into account.
1425 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1426 L{Fsum.imag} and L{Fsum.real}.
1427 '''
1428 s, r = self._fprs2
1429 f = _floor(s) + _floor(r) + 1
1430 while (f - s) > r: # f > (s + r)
1431 f -= 1
1432 return f # _floor(self._n_d)
1434# ffloordiv = __ifloordiv__ # for naming consistency?
1435# floordiv = __floordiv__ # for naming consistency?
1437 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1438 '''Apply C{B{self} //= B{other}}.
1439 '''
1440 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1441 return self._fset(q.floor) # floor(q)
1443 def fma(self, other1, other2, **nonfinites): # in .fmath.fma
1444 '''Fused-multiply-add C{self *= B{other1}; self += B{other2}}.
1446 @arg other1: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1447 @arg other2: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1448 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{False}, to
1449 override L{nonfinites<Fsum.nonfinites>} and
1450 L{nonfiniterrors} default (C{bool}).
1451 '''
1452 op = self.fma.__name__
1453 _fs = self._ps_other
1454 try:
1455 s, r = self._fprs2
1456 if r:
1457 f = self._f2mul(self.fma, other1, **nonfinites)
1458 f += other2
1459 else:
1460 fs = _2split3s(_fs(op, other1))
1461 fs = _2products(s, fs, *_fs(op, other2))
1462 f = _Psum(self._ps_acc([], fs, up=False), name=op)
1463 except TypeError as X:
1464 raise self._ErrorX(X, op, (other1, other2))
1465 except (OverflowError, ValueError) as X: # from math.fma
1466 f = self._mul_reduce(op, s, other1) # INF, NAN, NINF
1467 f = sum(_fs(op, f, other2))
1468 f = self._nonfiniteX(X, op, f, **nonfinites)
1469 return self._fset(f)
1471 fmul = __imul__
1473 def _fmul(self, other, op):
1474 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1475 '''
1476 if _isFsum_2Tuple(other):
1477 if len(self._ps) != 1:
1478 f = self._mul_Fsum(other, op)
1479 elif len(other._ps) != 1: # and len(self._ps) == 1
1480 f = self._ps_mul(op, *other._ps) if other._ps else _0_0
1481 elif self._f2product: # len(other._ps) == 1
1482 f = self._mul_scalar(other._ps[0], op)
1483 else: # len(other._ps) == len(self._ps) == 1
1484 f = self._finite(self._ps[0] * other._ps[0], op=op)
1485 else:
1486 s = self._scalar(other, op)
1487 f = self._mul_scalar(s, op)
1488 return self._fset(f) # n=len(self) + 1
1490 @deprecated_method
1491 def f2mul(self, *others, **raiser):
1492 '''DEPRECATED on 2024.09.13, use method L{f2mul_<Fsum.f2mul_>}.'''
1493 return self._fset(self.f2mul_(*others, **raiser))
1495 def f2mul_(self, *others, **nonfinites): # in .fmath.f2mul
1496 '''Return C{B{self} * B{other} * B{other} ...} for all B{C{others}} using cascaded,
1497 accurate multiplication like with L{f2product<Fsum.f2product>} set to C{True}.
1499 @arg others: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
1500 positional.
1501 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{False}, to override both
1502 L{nonfinites<Fsum.nonfinites>} and the L{nonfiniterrors}
1503 default (C{bool}).
1505 @return: The cascaded I{TwoProduct} (L{Fsum} or C{float}).
1507 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
1508 '''
1509 return self._f2mul(self.f2mul_, *others, **nonfinites)
1511 def _f2mul(self, where, *others, **nonfinites_raiser):
1512 '''(INTERNAL) See methods C{fma} and C{f2mul_}.
1513 '''
1514 f = self._copy_2(where)
1515 ps = f._ps
1516 if ps and others:
1517 op = where.__name__
1518 try:
1519 for other in others: # to pinpoint errors
1520 for p in self._ps_other(op, other):
1521 pfs = _2products(p, _2split3s(ps))
1522 ps[:] = f._ps_acc([], pfs, up=False)
1523 f._update()
1524 except TypeError as X:
1525 raise self._ErrorX(X, op, other)
1526 except (OverflowError, ValueError) as X:
1527 r = self._mul_reduce(op, sum(ps), other) # INF, NAN, NINF
1528 r = self._nonfiniteX(X, op, r, **nonfinites_raiser)
1529 f._fset(r)
1530 return f
1532 def fover(self, over, **raiser_RESIDUAL):
1533 '''Apply C{B{self} /= B{over}} and summate.
1535 @arg over: An L{Fsum} or C{scalar} denominator.
1536 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1537 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1538 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1540 @return: Precision running sum (C{float}).
1542 @raise ResidualError: Non-zero, significant residual or invalid
1543 B{C{RESIDUAL}}.
1545 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1546 '''
1547 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1549 fpow = __ipow__
1551 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1552 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1553 '''
1554 if mod:
1555 if mod[0] is not None: # == 3-arg C{pow}
1556 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1557 elif self.is_integer():
1558 # return an exact C{int} for C{int}**C{int}
1559 i, _ = self._fint2 # assert _ == 0
1560 x, r = _2scalar2(other) # C{int}, C{float} or other
1561 f = self._Fsum_as(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1562 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1563 else: # mod[0] is None, power(self, other)
1564 f = self._pow(other, other, op, **raiser_RESIDUAL)
1565 else: # pow(self, other)
1566 f = self._pow(other, other, op, **raiser_RESIDUAL)
1567 return self._fset(f) # n=max(len(self), 1)
1569 def f2product(self, *two):
1570 '''Get and set accurate I{TwoProduct} multiplication for this
1571 L{Fsum}, overriding the L{f2product} default.
1573 @arg two: If omitted, leave the override unchanged, if C{True},
1574 turn I{TwoProduct} on, if C{False} off, if C{None}e
1575 remove th override (C{bool} or C{None}).
1577 @return: The previous setting (C{bool} or C{None} if not set).
1579 @see: Function L{f2product<fsums.f2product>}.
1581 @note: Use C{f.f2product() or f2product()} to determine whether
1582 multiplication is accurate for L{Fsum} C{f}.
1583 '''
1584 if two: # delattrof(self, _f2product=None)
1585 t = _xkwds_pop(self.__dict__, _f2product=None)
1586 if two[0] is not None:
1587 self._f2product = bool(two[0])
1588 else: # getattrof(self, _f2product=None)
1589 t = _xkwds_get(self.__dict__, _f2product=None)
1590 return t
1592 @Property
1593 def _fprs(self):
1594 '''(INTERNAL) Get and cache this instance' precision
1595 running sum (C{float} or C{int}), ignoring C{residual}.
1597 @note: The precision running C{fsum} after a C{//=} or
1598 C{//} C{floor} division is C{int} in Python 3+.
1599 '''
1600 s, _ = self._fprs2
1601 return s # ._fprs2.fsum
1603 @_fprs.setter_ # PYCHOK setter_UNDERscore!
1604 def _fprs(self, s):
1605 '''(INTERNAL) Replace the C{_fprs} value.
1606 '''
1607 return s
1609 @Property
1610 def _fprs2(self):
1611 '''(INTERNAL) Get and cache this instance' precision
1612 running sum and residual (L{Fsum2Tuple}).
1613 '''
1614 ps = self._ps
1615 n = len(ps)
1616 try:
1617 if n > 2:
1618 s = _psum(ps, **self._isfine)
1619 if not _isfinite(s):
1620 ps[:] = s, # collapse ps
1621 return Fsum2Tuple(s, _NONFINITEr)
1622 n = len(ps)
1623# Fsum._ps_max = max(Fsum._ps_max, n)
1624 if n > 2:
1625 r = self._ps_1sum(s)
1626 return Fsum2Tuple(*_s_r(s, r))
1627 if n > 1: # len(ps) == 2
1628 s, r = _s_r(*_2sum(*ps, **self._isfine))
1629 ps[:] = (r, s) if r else (s,)
1630 elif ps: # len(ps) == 1
1631 s = ps[0]
1632 r = INT0 if _isfinite(s) else _NONFINITEr
1633 else: # len(ps) == 0
1634 s, r = _0_0, INT0
1635 ps[:] = s,
1636 except (OverflowError, ValueError) as X:
1637 op = sum.__name__ # INF, NAN, NINF
1638 ps[:] = sum(ps), # collapse ps
1639 s = self._nonfiniteX(X, op, ps[0])
1640 r = _NONFINITEr
1641 # assert self._ps is ps
1642 return Fsum2Tuple(s, r)
1644 @_fprs2.setter_ # PYCHOK setter_UNDERscore!
1645 def _fprs2(self, s_r):
1646 '''(INTERNAL) Replace the C{_fprs2} value.
1647 '''
1648 return Fsum2Tuple(s_r)
1650 def fset_(self, *xs):
1651 '''Apply C{B{self}.partials = Fsum(*B{xs}).partials}.
1653 @arg xs: Optional, new values (each C{scalar} or
1654 an L{Fsum} or L{Fsum2Tuple} instance), all
1655 positional.
1657 @return: This instance, replaced (C{Fsum}).
1659 @see: Method L{Fsum.fadd} for further details.
1660 '''
1661 f = self._Fsum_as(*xs)
1662 return self._fset(f, up=False, op=_fset_op_)
1664 def _fset(self, other, n=0, up=True, **op):
1665 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1666 '''
1667 if other is self:
1668 pass # from ._fmul, ._ftruediv and ._pow_0_1
1669 elif _isFsum_2Tuple(other):
1670 self._ps[:] = other._ps
1671 self._n = n or other._n
1672 if up: # use or zap the C{Property_RO} values
1673 Fsum._fint2._update_from(self, other)
1674 Fsum._fprs ._update_from(self, other)
1675 Fsum._fprs2._update_from(self, other)
1676 elif isscalar(other):
1677 s = float(self._finite(other, **op)) if op else other
1678 self._ps[:] = s,
1679 self._n = n or 1
1680 if up: # Property _fint2, _fprs and _fprs2 all have
1681 # @.setter_underscore and NOT @.setter because the
1682 # latter's _fset zaps the value set by @.setter
1683 self._fint2 = s
1684 self._fprs = s
1685 self._fprs2 = s, INT0
1686 # assert self._fprs is s
1687 else:
1688 op = _xkwds_get1(op, op=_fset_op_)
1689 raise self._Error(op, other, _TypeError)
1690 return self
1692 def _fset_ps(self, other): # in .fmath._Fsum__init__
1693 '''(INTERNAL) Set partials from a known C{other}.
1694 '''
1695 return self._fset(other, up=False)
1697 def fsub(self, xs=()):
1698 '''Subtract an iterable's items from this instance.
1700 @see: Method L{Fsum.fadd} for further details.
1701 '''
1702 return self._facc_neg(xs)
1704 def fsub_(self, *xs):
1705 '''Subtract all positional items from this instance.
1707 @see: Method L{Fsum.fadd_} for further details.
1708 '''
1709 return self._facc_neg(xs, origin=1) if len(xs) != 1 else \
1710 self._fsub(xs[0], _sub_op_)
1712 def _fsub(self, other, op):
1713 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1714 '''
1715 if _isFsum_2Tuple(other):
1716 if other is self: # or other._fprs2 == self._fprs2:
1717 self._fset(_0_0, n=len(self) * 2)
1718 elif other._ps:
1719 self._facc_scalar(other._ps_neg)
1720 elif self._scalar(other, op):
1721 self._facc_scalar_(-other)
1722 return self
1724 def fsum(self, xs=()):
1725 '''Add an iterable's items, summate and return the current
1726 precision running sum.
1728 @arg xs: Iterable of items to add (each item C{scalar}
1729 or an L{Fsum} or L{Fsum2Tuple} instance).
1731 @return: Precision running sum (C{float} or C{int}).
1733 @see: Method L{Fsum.fadd}.
1735 @note: Accumulation can continue after summation.
1736 '''
1737 return self._facc(xs)._fprs
1739 def fsum_(self, *xs):
1740 '''Add any positional items, summate and return the current
1741 precision running sum.
1743 @arg xs: Items to add (each C{scalar} or an L{Fsum}
1744 or L{Fsum2Tuple} instance), all positional.
1746 @return: Precision running sum (C{float} or C{int}).
1748 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1749 '''
1750 return self._facc_args(xs)._fprs
1752 def Fsum_(self, *xs, **name):
1753 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1755 @kwarg name: Optional name (C{str}).
1757 @return: Copy of this updated instance (L{Fsum}).
1758 '''
1759 return self._facc_args(xs)._copy_2(self.Fsum_, **name)
1761 def Fsum2Tuple_(self, *xs, **name):
1762 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1764 @kwarg name: Optional name (C{str}).
1766 @return: Precision running sum (L{Fsum2Tuple}).
1767 '''
1768 return Fsum2Tuple(self._facc_args(xs)._fprs2, **name)
1770 @property_RO
1771 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, for C{_2floats}, .fstats
1772 return self # NOT @Property_RO, see .copy and ._copy_2
1774 def _Fsum_as(self, *xs, **name_f2product_nonfinites_RESIDUAL):
1775 '''(INTERNAL) Return an C{Fsum} with this C{Fsum}'s C{.f2product},
1776 C{.nonfinites} and C{.RESIDUAL} setting, optionally
1777 overridden with C{name_f2product_nonfinites_RESIDUAL} and
1778 with any C{xs} accumulated.
1779 '''
1780 kwds = _xkwds_not(None, Fsum._RESIDUAL, f2product =self.f2product(),
1781 nonfinites=self.nonfinites(),
1782 RESIDUAL =self.RESIDUAL())
1783 if name_f2product_nonfinites_RESIDUAL: # overwrites
1784 kwds.update(name_f2product_nonfinites_RESIDUAL)
1785 F = Fsum(**kwds)
1786 # assert all(v == self.__dict__[n] for n, v in F.__dict__.items())
1787 return F._fset(xs[0], op=_fset_op_) if len(xs) == 1 else (
1788 F._facc(xs, up=False) if xs else F)
1790 def fsum2(self, xs=(), **name):
1791 '''Add an iterable's items, summate and return the
1792 current precision running sum I{and} the C{residual}.
1794 @arg xs: Iterable of items to add (each item C{scalar}
1795 or an L{Fsum} or L{Fsum2Tuple} instance).
1796 @kwarg name: Optional C{B{name}=NN} (C{str}).
1798 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1799 current precision running sum and C{residual}, the
1800 (precision) sum of the remaining C{partials}. The
1801 C{residual is INT0} if the C{fsum} is considered
1802 to be I{exact}.
1804 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1805 '''
1806 t = self._facc(xs)._fprs2
1807 return t.dup(name=name) if name else t
1809 def fsum2_(self, *xs):
1810 '''Add any positional items, summate and return the current
1811 precision running sum and the I{differential}.
1813 @arg xs: Values to add (each C{scalar} or an L{Fsum} or
1814 L{Fsum2Tuple} instance), all positional.
1816 @return: 2Tuple C{(fsum, delta)} with the current, precision
1817 running C{fsum} like method L{Fsum.fsum} and C{delta},
1818 the difference with previous running C{fsum}, C{float}.
1820 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1821 '''
1822 return self._fsum2(xs, self._facc_args)
1824 def _fsum2(self, xs, _facc, **facc_kwds):
1825 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1826 '''
1827 p, q = self._fprs2
1828 if xs:
1829 s, r = _facc(xs, **facc_kwds)._fprs2
1830 if _isfinite(s): # _fsum(_1primed((s, -p, r, -q))
1831 d, r = _2sum(s - p, r - q, _isfine=_isOK)
1832 r, _ = _s_r(d, r)
1833 return s, (r if _isfinite(r) else _NONFINITEr)
1834 else:
1835 return p, _0_0
1837 def fsumf_(self, *xs):
1838 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}}, each I{known to be}
1839 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1840 '''
1841 return self._facc_scalarf(xs, origin=1, which=self.fsumf_)._fprs
1843 def Fsumf_(self, *xs):
1844 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}}, each I{known to be}
1845 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1846 '''
1847 return self._facc_scalarf(xs, origin=1, which=self.Fsumf_)._copy_2(self.Fsumf_)
1849 def fsum2f_(self, *xs):
1850 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}}, each I{known to be}
1851 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1852 '''
1853 return self._fsum2(xs, self._facc_scalarf, origin=1, which=self.fsum2f_)
1855# ftruediv = __itruediv__ # for naming consistency?
1857 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1858 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1859 '''
1860 n = _1_0
1861 if _isFsum_2Tuple(other):
1862 if other is self or self == other:
1863 return self._fset(n, n=len(self))
1864 d, r = other._fprs2
1865 if r:
1866 R = self._raiser(r, d, **raiser_RESIDUAL)
1867 if R:
1868 raise self._ResidualError(op, other, r, **R)
1869 d, n = other.as_integer_ratio()
1870 else:
1871 d = self._scalar(other, op)
1872 try:
1873 s = n / d
1874 except Exception as X:
1875 raise self._ErrorX(X, op, other)
1876 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1877 return self._fset(f)
1879 @property_RO
1880 def imag(self):
1881 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1883 @see: Property L{Fsum.real}.
1884 '''
1885 return _0_0
1887 def int_float(self, **raiser_RESIDUAL):
1888 '''Return this instance' current running sum as C{int} or C{float}.
1890 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1891 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1892 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1894 @return: This C{int} sum if this instance C{is_integer}, otherwise
1895 the C{float} sum if the residual is zero or not significant.
1897 @raise ResidualError: Non-zero, significant residual or invalid
1898 B{C{RESIDUAL}}.
1900 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.is_integer},
1901 L{Fsum.RESIDUAL} and property L{Fsum.as_iscalar}.
1902 '''
1903 s, r = self._fint2
1904 if r:
1905 s, r = self._fprs2
1906 if r: # PYCHOK no cover
1907 R = self._raiser(r, s, **raiser_RESIDUAL)
1908 if R:
1909 t = _stresidual(_non_zero_, r, **R)
1910 raise ResidualError(int_float=s, txt=t)
1911 s = float(s)
1912 return s
1914 def is_exact(self):
1915 '''Is this instance' running C{fsum} considered to be exact?
1916 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1917 '''
1918 return self.residual is INT0
1920 def is_finite(self): # in .constants
1921 '''Is this instance C{finite}? (C{bool}).
1923 @see: Function L{isfinite<pygeodesy.isfinite>}.
1924 '''
1925 return _isfinite(sum(self._ps)) # == sum(self)
1927 def is_integer(self):
1928 '''Is this instance' running sum C{integer}? (C{bool}).
1930 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1931 '''
1932 s, r = self._fint2
1933 return False if r else (_isfinite(s) and isint(s))
1935 def is_math_fma(self):
1936 '''Is accurate L{f2product} multiplication based on Python's C{math.fma}?
1938 @return: C{True} if accurate multiplication uses C{math.fma}, C{False}
1939 an C{fma} implementation as C{math.fma} or C{None}, a previous
1940 C{PyGeodesy} implementation.
1941 '''
1942 return (_2split3s is _passarg) or (False if _2n_d is None else None)
1944 def is_math_fsum(self):
1945 '''Are the summation functions L{fsum}, L{fsum_}, L{fsumf_}, L{fsum1},
1946 L{fsum1_} and L{fsum1f_} based on Python's C{math.fsum}?
1948 @return: C{True} if summation functions use C{math.fsum}, C{False}
1949 otherwise.
1950 '''
1951 return _sum is _fsum # _fsum.__module__ is fabs.__module__
1953 def is_scalar(self, **raiser_RESIDUAL):
1954 '''Is this instance' running sum C{scalar} without residual or with
1955 a residual I{ratio} not exceeding the RESIDUAL threshold?
1957 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1958 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1959 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1961 @return: C{True} if this instance' non-zero residual C{ratio} exceeds
1962 the L{RESIDUAL<Fsum.RESIDUAL>} threshold (C{bool}).
1964 @raise ResidualError: Non-zero, significant residual or invalid
1965 B{C{RESIDUAL}}.
1967 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property
1968 L{Fsum.as_iscalar}.
1969 '''
1970 s, r = self._fprs2
1971 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1973 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1974 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1975 '''
1976 # assert _isFsum_2Tuple(other)
1977 if self._ps and other._ps:
1978 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
1979 else:
1980 f = _0_0
1981 return f
1983 def _mul_reduce(self, op, start, *others):
1984 '''(INTERNAL) Like fmath.freduce(_operator.mul, ...)
1985 for I{non-finite} C{start} and/or C{others}.
1986 '''
1987 for p in self._ps_other(op, *others):
1988 start *= p
1989 return start
1991 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1992 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
1993 '''
1994 # assert isscalar(factor)
1995 if self._ps and self._finite(factor, op):
1996 f = self if factor == _1_0 else (
1997 self._neg if factor == _N_1_0 else
1998 self._ps_mul(op, factor).as_iscalar)
1999 else:
2000 f = _0_0
2001 return f
2003# @property_RO
2004# def _n_d(self):
2005# n, d = self.as_integer_ratio()
2006# return n / d
2008 @property_RO
2009 def _neg(self):
2010 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
2011 '''
2012 return _Psum(self._ps_neg) if self._ps else NEG0
2014 def nonfinites(self, *OK):
2015 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan}
2016 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively
2017 C{ValueError} exceptions, overriding the L{nonfiniterrors} default.
2019 @arg OK: If omitted, leave the override unchanged, if C{True},
2020 I{non-finites} are C{OK}, if C{False} throw exceptions
2021 or if C{None} remove the override (C{bool} or C{None}).
2023 @return: The previous setting (C{bool} or C{None} if not set).
2025 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}.
2027 @note: Use property L{nonfinitesOK<Fsum.nonfinitesOK>} to determine
2028 whether I{non-finites} are C{OK} for this L{Fsum} and by the
2029 L{nonfiniterrors} default.
2030 '''
2031 _ks = Fsum._nonfinites_isfine_kwds
2032 if OK: # delattrof(self, _isfine=None)
2033 k = _xkwds_pop(self.__dict__, _isfine=None)
2034 if OK[0] is not None:
2035 self._isfine = _ks[bool(OK[0])]
2036 self._update()
2037 else: # getattrof(self, _isfine=None)
2038 k = _xkwds_get(self.__dict__, _isfine=None)
2039 # dict(map(reversed, _ks.items())).get(k, None)
2040 # raises a TypeError: unhashable type: 'dict'
2041 return True if k is _ks[True] else (
2042 False if k is _ks[False] else None)
2044 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK),
2045 False: dict(_isfine=_isfinite)}
2047 @property_RO
2048 def nonfinitesOK(self):
2049 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}).
2050 '''
2051 nf = self.nonfinites()
2052 if nf is None:
2053 nf = not nonfiniterrors()
2054 return nf
2056 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None):
2057 '''(INTERNAL) Handle a I{non-finite} exception.
2058 '''
2059 if nonfinites is None:
2060 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser)
2061 if not nonfinites:
2062 raise self._ErrorX(X, op, f)
2063 return f
2065 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL):
2066 '''(INTERNAL) Re/set options from keyword arguments.
2067 '''
2068 if f2product is not None:
2069 self.f2product(f2product)
2070 if nonfinites is not None:
2071 self.nonfinites(nonfinites)
2072 if name_RESIDUAL: # MUST be last
2073 n, kwds = _name2__(**name_RESIDUAL)
2074 if kwds:
2075 R = Fsum._RESIDUAL
2076 t = _threshold(R, **kwds)
2077 if t != R:
2078 self._RESIDUAL = t
2079 if n:
2080 self.name = n # self.rename(n)
2082 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over
2083 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
2084 '''
2085 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
2087 @property_RO
2088 def partials(self):
2089 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
2090 '''
2091 return tuple(self._ps)
2093 def pow(self, x, *mod, **raiser_RESIDUAL):
2094 '''Return C{B{self}**B{x}} as L{Fsum}.
2096 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2097 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
2098 C{pow(B{self}, B{other}, B{mod})} version.
2099 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
2100 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
2101 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2103 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
2104 result (L{Fsum}).
2106 @raise ResidualError: Non-zero, significant residual or invalid
2107 B{C{RESIDUAL}}.
2109 @note: If B{C{mod}} is given and C{None}, the result will be an
2110 C{integer} L{Fsum} provided this instance C{is_integer}
2111 or set to C{integer} by an L{Fsum.fint} call.
2113 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
2114 and L{Fsum.root}.
2115 '''
2116 f = self._copy_2(self.pow)
2117 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
2119 def _pow(self, other, unused, op, **raiser_RESIDUAL):
2120 '''Return C{B{self} ** B{other}}.
2121 '''
2122 if _isFsum_2Tuple(other):
2123 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
2124 elif self._scalar(other, op):
2125 x = self._finite(other, op)
2126 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2127 else:
2128 f = self._pow_0_1(0, other)
2129 return f
2131 def _pow_0_1(self, x, other):
2132 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
2133 '''
2134 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
2136 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
2137 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
2138 B{x}, int B{mod} or C{None})}, embellishing errors.
2139 '''
2141 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
2142 m = mod[0]
2143 # assert _isFsum_2Tuple(b)
2145 def _s(s, r):
2146 R = self._raiser(r, s, **raiser_RESIDUAL)
2147 if R:
2148 raise self._ResidualError(op, other, r, mod=m, **R)
2149 return s
2151 b = _s(*(b._fprs2 if m is None else b._fint2))
2152 x = _s(*_2scalar2(x))
2154 try:
2155 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
2156 s = pow(b, x, *mod)
2157 if iscomplex(s):
2158 # neg**frac == complex in Python 3+, but ValueError in 2-
2159 raise ValueError(_strcomplex(s, b, x, *mod))
2160 return self._finite(s)
2161 except Exception as X:
2162 raise self._ErrorX(X, op, other, *mod)
2164 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
2165 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}.
2166 '''
2167 # assert _isFsum_2Tuple(other)
2168 x, r = other._fprs2
2169 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2170 if f and r:
2171 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
2172 return f
2174 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
2175 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
2176 '''
2177 # assert isint(x) and x >= 0
2178 ps = self._ps
2179 if len(ps) > 1:
2180 _mul_Fsum = Fsum._mul_Fsum
2181 if x > 4:
2182 p = self
2183 f = self if (x & 1) else self._Fsum_as(_1_0)
2184 m = x >> 1 # // 2
2185 while m:
2186 p = _mul_Fsum(p, p, op) # p **= 2
2187 if (m & 1):
2188 f = _mul_Fsum(f, p, op) # f *= p
2189 m >>= 1 # //= 2
2190 elif x > 1: # self**2, 3, or 4
2191 f = _mul_Fsum(self, self, op)
2192 if x > 2: # self**3 or 4
2193 p = self if x < 4 else f
2194 f = _mul_Fsum(f, p, op)
2195 else: # self**1 or self**0 == 1 or _1_0
2196 f = self._pow_0_1(x, other)
2197 elif ps: # self._ps[0]**x
2198 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
2199 else: # PYCHOK no cover
2200 # 0**pos_int == 0, but 0**0 == 1
2201 f = 0 if x else 1
2202 return f
2204 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
2205 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
2206 '''
2207 s, r = self._fprs2
2208 if r:
2209 # assert s != 0
2210 if isint(x, both=True): # self**int
2211 x = int(x)
2212 y = abs(x)
2213 if y > 1:
2214 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
2215 if x > 0: # i.e. > 1
2216 return f # Fsum or scalar
2217 # assert x < 0 # i.e. < -1
2218 if _isFsum(f):
2219 s, r = f._fprs2
2220 if r:
2221 return self._1_Over(f, op, **raiser_RESIDUAL)
2222 else: # scalar
2223 s = f
2224 # use s**(-1) to get the CPython
2225 # float_pow error iff s is zero
2226 x = -1
2227 elif x < 0: # self**(-1)
2228 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self
2229 else: # self**1 or self**0
2230 return self._pow_0_1(x, other) # self, 1 or 1.0
2231 else: # self**fractional
2232 R = self._raiser(r, s, **raiser_RESIDUAL)
2233 if R:
2234 raise self._ResidualError(op, other, r, **R)
2235 n, d = self.as_integer_ratio()
2236 if abs(n) > abs(d):
2237 n, d, x = d, n, (-x)
2238 s = n / d
2239 # assert isscalar(s) and isscalar(x)
2240 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
2242 def _ps_acc(self, ps, xs, up=True, **unused):
2243 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.
2244 '''
2245 n = 0
2246 _2s = _2sum
2247 _fi = self._isfine
2248 for x in (tuple(xs) if xs is ps else xs):
2249 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine)
2250 if x:
2251 i = 0
2252 for p in ps:
2253 x, p = _2s(x, p, **_fi)
2254 if p:
2255 ps[i] = p
2256 i += 1
2257 ps[i:] = (x,) if x else ()
2258 n += 1
2259 if n:
2260 self._n += n
2261# if _fi: # collapse ps if non-finite
2262# x = sum(ps)
2263# if not _isfinite(x):
2264# ps[:] = x,
2265 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
2266 if up:
2267 self._update()
2268 return ps
2270 def _ps_mul(self, op, *factors):
2271 '''(INTERNAL) Multiply this instance' C{partials} with
2272 each scalar C{factor} and accumulate into an C{Fsum}.
2273 '''
2274 def _psfs(ps, fs, _isfine=_isfinite):
2275 if len(ps) < len(fs):
2276 ps, fs = fs, ps
2277 if self._f2product:
2278 fs, p = _2split3s(fs), fs
2279 if len(ps) > 1 and fs is not p:
2280 fs = tuple(fs) # several ps
2281 _pfs = _2products
2282 else:
2283 def _pfs(p, fs):
2284 return (p * f for f in fs)
2286 for p in ps:
2287 for f in _pfs(p, fs):
2288 yield f if _isfine(f) else self._finite(f, op)
2290 fs = _psfs(self._ps, factors, **self._isfine)
2291 f = _Psum(self._ps_acc([], fs, up=False), name=op)
2292 return f
2294 @property_RO
2295 def _ps_neg(self):
2296 '''(INTERNAL) Yield the partials, I{negated}.
2297 '''
2298 for p in self._ps:
2299 yield -p
2301 def _ps_other(self, op, *others):
2302 '''(INTERNAL) Yield all C{other}s as C{scalar}.
2303 '''
2304 for other in others:
2305 if _isFsum_2Tuple(other):
2306 for p in other._ps:
2307 yield p
2308 else:
2309 yield self._scalar(other, op)
2311 def _ps_1sum(self, *less):
2312 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
2313 '''
2314 def _1psls(ps, ls):
2315 yield _1_0
2316 for p in ps:
2317 yield p
2318 for p in ls:
2319 yield -p
2320 yield _N_1_0
2322 return _fsum(_1psls(self._ps, less))
2324 def _raiser(self, r, s, raiser=True, **RESIDUAL):
2325 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
2326 I{and} is residual C{r} I{non-zero} or I{significant} (for a
2327 negative respectively positive C{RESIDUAL} threshold)?
2328 '''
2329 if r and raiser:
2330 t = self._RESIDUAL
2331 if RESIDUAL:
2332 t = _threshold(t, **RESIDUAL)
2333 if t < 0 or (s + r) != s:
2334 q = (r / s) if s else s # == 0.
2335 if fabs(q) > fabs(t):
2336 return dict(ratio=q, R=t)
2337 return {}
2339 rdiv = __rtruediv__
2341 @property_RO
2342 def real(self):
2343 '''Get the C{real} part of this instance (C{float}).
2345 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
2346 and properties L{Fsum.ceil}, L{Fsum.floor},
2347 L{Fsum.imag} and L{Fsum.residual}.
2348 '''
2349 return float(self)
2351 @property_RO
2352 def residual(self):
2353 '''Get this instance' residual or residue (C{float} or C{int}):
2354 the C{sum(partials)} less the precision running sum C{fsum}.
2356 @note: The C{residual is INT0} iff the precision running
2357 C{fsum} is considered to be I{exact}.
2359 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
2360 '''
2361 return self._fprs2.residual
2363 def RESIDUAL(self, *threshold):
2364 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
2365 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
2367 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
2368 L{ResidualError}s in division and exponention, if
2369 C{None}, restore the default set with env variable
2370 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
2371 current setting.
2373 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
2375 @raise ResidualError: Invalid B{C{threshold}}.
2377 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}
2378 C{residual / fsum} exceeds the given B{C{threshold}} and (2)
2379 the C{residual} is non-zero and (3) is I{significant} vs the
2380 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional
2381 keyword argument C{raiser=False} is missing. Specify a
2382 negative B{C{threshold}} for only non-zero C{residual}
2383 testing without the I{significant} case.
2384 '''
2385 r = self._RESIDUAL
2386 if threshold:
2387 t = threshold[0]
2388 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
2389 (_0_0 if t else _1_0) if isbool(t) else
2390 _threshold(t)) # ... backward compatibility
2391 return r
2393 def _ResidualError(self, op, other, residual, **mod_R):
2394 '''(INTERNAL) Non-zero B{C{residual}} etc.
2395 '''
2396 def _p(mod=None, R=0, **unused): # ratio=0
2397 return (_non_zero_ if R < 0 else _significant_) \
2398 if mod is None else _integer_
2400 t = _stresidual(_p(**mod_R), residual, **mod_R)
2401 return self._Error(op, other, ResidualError, txt=t)
2403 def root(self, root, **raiser_RESIDUAL):
2404 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
2406 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2407 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any
2408 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar}
2409 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2411 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
2413 @raise ResidualError: Non-zero, significant residual or invalid
2414 B{C{RESIDUAL}}.
2416 @see: Method L{Fsum.pow}.
2417 '''
2418 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL)
2419 f = self._copy_2(self.root)
2420 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
2422 def _scalar(self, other, op, **txt):
2423 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}.
2424 '''
2425 if isscalar(other):
2426 return other
2427 raise self._Error(op, other, _TypeError, **txt) # _invalid_
2429 def signOf(self, res=True):
2430 '''Determine the sign of this instance.
2432 @kwarg res: If C{True}, consider the residual,
2433 otherwise ignore the latter (C{bool}).
2435 @return: The sign (C{int}, -1, 0 or +1).
2436 '''
2437 s, r = self._fprs2
2438 r = (-r) if res else 0
2439 return _signOf(s, r)
2441 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
2442 '''Return this C{Fsum} instance as representation.
2444 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
2445 for method L{Fsum.toStr}.
2447 @return: This instance (C{repr}).
2448 '''
2449 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
2451 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
2452 '''Return this C{Fsum} instance as string.
2454 @kwarg lenc: If C{True}, include the current C{[len]} of this
2455 L{Fsum} enclosed in I{[brackets]} (C{bool}).
2456 @kwarg prec_sep_fmt: Optional keyword arguments for method
2457 L{Fsum2Tuple.toStr}.
2459 @return: This instance (C{str}).
2460 '''
2461 p = self.classname
2462 if lenc:
2463 p = Fmt.SQUARE(p, len(self))
2464 n = _enquote(self.name, white=_UNDER_)
2465 t = self._fprs2.toStr(**prec_sep_fmt)
2466 return NN(p, _SPACE_, n, t)
2468 def _truediv(self, other, op, **raiser_RESIDUAL):
2469 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
2470 '''
2471 f = self._copy_2(self.__truediv__)
2472 return f._ftruediv(other, op, **raiser_RESIDUAL)
2474 def _update(self, updated=True): # see ._fset
2475 '''(INTERNAL) Zap all cached C{Property_RO} values.
2476 '''
2477 if updated:
2478 _pop = self.__dict__.pop
2479 for p in _ROs:
2480 _ = _pop(p, None)
2481# Fsum._fint2._update(self)
2482# Fsum._fprs ._update(self)
2483# Fsum._fprs2._update(self)
2484 return self # for .fset_
2486_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
2488if _NONFINITES == _std_: # PYCHOK no cover
2489 _ = nonfiniterrors(False)
2492def _Float_Int(arg, **name_Error):
2493 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit.
2494 '''
2495 U = Int if isint(arg) else Float
2496 return U(arg, **name_Error)
2499class DivMod2Tuple(_NamedTuple):
2500 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
2501 C{mod} results of a C{divmod} operation.
2503 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2504 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2505 '''
2506 _Names_ = ('div', 'mod')
2507 _Units_ = (_Float_Int, Fsum)
2510class Fsum2Tuple(_NamedTuple): # in .fstats
2511 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2512 and the C{residual}, the sum of the remaining partials. Each
2513 item is C{float} or C{int}.
2515 @note: If the C{residual is INT0}, the C{fsum} is considered
2516 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2517 '''
2518 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2519 _Units_ = (_Float_Int, _Float_Int)
2521 def __abs__(self): # in .fmath
2522 return self._Fsum.__abs__()
2524 def __bool__(self): # PYCHOK Python 3+
2525 return bool(self._Fsum)
2527 def __eq__(self, other):
2528 return self._other_op(other, self.__eq__)
2530 def __float__(self):
2531 return self._Fsum.__float__()
2533 def __ge__(self, other):
2534 return self._other_op(other, self.__ge__)
2536 def __gt__(self, other):
2537 return self._other_op(other, self.__gt__)
2539 def __le__(self, other):
2540 return self._other_op(other, self.__le__)
2542 def __lt__(self, other):
2543 return self._other_op(other, self.__lt__)
2545 def __int__(self):
2546 return self._Fsum.__int__()
2548 def __ne__(self, other):
2549 return self._other_op(other, self.__ne__)
2551 def __neg__(self):
2552 return self._Fsum.__neg__()
2554 __nonzero__ = __bool__ # Python 2-
2556 def __pos__(self):
2557 return self._Fsum.__pos__()
2559 def as_integer_ratio(self):
2560 '''Return this instance as the ratio of 2 integers.
2562 @see: Method L{Fsum.as_integer_ratio} for further details.
2563 '''
2564 return self._Fsum.as_integer_ratio()
2566 @property_RO
2567 def _fint2(self):
2568 return self._Fsum._fint2
2570 @property_RO
2571 def _fprs2(self):
2572 return self._Fsum._fprs2
2574 @Property_RO
2575 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2576 s, r = _s_r(*self)
2577 ps = (r, s) if r else (s,)
2578 return _Psum(ps, name=self.name)
2580 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL):
2581 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2582 '''
2583 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL)
2585 def is_exact(self):
2586 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2587 '''
2588 return self._Fsum.is_exact()
2590 def is_finite(self): # in .constants
2591 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}).
2593 @see: Function L{isfinite<pygeodesy.isfinite>}.
2594 '''
2595 return self._Fsum.is_finite()
2597 def is_integer(self):
2598 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2599 '''
2600 return self._Fsum.is_integer()
2602 def _mul_scalar(self, other, op): # for Fsum._fmul
2603 return self._Fsum._mul_scalar(other, op)
2605 @property_RO
2606 def _n(self):
2607 return self._Fsum._n
2609 def _other_op(self, other, which):
2610 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2611 return getattr(C, which.__name__)(s, other)
2613 @property_RO
2614 def _ps(self):
2615 return self._Fsum._ps
2617 @property_RO
2618 def _ps_neg(self):
2619 return self._Fsum._ps_neg
2621 def signOf(self, **res):
2622 '''Like method L{Fsum.signOf}.
2623 '''
2624 return self._Fsum.signOf(**res)
2626 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2627 '''Return this L{Fsum2Tuple} as string (C{str}).
2629 @kwarg fmt: Optional C{float} format (C{letter}).
2630 @kwarg prec_sep: Optional keyword arguments for function
2631 L{fstr<streprs.fstr>}.
2632 '''
2633 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2635_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2638class ResidualError(_ValueError):
2639 '''Error raised for a division, power or root operation of
2640 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2641 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2643 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2644 '''
2645 pass
2648try:
2649 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2651 # make sure _fsum works as expected (XXX check
2652 # float.__getformat__('float')[:4] == 'IEEE'?)
2653 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2654 del _fsum # nope, remove _fsum ...
2655 raise ImportError() # ... use _fsum below
2657 _sum = _fsum # in .elliptic
2658except ImportError:
2659 _sum = sum # in .elliptic
2661 def _fsum(xs):
2662 '''(INTERNAL) Precision summation, Python 2.5-.
2663 '''
2664 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True)
2665 return float(F._facc(xs, up=False))
2668def fsum(xs, nonfinites=None, **floats):
2669 '''Precision floating point summation from Python's C{math.fsum}.
2671 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2672 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if
2673 C{False} I{non-finites} raise an Overflow-/ValueError or if
2674 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}).
2675 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use
2676 keyword argument C{B{nonfinites}=False} instead.
2678 @return: Precision C{fsum} (C{float}).
2680 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow.
2682 @raise TypeError: Invalid B{C{xs}} item.
2684 @raise ValueError: Invalid or C{NAN} B{C{xs}} item.
2686 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites},
2687 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}.
2688 '''
2689 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0
2692def fsum_(*xs, **nonfinites):
2693 '''Precision floating point summation of all positional items.
2695 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2696 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2698 @see: Function L{fsum<fsums.fsum>} for further details.
2699 '''
2700 return _xsum(fsum_, xs, origin=1, **nonfinites) if xs else _0_0
2703def fsumf_(*xs):
2704 '''Precision floating point summation of all positional items with I{non-finites} C{OK}.
2706 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
2707 all positional.
2709 @see: Function L{fsum_<fsums.fsum_>} for further details.
2710 '''
2711 return _xsum(fsumf_, xs, nonfinites=True, origin=1) if xs else _0_0
2714def fsum1(xs, **nonfinites):
2715 '''Precision floating point summation, 1-primed.
2717 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2718 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2720 @see: Function L{fsum<fsums.fsum>} for further details.
2721 '''
2722 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0
2725def fsum1_(*xs, **nonfinites):
2726 '''Precision floating point summation of all positional items, 1-primed.
2728 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2729 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2731 @see: Function L{fsum_<fsums.fsum_>} for further details.
2732 '''
2733 return _xsum(fsum1_, xs, origin=1, primed=1, **nonfinites) if xs else _0_0
2736def fsum1f_(*xs):
2737 '''Precision floating point summation of all positional items, 1-primed and
2738 with I{non-finites} C{OK}.
2740 @see: Function L{fsum_<fsums.fsum_>} for further details.
2741 '''
2742 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0
2745def _xs(xs, i_x, nfOK): # in Fsum._facc_scalarf
2746 '''(INTERNAL) Yield all C{xs} as C{scalar}.
2747 '''
2748 _x = _passarg if nfOK else _2finite
2749 for i, x in enumerate(xs):
2750 i_x[:] = i, x
2751 if _isFsum_2Tuple(x):
2752 for p in map(_x, x._ps):
2753 yield p
2754 else:
2755 yield _x(x)
2758def _xsum(which, xs, nonfinites=None, origin=0, primed=0, **floats):
2759 '''(INTERNAL) Precision summation of C{xs} with conditions.
2760 '''
2761 i_x = [0, xs]
2762 try:
2763 if floats: # for backward compatibility
2764 nonfinites = _xkwds_get1(floats, floats=nonfinites)
2765 elif nonfinites is None:
2766 nonfinites = not nonfiniterrors()
2767 fs = _xs(xs, i_x, nonfinites)
2768 return _fsum(_1primed(fs) if primed else fs)
2769 except (OverflowError, TypeError, ValueError) as X:
2770 origin -= 1 if primed else 0
2771 i_x += [origin, which]
2772 raise _ixError(X, xs, *i_x)
2775# delete all decorators, etc.
2776del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \
2777 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \
2778 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _getenv, _std_
2780if __name__ == '__main__':
2782 # usage: python3 -m pygeodesy.fsums
2784 def _test(n):
2785 # copied from Hettinger, see L{Fsum} reference
2786 from pygeodesy import frandoms, printf
2788 printf(_fsum.__name__, end=_COMMASPACE_)
2789 printf(_psum.__name__, end=_COMMASPACE_)
2791 F = Fsum()
2792 if F.is_math_fsum():
2793 for t in frandoms(n, seeded=True):
2794 assert float(F.fset_(*t)) == _fsum(t)
2795 printf(_DOT_, end=NN)
2796 printf(NN)
2798 _test(128)
2800# **) MIT License
2801#
2802# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
2803#
2804# Permission is hereby granted, free of charge, to any person obtaining a
2805# copy of this software and associated documentation files (the "Software"),
2806# to deal in the Software without restriction, including without limitation
2807# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2808# and/or sell copies of the Software, and to permit persons to whom the
2809# Software is furnished to do so, subject to the following conditions:
2810#
2811# The above copyright notice and this permission notice shall be included
2812# in all copies or substantial portions of the Software.
2813#
2814# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2815# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2816# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2817# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2818# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2819# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2820# OTHER DEALINGS IN THE SOFTWARE.