Coverage for pygeodesy/fsums.py: 95%
1098 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-12 16:17 -0500
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-12 16:17 -0500
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
44from pygeodesy.constants import INF, INT0, MANT_DIG, NEG0, NINF, _0_0, \
45 _1_0, _N_1_0, _isfinite, _pos_self, \
46 Float, Int
47from pygeodesy.errors import _AssertionError, _OverflowError, _TypeError, \
48 _ValueError, _xError, _xError2, _xkwds, \
49 _xkwds_get, _xkwds_get1, _xkwds_not, \
50 _xkwds_pop, _xsError
51from pygeodesy.internals import _enquote, _getPYGEODESY, _MODS, _passarg
52from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DOT_, _from_, \
53 _not_finite_, _SPACE_, _std_, _UNDER_
54# from pygeodesy.lazily import _ALL_LAZY # from .named
55from pygeodesy.named import _name__, _name2__, _Named, _NamedTuple, \
56 _NotImplemented, _ALL_LAZY
57from pygeodesy.props import _allPropertiesOf_n, deprecated_method, \
58 deprecated_property_RO, Property, \
59 Property_RO, property_RO
60from pygeodesy.streprs import Fmt, fstr, unstr
61# from pygeodesy.units import Float, Int # from .constants
63from math import fabs, isinf, isnan, \
64 ceil as _ceil, floor as _floor # PYCHOK used! .ltp
66__all__ = _ALL_LAZY.fsums
67__version__ = '24.11.11'
69from pygeodesy.interns import (
70 _PLUS_ as _add_op_, # in .auxilats.auxAngle
71 _EQUAL_ as _fset_op_,
72 _RANGLE_ as _gt_op_,
73 _LANGLE_ as _lt_op_,
74 _PERCENT_ as _mod_op_,
75 _STAR_ as _mul_op_,
76 _NOTEQUAL_ as _ne_op_,
77 _DASH_ as _sub_op_, # in .auxilats.auxAngle
78 _SLASH_ as _truediv_op_
79)
80_floordiv_op_ = _truediv_op_ * 2 # _DSLASH_
81_divmod_op_ = _floordiv_op_ + _mod_op_
82_F2PRODUCT = _getPYGEODESY('FSUM_F2PRODUCT')
83_iadd_op_ = _add_op_ + _fset_op_ # in .auxilats.auxAngle, .fstats
84_integer_ = 'integer'
85_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle
86_NONFINITEr = _0_0 # NOT INT0!
87_NONFINITES = _getPYGEODESY('FSUM_NONFINITES')
88_non_zero_ = 'non-zero'
89_pow_op_ = _mul_op_ * 2 # _DSTAR_
90_RESIDUAL_0_0 = _getPYGEODESY('FSUM_RESIDUAL', _0_0)
91_significant_ = 'significant'
92_threshold_ = 'threshold'
95def _2finite(x, _isfine=_isfinite): # in .fstats
96 '''(INTERNAL) return C{float(x)} if finite.
97 '''
98 return (float(x) if _isfine(x) # and isscalar(x)
99 else _nfError(x))
102def _2float(index=None, _isfine=_isfinite, **name_x): # in .fmath, .fstats
103 '''(INTERNAL) Raise C{TypeError} or C{Overflow-/ValueError} if not finite.
104 '''
105 n, x = name_x.popitem() # _xkwds_item2(name_x)
106 try:
107 f = float(x)
108 return f if _isfine(f) else _nfError(x)
109 except Exception as X:
110 raise _xError(X, Fmt.INDEX(n, index), x)
113try: # MCCABE 26
114 from math import fma as _fma
116 def _2products(x, ys, *zs):
117 # yield(x * y for y in ys) + yield(z in zs)
118 # TwoProductFMA U{Algorithm 3.5
119 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
120 for y in ys:
121 f = x * y
122 yield f
123 if _isfinite(f):
124 yield _fma(x, y, -f)
125 for z in zs:
126 yield z
128# _2split3 = \
129 _2split3s = _passarg # in Fsum.is_math_fma
131except ImportError: # PYCHOK DSPACE! Python 3.12-
133 if _F2PRODUCT and _F2PRODUCT != _std_:
134 # backward to PyGeodesy 24.09.09, with _fmaX
136 def _fma(*a_b_c): # PYCHOK no cover
137 # mimick C{math.fma} from Python 3.13+,
138 # the same accuracy, but ~14x slower
139 (na, da), (nb, db), (nc, dc) = map(_2n_d, a_b_c)
140 n = na * nb * dc
141 n += da * db * nc
142 d = da * db * dc
143 try:
144 n, d = _n_d2(n, d)
145 r = float(n / d)
146 except OverflowError: # "integer division result too large ..."
147 r = NINF if (_signOf(n, 0) * _signOf(d, 0)) < 0 else INF
148 return r if _isfinite(r) else _fmaX(r, *a_b_c) # "overflow in fma"
150 def _2n_d(x): # PYCHOK no cover
151 try: # int.as_integer_ratio in 3.8+
152 return x.as_integer_ratio()
153 except (AttributeError, OverflowError, TypeError, ValueError):
154 return (x if isint(x) else float(x)), 1
155 else:
157 def _fma(a, b, c): # PYCHOK redef
158 # mimick C{math.fma} from Python 3.13+,
159 # the same accuracy, but ~13x slower
160 b3s = _2split3(b), # 1-tuple of 3-tuple
161 r = _fsum(_2products(a, b3s, c))
162 return r if _isfinite(r) else _fmaX(r, a, b, c)
164 _2n_d = None # redef
166 def _fmaX(r, *a_b_c): # PYCHOK no cover
167 # handle non-finite as Python 3.13+ C-function U{math_fma_impl<https://
168 # GitHub.com/python/cpython/blob/main/Modules/mathmodule.c#L2305>}:
169 # raise a ValueError for a NAN result from non-NAN C{a_b_c}s or an
170 # OverflowError for a non-NAN non-finite from all finite C{a_b_c}s.
171 if isnan(r):
172 def _x(x):
173 return not isnan(x)
174 else: # non-NAN non-finite
175 _x = _isfinite
176 if all(map(_x, a_b_c)):
177 raise _nfError(r, unstr(_fma, *a_b_c))
178 return r
180 def _2products(x, y3s, *zs): # PYCHOK in _fma, ...
181 # yield(x * y3 for y3 in y3s) + yield(z in zs)
182 # TwoProduct U{Algorithm 3.3
183 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
184 # also in Python 3.13+ C{Modules/mathmodule.c} under
185 # #ifndef UNRELIABLE_FMA ... #else ... #endif
186 _, a, b = _2split3(x)
187 for y, c, d in y3s:
188 y *= x
189 yield y
190 if _isfinite(y):
191 # yield b * d - (((y - a * c) - b * c) - a * d)
192 # = b * d + (a * d - ((y - a * c) - b * c))
193 # = b * d + (a * d + (b * c - (y - a * c)))
194 # = b * d + (a * d + (b * c + (a * c - y)))
195 yield a * c - y
196 yield b * c
197 if d:
198 yield a * d
199 yield b * d
200 for z in zs:
201 yield z
203 _2FACTOR = pow(2, (MANT_DIG + 1) // 2) + _1_0 # 134217729 if MANT_DIG == 53
205 def _2split3(x):
206 # Split U{Algorithm 3.2
207 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
208 a = c = x * _2FACTOR
209 a -= c - x
210 b = x - a
211 return x, a, b
213 def _2split3s(xs): # in Fsum.is_math_fma
214 return map(_2split3, xs)
217def f2product(two=None):
218 '''Turn accurate I{TwoProduct} multiplication on or off.
220 @kwarg two: If C{True}, turn I{TwoProduct} on, if C{False} off or
221 if C{None} or omitted, keep the current setting.
223 @return: The previous setting (C{bool}).
225 @see: I{TwoProduct} multiplication is based on the I{TwoProductFMA}
226 U{Algorithm 3.5 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
227 using function C{math.fma} from Python 3.13 and later or an
228 equivalent, slower implementation when not available.
229 '''
230 t = Fsum._f2product
231 if two is not None:
232 Fsum._f2product = bool(two)
233 return t
236def _Fsumf_(*xs): # in .auxLat, .ltp, ...
237 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
238 '''
239 return Fsum()._facc_scalarf(xs, up=False)
242def _Fsum1f_(*xs): # in .albers
243 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}, 1-primed.
244 '''
245 return Fsum()._facc_scalarf(_1primed(xs), origin=-1, up=False)
248def _halfeven(s, r, p):
249 '''(INTERNAL) Round half-even.
250 '''
251 if (p > 0 and r > 0) or \
252 (p < 0 and r < 0): # signs match
253 r *= 2
254 t = s + r
255 if r == (t - s):
256 s = t
257 return s
260def _isFsum(x): # in .fmath
261 '''(INTERNAL) Is C{x} an C{Fsum} instance?
262 '''
263 return isinstance(x, Fsum)
266def _isFsum_2Tuple(x): # in .basics, .constants, .fmath, .fstats
267 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance?
268 '''
269 return isinstance(x, _Fsum_2Tuple_types)
272def _isOK(unused):
273 '''(INTERNAL) Helper for C{Fsum._fsum2} and C{Fsum.nonfinites}.
274 '''
275 return True
278def _isOK_or_finite(x, _isfine=_isfinite):
279 '''(INTERNAL) Is C{x} finite or is I{non-finite} OK?
280 '''
281 # assert _isfine in (_isOK, _isfinite)
282 return _isfine(x) # C{bool}
285try:
286 from math import gcd as _gcd
288 def _n_d2(n, d):
289 '''(INTERNAL) Reduce C{n} and C{d} by C{gcd}.
290 '''
291 if n and d:
292 try:
293 c = _gcd(n, d)
294 if c > 1:
295 n, d = (n // c), (d // c)
296 except TypeError: # non-int float
297 pass
298 return n, d
300except ImportError: # 3.4-
302 def _n_d2(*n_d): # PYCHOK redef
303 return n_d
306def _nfError(x, *args):
307 '''(INTERNAL) Throw a C{not-finite} exception.
308 '''
309 E = _NonfiniteError(x)
310 t = Fmt.PARENSPACED(_not_finite_, x)
311 if args: # in _fmaX, _2sum
312 return E(txt=t, *args)
313 raise E(t, txt=None)
316def _NonfiniteError(x):
317 '''(INTERNAL) Return the Error class for C{x}, I{non-finite}.
318 '''
319 return _OverflowError if isinf(x) else (
320 _ValueError if isnan(x) else _AssertionError)
323def nonfiniterrors(raiser=None):
324 '''Throw C{OverflowError} and C{ValueError} exceptions for or
325 handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF},
326 C{nan} and C{NAN} in summations and multiplications.
328 @kwarg raiser: If C{True}, throw exceptions, if C{False} handle
329 I{non-finites} or if C{None} or omitted, leave
330 the setting unchanged.
332 @return: Previous setting (C{bool}).
334 @note: C{inf}, C{INF} and C{NINF} throw an C{OverflowError},
335 C{nan} and C{NAN} a C{ValueError}.
336 '''
337 d = Fsum._isfine
338 if raiser is not None:
339 Fsum._isfine = {} if bool(raiser) else Fsum._nonfinites_isfine_kwds[True]
340 return (False if d is Fsum._nonfinites_isfine_kwds[True] else
341 _xkwds_get1(d, _isfine=_isfinite) is _isfinite) if d else True
344def _1primed(xs): # in .fmath
345 '''(INTERNAL) 1-Primed summation of iterable C{xs}
346 items, all I{known} to be C{scalar}.
347 '''
348 yield _1_0
349 for x in xs:
350 yield x
351 yield _N_1_0
354def _psum(ps, **_isfine): # PYCHOK used!
355 '''(INTERNAL) Partials summation, updating C{ps}.
356 '''
357 # assert isinstance(ps, list)
358 i = len(ps) - 1
359 s = _0_0 if i < 0 else ps[i]
360 while i > 0:
361 i -= 1
362 s, r = _2sum(s, ps[i], **_isfine)
363 if r: # sum(ps) became inexact
364 if s:
365 ps[i:] = r, s
366 if i > 0:
367 s = _halfeven(s, r, ps[i-1])
368 break # return s
369 s = r # PYCHOK no cover
370 elif not _isfinite(s): # non-finite OK
371 i = 0 # collapse ps
372 if ps:
373 s += sum(ps)
374 ps[i:] = s,
375 return s
378def _Psum(ps, **name_f2product_nonfinites_RESIDUAL):
379 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
380 '''
381 F = Fsum(**name_f2product_nonfinites_RESIDUAL)
382 if ps:
383 F._ps[:] = ps
384 F._n = len(F._ps)
385 return F
388def _Psum_(*ps, **name_f2product_nonfinites_RESIDUAL): # in .fmath
389 '''(INTERNAL) Return an C{Fsum} from I{known scalar} C{ps}.
390 '''
391 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL)
394def _residue(other):
395 '''(INTERNAL) Return the C{residual} or C{None} for C{scalar}.
396 '''
397 try:
398 r = other.residual
399 except AttributeError:
400 r = None # float, int, other
401 return r
404def _s_r(s, r):
405 '''(INTERNAL) Return C{(s, r)}, I{ordered}.
406 '''
407 if _isfinite(s):
408 if r:
409 if fabs(s) < fabs(r):
410 s, r = r, (s or INT0)
411 else:
412 r = INT0
413 else:
414 r = _NONFINITEr
415 return s, r
418def _2s_r(other):
419 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
420 C{float} or C{as-is} and C{r} the residual of C{as-is} or 0.
421 '''
422 if _isFsum_2Tuple(other):
423 s, r = other._fint2
424 if r:
425 s, r = other._nfprs2
426 if r: # PYCHOK no cover
427 s = other # L{Fsum} as-is
428 else:
429 r = 0
430 s = other # C{type} as-is
431 if isint(s, both=True):
432 s = int(s)
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 = _MODS.sys_version_info2 > (3, 12) or bool(_F2PRODUCT)
522 _isfine = {} # == _isfinite, see nonfiniterrors()
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)
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._nfprs2
569 return bool(s or r) and s != -r # == self != 0
571 def __call__(self, other, **up): # in .fmath
572 '''Reset this C{Fsum} to C{other}, default C{B{up}=True}.
573 '''
574 self._ps[:] = 0, # clear for errors
575 self._fset(other, op=_fset_op_, **up)
576 return self
579 def __ceil__(self): # PYCHOK not special in Python 2-
580 '''Return this instance' C{math.ceil} as C{int} or C{float}.
582 @return: An C{int} in Python 3+, but C{float} in Python 2-.
584 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
585 '''
586 return self.ceil
588 def __cmp__(self, other): # PYCHOK no cover
589 '''Compare this with an other instance or C{scalar}, Python 2-.
591 @return: -1, 0 or +1 (C{int}).
593 @raise TypeError: Incompatible B{C{other}} C{type}.
594 '''
595 s = self._cmp_0(other, self.cmp.__name__)
596 return _signOf(s, 0)
598 def __divmod__(self, other, **raiser_RESIDUAL):
599 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
600 with quotient C{div} an C{int} in Python 3+ or C{float}
601 in Python 2- and remainder C{mod} an L{Fsum} instance.
603 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
604 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
605 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
606 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
608 @raise ResidualError: Non-zero, significant residual or invalid
609 B{C{RESIDUAL}}.
611 @see: Method L{Fsum.fdiv}.
612 '''
613 f = self._copy_2(self.__divmod__)
614 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
616 def __eq__(self, other):
617 '''Return C{(B{self} == B{other})} as C{bool} where B{C{other}}
618 is C{scalar}, an other L{Fsum} or L{Fsum2Tuple}.
619 '''
620 return self._cmp_0(other, _fset_op_ + _fset_op_) == 0
622 def __float__(self):
623 '''Return this instance' current, precision running sum as C{float}.
625 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
626 '''
627 return float(self._fprs)
629 def __floor__(self): # PYCHOK not special in Python 2-
630 '''Return this instance' C{math.floor} as C{int} or C{float}.
632 @return: An C{int} in Python 3+, but C{float} in Python 2-.
634 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
635 '''
636 return self.floor
638 def __floordiv__(self, other):
639 '''Return C{B{self} // B{other}} as an L{Fsum}.
641 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
643 @return: The C{floor} quotient (L{Fsum}).
645 @see: Methods L{Fsum.__ifloordiv__}.
646 '''
647 f = self._copy_2(self.__floordiv__)
648 return f._floordiv(other, _floordiv_op_)
650 def __ge__(self, other):
651 '''Return C{(B{self} >= B{other})}, see C{__eq__}.
652 '''
653 return self._cmp_0(other, _gt_op_ + _fset_op_) >= 0
655 def __gt__(self, other):
656 '''Return C{(B{self} > B{other})}, see C{__eq__}.
657 '''
658 return self._cmp_0(other, _gt_op_) > 0
660 def __hash__(self): # PYCHOK no cover
661 '''Return C{hash(B{self})} as C{float}.
662 '''
663 # @see: U{Notes for type implementors<https://docs.Python.org/
664 # 3/library/numbers.html#numbers.Rational>}
665 return hash(self.partials) # tuple.__hash__()
667 def __iadd__(self, other):
668 '''Apply C{B{self} += B{other}} to this instance.
670 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
671 an iterable of several of the former.
673 @return: This instance, updated (L{Fsum}).
675 @raise TypeError: Invalid B{C{other}}, not
676 C{scalar} nor L{Fsum}.
678 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
679 '''
680 try:
681 return self._fadd(other, op=_iadd_op_)
682 except TypeError:
683 pass
684 _xiterable(other)
685 return self._facc(other)
687 def __ifloordiv__(self, other):
688 '''Apply C{B{self} //= B{other}} to this instance.
690 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
692 @return: This instance, updated (L{Fsum}).
694 @raise ResidualError: Non-zero, significant residual
695 in B{C{other}}.
697 @raise TypeError: Invalid B{C{other}} type.
699 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
701 @raise ZeroDivisionError: Zero B{C{other}}.
703 @see: Methods L{Fsum.__itruediv__}.
704 '''
705 return self._floordiv(other, _floordiv_op_ + _fset_op_)
707 def __imatmul__(self, other): # PYCHOK no cover
708 '''Not implemented.'''
709 return _NotImplemented(self, other)
711 def __imod__(self, other):
712 '''Apply C{B{self} %= B{other}} to this instance.
714 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
716 @return: This instance, updated (L{Fsum}).
718 @see: Method L{Fsum.__divmod__}.
719 '''
720 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
722 def __imul__(self, other):
723 '''Apply C{B{self} *= B{other}} to this instance.
725 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
727 @return: This instance, updated (L{Fsum}).
729 @raise OverflowError: Partial C{2sum} overflow.
731 @raise TypeError: Invalid B{C{other}} type.
733 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
734 '''
735 return self._fmul(other, _mul_op_ + _fset_op_)
737 def __int__(self):
738 '''Return this instance as an C{int}.
740 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
741 and L{Fsum.floor}.
742 '''
743 i, _ = self._fint2
744 return i
746 def __invert__(self): # PYCHOK no cover
747 '''Not implemented.'''
748 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
749 return _NotImplemented(self)
751 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
752 '''Apply C{B{self} **= B{other}} to this instance.
754 @arg other: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
755 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
756 C{pow(B{self}, B{other}, B{mod})} version.
757 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
758 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
759 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
761 @return: This instance, updated (L{Fsum}).
763 @note: If B{C{mod}} is given, the result will be an C{integer}
764 L{Fsum} in Python 3+ if this instance C{is_integer} or
765 set to C{as_integer} and B{C{mod}} is given and C{None}.
767 @raise OverflowError: Partial C{2sum} overflow.
769 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
770 is non-zero and significant and either
771 B{C{other}} is a fractional or negative
772 C{scalar} or B{C{mod}} is given and not
773 C{None}.
775 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
776 invocation failed.
778 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
779 instance is C{0} or B{C{other}} is a fractional
780 C{scalar} and this instance is negative or has a
781 non-zero and significant residual or B{C{mod}}
782 is given as C{0}.
784 @see: CPython function U{float_pow<https://GitHub.com/
785 python/cpython/blob/main/Objects/floatobject.c>}.
786 '''
787 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
789 def __isub__(self, other):
790 '''Apply C{B{self} -= B{other}} to this instance.
792 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
793 an iterable of several of the former.
795 @return: This instance, updated (L{Fsum}).
797 @raise TypeError: Invalid B{C{other}} type.
799 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
800 '''
801 try:
802 return self._fsub(other, _isub_op_)
803 except TypeError:
804 pass
805 _xiterable(other)
806 return self._facc_neg(other)
808 def __iter__(self):
809 '''Return an C{iter}ator over a C{partials} duplicate.
810 '''
811 return iter(self.partials)
813 def __itruediv__(self, other, **raiser_RESIDUAL):
814 '''Apply C{B{self} /= B{other}} to this instance.
816 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
817 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
818 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
819 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
821 @return: This instance, updated (L{Fsum}).
823 @raise OverflowError: Partial C{2sum} overflow.
825 @raise ResidualError: Non-zero, significant residual or invalid
826 B{C{RESIDUAL}}.
828 @raise TypeError: Invalid B{C{other}} type.
830 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
832 @raise ZeroDivisionError: Zero B{C{other}}.
834 @see: Method L{Fsum.__ifloordiv__}.
835 '''
836 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
838 def __le__(self, other):
839 '''Return C{(B{self} <= B{other})}, see C{__eq__}.
840 '''
841 return self._cmp_0(other, _lt_op_ + _fset_op_) <= 0
843 def __len__(self):
844 '''Return the number of values accumulated (C{int}).
845 '''
846 return self._n
848 def __lt__(self, other):
849 '''Return C{(B{self} < B{other})}, see C{__eq__}.
850 '''
851 return self._cmp_0(other, _lt_op_) < 0
853 def __matmul__(self, other): # PYCHOK no cover
854 '''Not implemented.'''
855 return _NotImplemented(self, other)
857 def __mod__(self, other):
858 '''Return C{B{self} % B{other}} as an L{Fsum}.
860 @see: Method L{Fsum.__imod__}.
861 '''
862 f = self._copy_2(self.__mod__)
863 return f._fdivmod2(other, _mod_op_).mod
865 def __mul__(self, other):
866 '''Return C{B{self} * B{other}} as an L{Fsum}.
868 @see: Method L{Fsum.__imul__}.
869 '''
870 f = self._copy_2(self.__mul__)
871 return f._fmul(other, _mul_op_)
873 def __ne__(self, other):
874 '''Return C{(B{self} != B{other})}, see C{__eq__}.
875 '''
876 return self._cmp_0(other, _ne_op_) != 0
878 def __neg__(self):
879 '''Return C{copy(B{self})}, I{negated}.
880 '''
881 f = self._copy_2(self.__neg__)
882 return f._fset(self._neg)
884 def __pos__(self):
885 '''Return this instance I{as-is}, like C{float.__pos__()}.
886 '''
887 return self if _pos_self else self._copy_2(self.__pos__)
889 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
890 '''Return C{B{self}**B{other}} as an L{Fsum}.
892 @see: Method L{Fsum.__ipow__}.
893 '''
894 f = self._copy_2(self.__pow__)
895 return f._fpow(other, _pow_op_, *mod)
897 def __radd__(self, other):
898 '''Return C{B{other} + B{self}} as an L{Fsum}.
900 @see: Method L{Fsum.__iadd__}.
901 '''
902 f = self._copy_2r(other, self.__radd__)
903 return f._fadd(self)
905 def __rdivmod__(self, other):
906 '''Return C{divmod(B{other}, B{self})} as 2-tuple
907 C{(quotient, remainder)}.
909 @see: Method L{Fsum.__divmod__}.
910 '''
911 f = self._copy_2r(other, self.__rdivmod__)
912 return f._fdivmod2(self, _divmod_op_)
914# turned off, called by _deepcopy and _copy
915# def __reduce__(self): # Python 3.8+
916# ''' Pickle, like std C{fractions.Fraction}, see U{__reduce__
917# <https://docs.Python.org/3/library/pickle.html#object.__reduce__>}
918# '''
919# dict_ = self._Fsum_as().__dict__ # no __setstate__
920# return (self.__class__, self.partials, dict_)
922# def __repr__(self):
923# '''Return the default C{repr(this)}.
924# '''
925# return self.toRepr(lenc=True)
927 def __rfloordiv__(self, other):
928 '''Return C{B{other} // B{self}} as an L{Fsum}.
930 @see: Method L{Fsum.__ifloordiv__}.
931 '''
932 f = self._copy_2r(other, self.__rfloordiv__)
933 return f._floordiv(self, _floordiv_op_)
935 def __rmatmul__(self, other): # PYCHOK no coveS
936 '''Not implemented.'''
937 return _NotImplemented(self, other)
939 def __rmod__(self, other):
940 '''Return C{B{other} % B{self}} as an L{Fsum}.
942 @see: Method L{Fsum.__imod__}.
943 '''
944 f = self._copy_2r(other, self.__rmod__)
945 return f._fdivmod2(self, _mod_op_).mod
947 def __rmul__(self, other):
948 '''Return C{B{other} * B{self}} as an L{Fsum}.
950 @see: Method L{Fsum.__imul__}.
951 '''
952 f = self._copy_2r(other, self.__rmul__)
953 return f._fmul(self, _mul_op_)
955 def __round__(self, *ndigits): # PYCHOK Python 3+
956 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
958 @arg ndigits: Optional number of digits (C{int}).
959 '''
960 f = self._copy_2(self.__round__)
961 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
962 return f._fset(round(float(self), *ndigits)) # can be C{int}
964 def __rpow__(self, other, *mod):
965 '''Return C{B{other}**B{self}} as an L{Fsum}.
967 @see: Method L{Fsum.__ipow__}.
968 '''
969 f = self._copy_2r(other, self.__rpow__)
970 return f._fpow(self, _pow_op_, *mod)
972 def __rsub__(self, other):
973 '''Return C{B{other} - B{self}} as L{Fsum}.
975 @see: Method L{Fsum.__isub__}.
976 '''
977 f = self._copy_2r(other, self.__rsub__)
978 return f._fsub(self, _sub_op_)
980 def __rtruediv__(self, other, **raiser_RESIDUAL):
981 '''Return C{B{other} / B{self}} as an L{Fsum}.
983 @see: Method L{Fsum.__itruediv__}.
984 '''
985 f = self._copy_2r(other, self.__rtruediv__)
986 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
988 def __str__(self):
989 '''Return the default C{str(self)}.
990 '''
991 return self.toStr(lenc=True)
993 def __sub__(self, other):
994 '''Return C{B{self} - B{other}} as an L{Fsum}.
996 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
998 @return: The difference (L{Fsum}).
1000 @see: Method L{Fsum.__isub__}.
1001 '''
1002 f = self._copy_2(self.__sub__)
1003 return f._fsub(other, _sub_op_)
1005 def __truediv__(self, other, **raiser_RESIDUAL):
1006 '''Return C{B{self} / B{other}} as an L{Fsum}.
1008 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
1009 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1010 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1011 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1013 @return: The quotient (L{Fsum}).
1015 @raise ResidualError: Non-zero, significant residual or invalid
1016 B{C{RESIDUAL}}.
1018 @see: Method L{Fsum.__itruediv__}.
1019 '''
1020 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
1022 __trunc__ = __int__
1024 if _MODS.sys_version_info2 < (3, 0): # PYCHOK no cover
1025 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
1026 __div__ = __truediv__
1027 __idiv__ = __itruediv__
1028 __long__ = __int__
1029 __nonzero__ = __bool__
1030 __rdiv__ = __rtruediv__
1032 def as_integer_ratio(self):
1033 '''Return this instance as the ratio of 2 integers.
1035 @return: 2-Tuple C{(numerator, denominator)} both C{int} with
1036 C{numerator} signed and C{denominator} non-zero and
1037 positive. The C{numerator} is I{non-finite} if this
1038 instance is.
1040 @see: Method L{Fsum.fint2} and C{float.as_integer_ratio} in
1041 Python 2.7+.
1042 '''
1043 n, r = self._fint2
1044 if r:
1045 i, d = float(r).as_integer_ratio()
1046 n, d = _n_d2(n * d + i, d)
1047 else: # PYCHOK no cover
1048 d = 1
1049 return n, d
1051 @property_RO
1052 def as_iscalar(self):
1053 '''Get this instance I{as-is} (L{Fsum} with C{non-zero residual},
1054 C{scalar} or I{non-finite}).
1055 '''
1056 s, r = self._nfprs2
1057 return self if r else s
1059 @property_RO
1060 def ceil(self):
1061 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
1062 C{float} in Python 2-).
1064 @note: This C{ceil} takes the C{residual} into account.
1066 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
1067 L{Fsum.imag} and L{Fsum.real}.
1068 '''
1069 s, r = self._fprs2
1070 c = _ceil(s) + int(r) - 1
1071 while r > (c - s): # (s + r) > c
1072 c += 1
1073 return c # _ceil(self._n_d)
1075 cmp = __cmp__
1077 def _cmp_0(self, other, op):
1078 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
1079 '''
1080 if _isFsum_2Tuple(other):
1081 s = self._ps_1sum(*other._ps)
1082 elif self._scalar(other, op):
1083 s = self._ps_1sum(other)
1084 else:
1085 s = self.signOf() # res=True
1086 return s
1088 def copy(self, deep=False, **name):
1089 '''Copy this instance, C{shallow} or B{C{deep}}.
1091 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}).
1093 @return: The copy (L{Fsum}).
1094 '''
1095 n = _name__(name, name__=self.copy)
1096 f = _Named.copy(self, deep=deep, name=n)
1097 if f._ps is self._ps:
1098 f._ps = list(self._ps) # separate list
1099 if not deep:
1100 f._n = 1
1101 # assert f._f2product == self._f2product
1102 # assert f._Fsum is f
1103 # assert f._isfine is self._isfine
1104 # assert f._RESIDUAL is self._RESIDUAL
1105 return f
1107 def _copy_2(self, which, name=NN):
1108 '''(INTERNAL) Copy for I{dyadic} operators.
1109 '''
1110 n = name or which.__name__ # _DUNDER_nameof
1111 # NOT .classof due to .Fdot(a, *b) args, etc.
1112 f = _Named.copy(self, deep=False, name=n)
1113 f._ps = list(self._ps) # separate list
1114 # assert f._n == self._n
1115 # assert f._f2product == self._f2product
1116 # assert f._Fsum is f
1117 # assert f._isfine is self._isfine
1118 # assert f._RESIDUAL is self._RESIDUAL
1119 return f
1121 def _copy_2r(self, other, which):
1122 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
1123 '''
1124 return other._copy_2(which) if _isFsum(other) else \
1125 self._copy_2(which)._fset(other)
1127 divmod = __divmod__
1129 def _Error(self, op, other, Error, **txt_cause):
1130 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
1131 '''
1132 # self.as_iscalar causes RecursionError for ._fprs2 errors
1133 s = _Psum(self._ps, nonfinites=True, name=self.name)
1134 return Error(_SPACE_(s.as_iscalar, op, other), **txt_cause)
1136 def _ErrorX(self, X, op, other, *mod):
1137 '''(INTERNAL) Format the caught exception C{X}.
1138 '''
1139 E, t = _xError2(X)
1140 if mod:
1141 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
1142 return self._Error(op, other, E, txt=t, cause=X)
1144 def _ErrorXs(self, X, xs, **kwds): # in .fmath
1145 '''(INTERNAL) Format the caught exception C{X}.
1146 '''
1147 E, t = _xError2(X)
1148 u = unstr(self.named3, *xs, _ELLIPSIS=4, **kwds)
1149 return E(u, txt=t, cause=X)
1151 def _facc(self, xs, up=True, **_X_x_origin):
1152 '''(INTERNAL) Accumulate more C{scalar}s or L{Fsum}s.
1153 '''
1154 if xs:
1155 kwds = self._isfine
1156 if _X_x_origin:
1157 kwds = _xkwds(_X_x_origin, **kwds)
1158 fs = _xs(xs, **kwds) # PYCHOK yield
1159 ps = self._ps
1160 ps[:] = self._ps_acc(list(ps), fs, up=up)
1161# if len(ps) > 16:
1162# _ = _psum(ps, **self._isfine)
1163 return self
1165 def _facc_args(self, xs, **up):
1166 '''(INTERNAL) Accumulate 0, 1 or more C{xs}, all positional
1167 arguments in the caller of this method.
1168 '''
1169 return self._fadd(xs[0], **up) if len(xs) == 1 else \
1170 self._facc(xs, **up) # origin=1?
1172 def _facc_dot(self, n, xs, ys, **kwds): # in .fmath
1173 '''(INTERNAL) Accumulate C{fdot(B{xs}, *B{ys})}.
1174 '''
1175 if n > 0:
1176 _f = Fsum(**kwds)
1177 self._facc(_f(x).fmul(y) for x, y in zip(xs, ys)) # PYCHOK attr?
1178 return self
1180 def _facc_neg(self, xs, **up_origin):
1181 '''(INTERNAL) Accumulate more C{xs}, negated.
1182 '''
1183 def _N(X):
1184 return X._ps_neg
1186 def _n(x):
1187 return -float(x)
1189 return self._facc(xs, _X=_N, _x=_n, **up_origin)
1191 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
1192 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
1193 '''
1194 def _Pow4(p):
1195 r = 0
1196 if _isFsum_2Tuple(p):
1197 s, r = p._fprs2
1198 if r:
1199 m = Fsum._pow
1200 else: # scalar
1201 return _Pow4(s)
1202 elif isint(p, both=True) and int(p) >= 0:
1203 p = s = int(p)
1204 m = Fsum._pow_int
1205 else:
1206 p = s = _2float(power=p, **self._isfine)
1207 m = Fsum._pow_scalar
1208 return m, p, s, r
1210 _Pow, p, s, r = _Pow4(power)
1211 if p: # and xs:
1212 op = which.__name__
1213 _FsT = _Fsum_2Tuple_types
1214 _pow = self._pow_2_3
1216 def _P(X):
1217 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
1218 return f._ps if isinstance(f, _FsT) else (f,)
1220 def _p(x):
1221 x = float(x)
1222 f = _pow(x, s, power, op, **raiser_RESIDUAL)
1223 if f and r:
1224 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
1225 return f
1227 f = self._facc(xs, _X=_P, _x=_p) # origin=1?
1228 else:
1229 f = self._facc_scalar_(float(len(xs))) # x**0 == 1
1230 return f
1232 def _facc_scalar(self, xs, **up):
1233 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}.
1234 '''
1235 if xs:
1236 ps = self._ps
1237 ps[:] = self._ps_acc(list(ps), xs, **up)
1238 return self
1240 def _facc_scalar_(self, *xs, **up):
1241 '''(INTERNAL) Accumulate all positional C{xs}, each C{scalar}.
1242 '''
1243 return self._facc_scalar(xs, **up)
1245 def _facc_scalarf(self, xs, up=True, **origin_which):
1246 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}, an L{Fsum} or
1247 L{Fsum2Tuple}, like function C{_xsum}.
1248 '''
1249 _C = self.__class__
1250 fs = _xs(xs, **_x_isfine(self.nonfinitesOK, _Cdot=_C,
1251 **origin_which)) # PYCHOK yield
1252 return self._facc_scalar(fs, up=up)
1254# def _facc_up(self, up=True):
1255# '''(INTERNAL) Update the C{partials}, by removing
1256# and re-accumulating the final C{partial}.
1257# '''
1258# ps = self._ps
1259# while len(ps) > 1:
1260# p = ps.pop()
1261# if p:
1262# n = self._n
1263# _ = self._ps_acc(ps, (p,), up=False)
1264# self._n = n
1265# break
1266# return self._update() if up else self
1268 def fadd(self, xs=()):
1269 '''Add an iterable's items to this instance.
1271 @arg xs: Iterable of items to add (each C{scalar},
1272 an L{Fsum} or L{Fsum2Tuple}).
1274 @return: This instance (L{Fsum}).
1276 @raise OverflowError: Partial C{2sum} overflow.
1278 @raise TypeError: An invalid B{C{xs}} item.
1280 @raise ValueError: Invalid or I{non-finite} B{C{xs}} value.
1281 '''
1282 if _isFsum_2Tuple(xs):
1283 self._facc_scalar(xs._ps)
1284 elif isscalar(xs): # for backward compatibility # PYCHOK no cover
1285 x = _2float(x=xs, **self._isfine)
1286 self._facc_scalar_(x)
1287 elif xs: # _xiterable(xs)
1288 self._facc(xs)
1289 return self
1291 def fadd_(self, *xs):
1292 '''Add all positional items to this instance.
1294 @arg xs: Values to add (each C{scalar}, an L{Fsum}
1295 or L{Fsum2Tuple}), all positional.
1297 @see: Method L{Fsum.fadd} for further details.
1298 '''
1299 return self._facc_args(xs)
1301 def _fadd(self, other, op=_add_op_, **up):
1302 '''(INTERNAL) Apply C{B{self} += B{other}}.
1303 '''
1304 if _isFsum_2Tuple(other):
1305 self._facc_scalar(other._ps, **up)
1306 elif self._scalar(other, op):
1307 self._facc_scalar_(other, **up)
1308 return self
1310 fcopy = copy # for backward compatibility
1311 fdiv = __itruediv__
1312 fdivmod = __divmod__
1314 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1315 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1316 '''
1317 # result mostly follows CPython function U{float_divmod
1318 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1319 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1320 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1321 if q: # == float // other == floor(float / other)
1322 self -= self._Fsum_as(q) * other # NOT other * q!
1324 s = signOf(other) # make signOf(self) == signOf(other)
1325 if s and self.signOf() == -s: # PYCHOK no cover
1326 self += other
1327 q -= 1
1328# t = self.signOf()
1329# if t and t != s:
1330# raise self._Error(op, other, _AssertionError, txt__=signOf)
1331 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1333 def _fhorner(self, x, cs, where, incx=True): # in .fmath
1334 '''(INTERNAL) Add an L{Fhorner} evaluation of polynomial
1335 C{sum(cs[i] * B{x}**i for i=0..len(cs)-1) if B{incx}
1336 else sum(... i=len(cs)-1..0)}.
1337 '''
1338 # assert _xiterablen(cs)
1339 try:
1340 n = len(cs)
1341 H = self._Fsum_as(name__=self._fhorner)
1342 _m = H._mul_Fsum if _isFsum_2Tuple(x) else \
1343 H._mul_scalar
1344 if _2finite(x, **self._isfine) and n > 1:
1345 for c in (reversed(cs) if incx else cs):
1346 H._fset(_m(x, _mul_op_), up=False)
1347 H._fadd(c, up=False)
1348 else: # x == 0
1349 H = cs[0] if n else 0
1350 self._fadd(H)
1351 except Exception as X:
1352 t = unstr(where, x, *cs, _ELLIPSIS=4, incx=incx)
1353 raise self._ErrorX(X, _add_op_, t)
1354 return self
1356 def _finite(self, other, op=None):
1357 '''(INTERNAL) Return B{C{other}} if C{finite}.
1358 '''
1359 if _isOK_or_finite(other, **self._isfine):
1360 return other
1361 E = _NonfiniteError(other)
1362 raise self._Error(op, other, E, txt=_not_finite_)
1364 def fint(self, name=NN, **raiser_RESIDUAL):
1365 '''Return this instance' current running sum as C{integer}.
1367 @kwarg name: Optional, overriding C{B{name}="fint"} (C{str}).
1368 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1369 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1370 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1372 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1373 with a zero or insignificant I{integer} residual.
1375 @raise ResidualError: Non-zero, significant residual or invalid
1376 B{C{RESIDUAL}}.
1378 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1379 '''
1380 i, r = self._fint2
1381 if r:
1382 R = self._raiser(r, i, **raiser_RESIDUAL)
1383 if R:
1384 t = _stresidual(_integer_, r, **R)
1385 raise ResidualError(_integer_, i, txt=t)
1386 return self._Fsum_as(i, name=_name__(name, name__=self.fint))
1388 def fint2(self, **name):
1389 '''Return this instance' current running sum as C{int} and the
1390 I{integer} residual.
1392 @kwarg name: Optional name (C{str}).
1394 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1395 an C{int} and I{integer} C{residual} a C{float} or
1396 C{INT0} if the C{fsum} is considered to be I{exact}.
1397 The C{fsum} is I{non-finite} if this instance is.
1398 '''
1399 return Fsum2Tuple(*self._fint2, **name)
1401 @Property
1402 def _fint2(self): # see ._fset
1403 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1404 '''
1405 s, r = self._nfprs2
1406 if _isfinite(s):
1407 i = int(s)
1408 r = (self._ps_1sum(i) if len(self._ps) > 1 else
1409 float(s - i)) or INT0
1410 else: # INF, NAN, NINF
1411 i = float(s)
1412# r = _NONFINITEr
1413 return i, r # Fsum2Tuple?
1415 @_fint2.setter_ # PYCHOK setter_UNDERscore!
1416 def _fint2(self, s): # in _fset
1417 '''(INTERNAL) Replace the C{_fint2} value.
1418 '''
1419 if _isfinite(s):
1420 i = int(s)
1421 r = (s - i) or INT0
1422 else: # INF, NAN, NINF
1423 i = float(s)
1424 r = _NONFINITEr
1425 return i, r # like _fint2.getter
1427 @deprecated_property_RO
1428 def float_int(self): # PYCHOK no cover
1429 '''DEPRECATED, use method C{Fsum.int_float}.'''
1430 return self.int_float() # raiser=False
1432 @property_RO
1433 def floor(self):
1434 '''Get this instance' C{floor} (C{int} in Python 3+, but
1435 C{float} in Python 2-).
1437 @note: This C{floor} takes the C{residual} into account.
1439 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1440 L{Fsum.imag} and L{Fsum.real}.
1441 '''
1442 s, r = self._fprs2
1443 f = _floor(s) + _floor(r) + 1
1444 while (f - s) > r: # f > (s + r)
1445 f -= 1
1446 return f # _floor(self._n_d)
1448# ffloordiv = __ifloordiv__ # for naming consistency?
1449# floordiv = __floordiv__ # for naming consistency?
1451 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1452 '''Apply C{B{self} //= B{other}}.
1453 '''
1454 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1455 return self._fset(q.floor) # floor(q)
1457 def fma(self, other1, other2, **nonfinites): # in .fmath.fma
1458 '''Fused-multiply-add C{self *= B{other1}; self += B{other2}}.
1460 @arg other1: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1461 @arg other2: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1462 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{False}, to
1463 override L{nonfinites<Fsum.nonfinites>} and
1464 L{nonfiniterrors} default (C{bool}).
1465 '''
1466 op = self.fma.__name__
1467 _fs = self._ps_other
1468 try:
1469 s, r = self._fprs2
1470 if r:
1471 f = self._f2mul(self.fma, (other1,), **nonfinites)
1472 f += other2
1473 elif _residue(other1) or _residue(other2):
1474 fs = _2split3s(_fs(op, other1))
1475 fs = _2products(s, fs, *_fs(op, other2))
1476 f = _Psum(self._ps_acc([], fs, up=False), name=op)
1477 else:
1478 f = _fma(s, other1, other2)
1479 f = _2finite(f, **self._isfine)
1480 except TypeError as X:
1481 raise self._ErrorX(X, op, (other1, other2))
1482 except (OverflowError, ValueError) as X: # from math.fma
1483 f = self._mul_reduce(s, other1) # INF, NAN, NINF
1484 f += sum(_fs(op, other2))
1485 f = self._nonfiniteX(X, op, f, **nonfinites)
1486 return self._fset(f)
1488 fmul = __imul__
1490 def _fmul(self, other, op):
1491 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1492 '''
1493 if _isFsum_2Tuple(other):
1494 if len(self._ps) != 1:
1495 f = self._mul_Fsum(other, op)
1496 elif len(other._ps) != 1: # and len(self._ps) == 1
1497 f = self._ps_mul(op, *other._ps) if other._ps else _0_0
1498 elif self._f2product: # len(other._ps) == 1
1499 f = self._mul_scalar(other._ps[0], op)
1500 else: # len(other._ps) == len(self._ps) == 1
1501 f = self._finite(self._ps[0] * other._ps[0], op=op)
1502 else:
1503 s = self._scalar(other, op)
1504 f = self._mul_scalar(s, op)
1505 return self._fset(f) # n=len(self) + 1
1507 @deprecated_method
1508 def f2mul(self, *others, **raiser):
1509 '''DEPRECATED on 2024.09.13, use method L{f2mul_<Fsum.f2mul_>}.'''
1510 return self._fset(self.f2mul_(others, **raiser))
1512 def f2mul_(self, *others, **f2product_nonfinites): # in .fmath.f2mul
1513 '''Return C{B{self} * B{other} * B{other} ...} for all B{C{others}} using cascaded,
1514 accurate multiplication like with L{f2product<Fsum.f2product>}C{(B{True})}.
1516 @arg others: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
1517 positional.
1518 @kwarg f2product_nonfinites: Use C{B{f2product=False}} to override the default
1519 C{True} and C{B{nonfinites}=True} or C{False}, to override
1520 settings L{nonfinites<Fsum.nonfinites>} and L{nonfiniterrors}.
1522 @return: The cascaded I{TwoProduct} (L{Fsum} or C{float}).
1524 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
1525 '''
1526 return self._f2mul(self.f2mul_, others, **f2product_nonfinites)
1528 def _f2mul(self, where, others, f2product=True, **nonfinites_raiser):
1529 '''(INTERNAL) See methods C{fma} and C{f2mul_}.
1530 '''
1531 f = _Psum(self._ps, f2product=f2product, name=where.__name__)
1532 if others and f:
1533 if f.f2product():
1534 def _pfs(f, ps):
1535 return _2products(f, _2split3s(ps))
1536 else:
1537 def _pfs(f, ps): # PYCHOK redef
1538 return (f * p for p in ps)
1540 op, ps = where.__name__, f._ps
1541 try: # as if self.f2product(True)
1542 for other in others: # to pinpoint errors
1543 for p in self._ps_other(op, other):
1544 ps[:] = f._ps_acc([], _pfs(p, ps), update=False)
1545 f._update()
1546 except TypeError as X:
1547 raise self._ErrorX(X, op, other)
1548 except (OverflowError, ValueError) as X:
1549 r = self._mul_reduce(sum(ps), other) # INF, NAN, NINF
1550 r = self._nonfiniteX(X, op, r, **nonfinites_raiser)
1551 f._fset(r)
1552 return f
1554 def fover(self, over, **raiser_RESIDUAL):
1555 '''Apply C{B{self} /= B{over}} and summate.
1557 @arg over: An L{Fsum} or C{scalar} denominator.
1558 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1559 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1560 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1562 @return: Precision running sum (C{float}).
1564 @raise ResidualError: Non-zero, significant residual or invalid
1565 B{C{RESIDUAL}}.
1567 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1568 '''
1569 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1571 fpow = __ipow__
1573 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1574 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1575 '''
1576 if mod:
1577 if mod[0] is not None: # == 3-arg C{pow}
1578 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1579 elif self.is_integer():
1580 # return an exact C{int} for C{int}**C{int}
1581 i, _ = self._fint2 # assert _ == 0
1582 x, r = _2s_r(other) # C{int}, C{float} or other
1583 f = self._Fsum_as(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1584 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1585 else: # mod[0] is None, power(self, other)
1586 f = self._pow(other, other, op, **raiser_RESIDUAL)
1587 else: # pow(self, other)
1588 f = self._pow(other, other, op, **raiser_RESIDUAL)
1589 return self._fset(f) # n=max(len(self), 1)
1591 def f2product(self, *two):
1592 '''Get and set accurate I{TwoProduct} multiplication for this
1593 L{Fsum}, overriding the L{f2product} default.
1595 @arg two: If omitted, leave the override unchanged, if C{True},
1596 turn I{TwoProduct} on, if C{False} off, if C{None}e
1597 remove th override (C{bool} or C{None}).
1599 @return: The previous setting (C{bool} or C{None} if not set).
1601 @see: Function L{f2product<fsums.f2product>}.
1603 @note: Use C{f.f2product() or f2product()} to determine whether
1604 multiplication is accurate for L{Fsum} C{f}.
1605 '''
1606 if two: # delattrof(self, _f2product=None)
1607 t = _xkwds_pop(self.__dict__, _f2product=None)
1608 if two[0] is not None:
1609 self._f2product = bool(two[0])
1610 else: # getattrof(self, _f2product=None)
1611 t = _xkwds_get(self.__dict__, _f2product=None)
1612 return t
1614 @Property
1615 def _fprs(self):
1616 '''(INTERNAL) Get and cache this instance' precision
1617 running sum (C{float} or C{int}), ignoring C{residual}.
1619 @note: The precision running C{fsum} after a C{//=} or
1620 C{//} C{floor} division is C{int} in Python 3+.
1621 '''
1622 s, _ = self._fprs2
1623 return s # ._fprs2.fsum
1625 @_fprs.setter_ # PYCHOK setter_UNDERscore!
1626 def _fprs(self, s):
1627 '''(INTERNAL) Replace the C{_fprs} value.
1628 '''
1629 return s
1631 @Property
1632 def _fprs2(self):
1633 '''(INTERNAL) Get and cache this instance' precision
1634 running sum and residual (L{Fsum2Tuple}).
1635 '''
1636 ps = self._ps
1637 n = len(ps)
1638 try:
1639 if n > 2:
1640 s = _psum(ps, **self._isfine)
1641 if not _isfinite(s):
1642 ps[:] = s, # collapse ps
1643 return Fsum2Tuple(s, _NONFINITEr)
1644 n = len(ps)
1645# Fsum._ps_max = max(Fsum._ps_max, n)
1646 if n > 2:
1647 r = self._ps_1sum(s)
1648 return Fsum2Tuple(*_s_r(s, r))
1649 if n > 1: # len(ps) == 2
1650 s, r = _s_r(*_2sum(*ps, **self._isfine))
1651 ps[:] = (r, s) if r else (s,)
1652 elif ps: # len(ps) == 1
1653 s = ps[0]
1654 r = INT0 if _isfinite(s) else _NONFINITEr
1655 else: # len(ps) == 0
1656 s = _0_0
1657 r = INT0 if _isfinite(s) else _NONFINITEr
1658 ps[:] = s,
1659 except (OverflowError, ValueError) as X:
1660 op = _fset_op_ # INF, NAN, NINF
1661 ps[:] = sum(ps), # collapse ps
1662 s = self._nonfiniteX(X, op, ps[0])
1663 r = _NONFINITEr
1664 # assert self._ps is ps
1665 return Fsum2Tuple(s, r)
1667 @_fprs2.setter_ # PYCHOK setter_UNDERscore!
1668 def _fprs2(self, s_r):
1669 '''(INTERNAL) Replace the C{_fprs2} value.
1670 '''
1671 return Fsum2Tuple(s_r)
1673 def fset_(self, *xs):
1674 '''Apply C{B{self}.partials = Fsum(*B{xs}).partials}.
1676 @arg xs: Optional, new values (each C{scalar} or
1677 an L{Fsum} or L{Fsum2Tuple} instance), all
1678 positional.
1680 @return: This instance, replaced (C{Fsum}).
1682 @see: Method L{Fsum.fadd} for further details.
1683 '''
1684 f = (xs[0] if xs else _0_0) if len(xs) < 2 else \
1685 Fsum(*xs, nonfinites=self.nonfinites()) # self._Fsum_as(*xs)
1686 return self._fset(f, op=_fset_op_)
1688 def _fset(self, other, n=0, up=True, **op):
1689 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1690 '''
1691 if other is self:
1692 pass # from ._fmul, ._ftruediv and ._pow_0_1
1693 elif _isFsum_2Tuple(other):
1694 if op: # and not self.nonfinitesOK:
1695 self._finite(other._fprs, **op)
1696 self._ps[:] = other._ps
1697 self._n = n or other._n
1698 if up: # use or zap the C{Property_RO} values
1699 Fsum._fint2._update_from(self, other)
1700 Fsum._fprs ._update_from(self, other)
1701 Fsum._fprs2._update_from(self, other)
1702 elif isscalar(other):
1703 s = float(self._finite(other, **op)) if op else other
1704 self._ps[:] = s,
1705 self._n = n or 1
1706 if up: # Property _fint2, _fprs and _fprs2 all have
1707 # @.setter_underscore and NOT @.setter because the
1708 # latter's _fset zaps the value set by @.setter
1709 self._fint2 = s
1710 self._fprs = s
1711 self._fprs2 = s, INT0
1712 # assert self._fprs is s
1713 else:
1714 op = _xkwds_get1(op, op=_fset_op_)
1715 raise self._Error(op, other, _TypeError)
1716 return self
1718 def fsub(self, xs=()):
1719 '''Subtract an iterable's items from this instance.
1721 @see: Method L{Fsum.fadd} for further details.
1722 '''
1723 return self._facc_neg(xs)
1725 def fsub_(self, *xs):
1726 '''Subtract all positional items from this instance.
1728 @see: Method L{Fsum.fadd_} for further details.
1729 '''
1730 return self._fsub(xs[0], _sub_op_) if len(xs) == 1 else \
1731 self._facc_neg(xs) # origin=1?
1733 def _fsub(self, other, op):
1734 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1735 '''
1736 if _isFsum_2Tuple(other):
1737 if other is self: # or other._fprs2 == self._fprs2:
1738 self._fset(_0_0, n=len(self) * 2)
1739 elif other._ps:
1740 self._facc_scalar(other._ps_neg)
1741 elif self._scalar(other, op):
1742 self._facc_scalar_(-other)
1743 return self
1745 def fsum(self, xs=()):
1746 '''Add an iterable's items, summate and return the current
1747 precision running sum.
1749 @arg xs: Iterable of items to add (each item C{scalar},
1750 an L{Fsum} or L{Fsum2Tuple}).
1752 @return: Precision running sum (C{float} or C{int}).
1754 @see: Method L{Fsum.fadd}.
1756 @note: Accumulation can continue after summation.
1757 '''
1758 return self._facc(xs)._fprs
1760 def fsum_(self, *xs):
1761 '''Add any positional items, summate and return the current
1762 precision running sum.
1764 @arg xs: Items to add (each C{scalar}, an L{Fsum} or
1765 L{Fsum2Tuple}), all positional.
1767 @return: Precision running sum (C{float} or C{int}).
1769 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1770 '''
1771 return self._facc_args(xs)._fprs
1773 def Fsum_(self, *xs, **name):
1774 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1776 @kwarg name: Optional name (C{str}).
1778 @return: Copy of this updated instance (L{Fsum}).
1779 '''
1780 return self._facc_args(xs)._copy_2(self.Fsum_, **name)
1782 def Fsum2Tuple_(self, *xs, **name):
1783 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1785 @kwarg name: Optional name (C{str}).
1787 @return: Precision running sum (L{Fsum2Tuple}).
1788 '''
1789 return Fsum2Tuple(self._facc_args(xs)._nfprs2, **name)
1791 @property_RO
1792 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, in .fstats
1793 return self # NOT @Property_RO, see .copy and ._copy_2
1795 def _Fsum_as(self, *xs, **name_f2product_nonfinites_RESIDUAL):
1796 '''(INTERNAL) Return an C{Fsum} with this C{Fsum}'s C{.f2product},
1797 C{.nonfinites} and C{.RESIDUAL} setting, optionally
1798 overridden with C{name_f2product_nonfinites_RESIDUAL} and
1799 with any C{xs} accumulated.
1800 '''
1801 kwds = _xkwds_not(None, Fsum._RESIDUAL, f2product =self.f2product(),
1802 nonfinites=self.nonfinites(),
1803 RESIDUAL =self.RESIDUAL())
1804 if name_f2product_nonfinites_RESIDUAL: # overwrites
1805 kwds.update(name_f2product_nonfinites_RESIDUAL)
1806 f = Fsum(**kwds)
1807 # assert all(v == self.__dict__[n] for n, v in f.__dict__.items())
1808 return f._fset(xs[0], op=_fset_op_) if len(xs) == 1 else (
1809 f._facc(xs, up=False) if xs else f)
1811 def fsum2(self, xs=(), **name):
1812 '''Add an iterable's items, summate and return the
1813 current precision running sum I{and} the C{residual}.
1815 @arg xs: Iterable of items to add (each item C{scalar},
1816 an L{Fsum} or L{Fsum2Tuple}).
1817 @kwarg name: Optional C{B{name}=NN} (C{str}).
1819 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1820 current precision running sum and C{residual}, the
1821 (precision) sum of the remaining C{partials}. The
1822 C{residual is INT0} if the C{fsum} is considered
1823 to be I{exact}.
1825 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1826 '''
1827 t = self._facc(xs)._fprs2
1828 return t.dup(name=name) if name else t
1830 def fsum2_(self, *xs):
1831 '''Add any positional items, summate and return the current
1832 precision running sum and the I{differential}.
1834 @arg xs: Values to add (each C{scalar}, an L{Fsum} or
1835 L{Fsum2Tuple}), all positional.
1837 @return: 2Tuple C{(fsum, delta)} with the current, precision
1838 running C{fsum} like method L{Fsum.fsum} and C{delta},
1839 the difference with previous running C{fsum}, C{float}.
1841 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1842 '''
1843 return self._fsum2(xs, self._facc_args)
1845 def _fsum2(self, xs, _facc, **facc_kwds):
1846 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1847 '''
1848 p, q = self._fprs2
1849 if xs:
1850 s, r = _facc(xs, **facc_kwds)._fprs2
1851 if _isfinite(s): # _fsum(_1primed((s, -p, r, -q))
1852 d, r = _2sum(s - p, r - q, _isfine=_isOK)
1853 r, _ = _s_r(d, r)
1854 return s, (r if _isfinite(r) else _NONFINITEr)
1855 else:
1856 return p, _0_0
1858 def fsumf_(self, *xs):
1859 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}}, each I{known to be}
1860 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1861 '''
1862 return self._facc_scalarf(xs, which=self.fsumf_)._fprs # origin=1?
1864 def Fsumf_(self, *xs):
1865 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}}, each I{known to be}
1866 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1867 '''
1868 return self._facc_scalarf(xs, which=self.Fsumf_)._copy_2(self.Fsumf_) # origin=1?
1870 def fsum2f_(self, *xs):
1871 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}}, each I{known to be}
1872 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1873 '''
1874 return self._fsum2(xs, self._facc_scalarf, which=self.fsum2f_) # origin=1?
1876# ftruediv = __itruediv__ # for naming consistency?
1878 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1879 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1880 '''
1881 n = _1_0
1882 if _isFsum_2Tuple(other):
1883 if other is self or self == other:
1884 return self._fset(n, n=len(self))
1885 d, r = other._fprs2
1886 if r:
1887 R = self._raiser(r, d, **raiser_RESIDUAL)
1888 if R:
1889 raise self._ResidualError(op, other, r, **R)
1890 d, n = other.as_integer_ratio()
1891 else:
1892 d = self._scalar(other, op)
1893 try:
1894 s = n / d
1895 except Exception as X:
1896 raise self._ErrorX(X, op, other)
1897 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1898 return self._fset(f)
1900 @property_RO
1901 def imag(self):
1902 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1904 @see: Property L{Fsum.real}.
1905 '''
1906 return _0_0
1908 def int_float(self, **raiser_RESIDUAL):
1909 '''Return this instance' current running sum as C{int} or C{float}.
1911 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1912 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1913 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1915 @return: This C{int} sum if this instance C{is_integer} and
1916 I{finite}, otherwise the C{float} sum if the residual
1917 is zero or not significant.
1919 @raise ResidualError: Non-zero, significant residual or invalid
1920 B{C{RESIDUAL}}.
1922 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.is_integer},
1923 L{Fsum.RESIDUAL} and property L{Fsum.as_iscalar}.
1924 '''
1925 s, r = self._fint2
1926 if r:
1927 s, r = self._fprs2
1928 if r: # PYCHOK no cover
1929 R = self._raiser(r, s, **raiser_RESIDUAL)
1930 if R:
1931 t = _stresidual(_non_zero_, r, **R)
1932 raise ResidualError(int_float=s, txt=t)
1933 s = float(s)
1934 return s
1936 def is_exact(self):
1937 '''Is this instance' running C{fsum} considered to be exact?
1938 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1939 '''
1940 return self.residual is INT0
1942 def is_finite(self): # in .constants
1943 '''Is this instance C{finite}? (C{bool}).
1945 @see: Function L{isfinite<pygeodesy.isfinite>}.
1946 '''
1947 return _isfinite(sum(self._ps)) # == sum(self)
1949 def is_integer(self):
1950 '''Is this instance' running sum C{integer}? (C{bool}).
1952 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1953 '''
1954 s, r = self._fint2
1955 return False if r else (_isfinite(s) and isint(s))
1957 def is_math_fma(self):
1958 '''Is accurate L{f2product} multiplication based on Python's C{math.fma}?
1960 @return: C{True} if accurate multiplication uses C{math.fma}, C{False}
1961 an C{fma} implementation as C{math.fma} or C{None}, a previous
1962 C{PyGeodesy} implementation.
1963 '''
1964 return (_2split3s is _passarg) or (False if _2n_d is None else None)
1966 def is_math_fsum(self):
1967 '''Are the summation functions L{fsum}, L{fsum_}, L{fsumf_}, L{fsum1},
1968 L{fsum1_} and L{fsum1f_} based on Python's C{math.fsum}?
1970 @return: C{True} if summation functions use C{math.fsum}, C{False}
1971 otherwise.
1972 '''
1973 return _sum is _fsum # _fsum.__module__ is fabs.__module__
1975 def is_scalar(self, **raiser_RESIDUAL):
1976 '''Is this instance' running sum C{scalar} with C{0} residual or with
1977 a residual I{ratio} not exceeding the RESIDUAL threshold?
1979 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1980 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1981 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1983 @return: C{True} if this instance' residual is C{0} or C{insignificant},
1984 i.e. its residual C{ratio} doesn't exceed the L{RESIDUAL
1985 <Fsum.RESIDUAL>} threshold (C{bool}).
1987 @raise ResidualError: Non-zero, significant residual or invalid
1988 B{C{RESIDUAL}}.
1990 @see: Methods L{Fsum.RESIDUAL} and L{Fsum.is_integer} and property
1991 L{Fsum.as_iscalar}.
1992 '''
1993 s, r = self._fprs2
1994 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1996 def _mul_Fsum(self, other, op):
1997 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1998 '''
1999 # assert _isFsum_2Tuple(other)
2000 if self._ps and other._ps:
2001 try:
2002 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
2003 except Exception as X:
2004 raise self._ErrorX(X, op, other)
2005 else:
2006 f = _0_0
2007 return f
2009 def _mul_reduce(self, *others):
2010 '''(INTERNAL) Like fmath.fprod for I{non-finite} C{other}s.
2011 '''
2012 r = _1_0
2013 for f in others:
2014 r *= sum(f._ps) if _isFsum_2Tuple(f) else float(f)
2015 return r
2017 def _mul_scalar(self, factor, op):
2018 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
2019 '''
2020 # assert isscalar(factor)
2021 if self._ps and self._finite(factor, op=op):
2022 f = self if factor == _1_0 else (
2023 self._neg if factor == _N_1_0 else
2024 self._ps_mul(op, factor).as_iscalar)
2025 else:
2026 f = _0_0
2027 return f
2029# @property_RO
2030# def _n_d(self):
2031# n, d = self.as_integer_ratio()
2032# return n / d
2034 @property_RO
2035 def _neg(self):
2036 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
2037 '''
2038 return _Psum(self._ps_neg) if self._ps else NEG0
2040 @property_RO
2041 def _nfprs2(self):
2042 '''(INTERNAL) Handle I{non-finite} C{_fprs2}.
2043 '''
2044 try: # to handle nonfiniterrors, etc.
2045 t = self._fprs2
2046 except (OverflowError, ValueError):
2047 t = Fsum2Tuple(sum(self._ps), _NONFINITEr)
2048 return t
2050 def nonfinites(self, *OK):
2051 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan}
2052 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively
2053 C{ValueError} exceptions, overriding the L{nonfiniterrors} default.
2055 @arg OK: If omitted, leave the override unchanged, if C{True},
2056 I{non-finites} are C{OK}, if C{False} throw exceptions
2057 or if C{None} remove the override (C{bool} or C{None}).
2059 @return: The previous setting (C{bool} or C{None} if not set).
2061 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}.
2063 @note: Use property L{nonfinitesOK<Fsum.nonfinitesOK>} to determine
2064 whether I{non-finites} are C{OK} for this L{Fsum} and by the
2065 L{nonfiniterrors} default.
2066 '''
2067 _ks = Fsum._nonfinites_isfine_kwds
2068 if OK: # delattrof(self, _isfine=None)
2069 k = _xkwds_pop(self.__dict__, _isfine=None)
2070 if OK[0] is not None:
2071 self._isfine = _ks[bool(OK[0])]
2072 self._update()
2073 else: # getattrof(self, _isfine=None)
2074 k = _xkwds_get(self.__dict__, _isfine=None)
2075 # dict(map(reversed, _ks.items())).get(k, None)
2076 # raises a TypeError: unhashable type: 'dict'
2077 return True if k is _ks[True] else (
2078 False if k is _ks[False] else None)
2080 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK),
2081 False: dict(_isfine=_isfinite)}
2083 @property_RO
2084 def nonfinitesOK(self):
2085 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}).
2086 '''
2087# nf = self.nonfinites()
2088# if nf is None:
2089# nf = not nonfiniterrors()
2090 return _isOK_or_finite(INF, **self._isfine)
2092 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None):
2093 '''(INTERNAL) Handle a I{non-finite} exception.
2094 '''
2095 if nonfinites is None:
2096 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser)
2097 if not nonfinites:
2098 raise self._ErrorX(X, op, f)
2099 return f
2101 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL):
2102 '''(INTERNAL) Re/set options from keyword arguments.
2103 '''
2104 if f2product is not None:
2105 self.f2product(f2product)
2106 if nonfinites is not None:
2107 self.nonfinites(nonfinites)
2108 if name_RESIDUAL: # MUST be last
2109 n, kwds = _name2__(**name_RESIDUAL)
2110 if kwds:
2111 R = Fsum._RESIDUAL
2112 t = _threshold(R, **kwds)
2113 if t != R:
2114 self._RESIDUAL = t
2115 if n:
2116 self.name = n # self.rename(n)
2118 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over
2119 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
2120 '''
2121 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
2123 @property_RO
2124 def partials(self):
2125 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
2126 '''
2127 return tuple(self._ps)
2129 def pow(self, x, *mod, **raiser_RESIDUAL):
2130 '''Return C{B{self}**B{x}} as L{Fsum}.
2132 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2133 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
2134 C{pow(B{self}, B{other}, B{mod})} version.
2135 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
2136 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
2137 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2139 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
2140 result (L{Fsum}).
2142 @raise ResidualError: Non-zero, significant residual or invalid
2143 B{C{RESIDUAL}}.
2145 @note: If B{C{mod}} is given and C{None}, the result will be an
2146 C{integer} L{Fsum} provided this instance C{is_integer}
2147 or set to C{integer} by an L{Fsum.fint} call.
2149 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
2150 and L{Fsum.root}.
2151 '''
2152 f = self._copy_2(self.pow)
2153 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
2155 def _pow(self, other, unused, op, **raiser_RESIDUAL):
2156 '''Return C{B{self} ** B{other}}.
2157 '''
2158 if _isFsum_2Tuple(other):
2159 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
2160 elif self._scalar(other, op):
2161 x = self._finite(other, op=op)
2162 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2163 else:
2164 f = self._pow_0_1(0, other)
2165 return f
2167 def _pow_0_1(self, x, other):
2168 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
2169 '''
2170 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
2172 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
2173 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
2174 B{x}, int B{mod} or C{None})}, embellishing errors.
2175 '''
2177 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
2178 m = mod[0]
2179 # assert _isFsum_2Tuple(b)
2181 def _s(s, r):
2182 R = self._raiser(r, s, **raiser_RESIDUAL)
2183 if R:
2184 raise self._ResidualError(op, other, r, mod=m, **R)
2185 return s
2187 b = _s(*(b._fprs2 if m is None else b._fint2))
2188 x = _s(*_2s_r(x))
2190 try:
2191 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
2192 s = pow(b, x, *mod)
2193 if iscomplex(s):
2194 # neg**frac == complex in Python 3+, but ValueError in 2-
2195 raise ValueError(_strcomplex(s, b, x, *mod))
2196 _ = _2finite(s, **self._isfine) # ignore float
2197 return s
2198 except Exception as X:
2199 raise self._ErrorX(X, op, other, *mod)
2201 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
2202 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}.
2203 '''
2204 # assert _isFsum_2Tuple(other)
2205 x, r = other._fprs2
2206 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2207 if f and r:
2208 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
2209 return f
2211 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
2212 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
2213 '''
2214 # assert isint(x) and x >= 0
2215 ps = self._ps
2216 if len(ps) > 1:
2217 _mul_Fsum = Fsum._mul_Fsum
2218 if x > 4:
2219 p = self
2220 f = self if (x & 1) else self._Fsum_as(_1_0)
2221 m = x >> 1 # // 2
2222 while m:
2223 p = _mul_Fsum(p, p, op) # p **= 2
2224 if (m & 1):
2225 f = _mul_Fsum(f, p, op) # f *= p
2226 m >>= 1 # //= 2
2227 elif x > 1: # self**2, 3, or 4
2228 f = _mul_Fsum(self, self, op)
2229 if x > 2: # self**3 or 4
2230 p = self if x < 4 else f
2231 f = _mul_Fsum(f, p, op)
2232 else: # self**1 or self**0 == 1 or _1_0
2233 f = self._pow_0_1(x, other)
2234 elif ps: # self._ps[0]**x
2235 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
2236 else: # PYCHOK no cover
2237 # 0**pos_int == 0, but 0**0 == 1
2238 f = 0 if x else 1
2239 return f
2241 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
2242 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
2243 '''
2244 s, r = self._fprs2
2245 if r:
2246 # assert s != 0
2247 if isint(x, both=True): # self**int
2248 x = int(x)
2249 y = abs(x)
2250 if y > 1:
2251 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
2252 if x > 0: # i.e. > 1
2253 return f # Fsum or scalar
2254 # assert x < 0 # i.e. < -1
2255 if _isFsum(f):
2256 s, r = f._fprs2
2257 if r:
2258 return self._1_Over(f, op, **raiser_RESIDUAL)
2259 else: # scalar
2260 s = f
2261 # use s**(-1) to get the CPython
2262 # float_pow error iff s is zero
2263 x = -1
2264 elif x < 0: # self**(-1)
2265 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self
2266 else: # self**1 or self**0
2267 return self._pow_0_1(x, other) # self, 1 or 1.0
2268 else: # self**fractional
2269 R = self._raiser(r, s, **raiser_RESIDUAL)
2270 if R:
2271 raise self._ResidualError(op, other, r, **R)
2272 n, d = self.as_integer_ratio()
2273 if abs(n) > abs(d):
2274 n, d, x = d, n, (-x)
2275 s = n / d
2276 # assert isscalar(s) and isscalar(x)
2277 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
2279 def _ps_acc(self, ps, xs, up=True, **unused):
2280 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.
2281 '''
2282 n = 0
2283 _2s = _2sum
2284 _fi = self._isfine
2285 for x in (tuple(xs) if xs is ps else xs):
2286 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine)
2287 if x:
2288 i = 0
2289 for p in ps:
2290 x, p = _2s(x, p, **_fi)
2291 if p:
2292 ps[i] = p
2293 i += 1
2294 ps[i:] = (x,) if x else ()
2295 n += 1
2296 if n:
2297 self._n += n
2298 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
2299 if up:
2300 self._update()
2301# x = sum(ps)
2302# if not _isOK_or_finite(x, **fi):
2303# ps[:] = x, # collapse ps
2304 return ps
2306 def _ps_mul(self, op, *factors):
2307 '''(INTERNAL) Multiply this instance' C{partials} with
2308 each scalar C{factor} and accumulate into an C{Fsum}.
2309 '''
2310 def _psfs(ps, fs, _isfine=_isfinite):
2311 if len(ps) < len(fs):
2312 ps, fs = fs, ps
2313 if self._f2product:
2314 fs, p = _2split3s(fs), fs
2315 if len(ps) > 1 and fs is not p:
2316 fs = tuple(fs) # several ps
2317 _pfs = _2products
2318 else:
2319 def _pfs(p, fs):
2320 return (p * f for f in fs)
2322 for p in ps:
2323 for x in _pfs(p, fs):
2324 yield x if _isfine(x) else _nfError(x)
2326 xs = _psfs(self._ps, factors, **self._isfine)
2327 f = _Psum(self._ps_acc([], xs, up=False), name=op)
2328 return f
2330 @property_RO
2331 def _ps_neg(self):
2332 '''(INTERNAL) Yield the partials, I{negated}.
2333 '''
2334 for p in self._ps:
2335 yield -p
2337 def _ps_other(self, op, other):
2338 '''(INTERNAL) Yield C{other} as C{scalar}s.
2339 '''
2340 if _isFsum_2Tuple(other):
2341 for p in other._ps:
2342 yield p
2343 else:
2344 yield self._scalar(other, op)
2346 def _ps_1sum(self, *less):
2347 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
2348 '''
2349 def _1psls(ps, ls):
2350 yield _1_0
2351 for p in ps:
2352 yield p
2353 for p in ls:
2354 yield -p
2355 yield _N_1_0
2357 return _fsum(_1psls(self._ps, less))
2359 def _raiser(self, r, s, raiser=True, **RESIDUAL):
2360 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
2361 I{and} is residual C{r} I{non-zero} or I{significant} (for a
2362 negative respectively positive C{RESIDUAL} threshold)?
2363 '''
2364 if r and raiser:
2365 t = self._RESIDUAL
2366 if RESIDUAL:
2367 t = _threshold(t, **RESIDUAL)
2368 if t < 0 or (s + r) != s:
2369 q = (r / s) if s else s # == 0.
2370 if fabs(q) > fabs(t):
2371 return dict(ratio=q, R=t)
2372 return {}
2374 rdiv = __rtruediv__
2376 @property_RO
2377 def real(self):
2378 '''Get the C{real} part of this instance (C{float}).
2380 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
2381 and properties L{Fsum.ceil}, L{Fsum.floor},
2382 L{Fsum.imag} and L{Fsum.residual}.
2383 '''
2384 return float(self)
2386 @property_RO
2387 def residual(self):
2388 '''Get this instance' residual or residue (C{float} or C{int}):
2389 the C{sum(partials)} less the precision running sum C{fsum}.
2391 @note: The C{residual is INT0} iff the precision running
2392 C{fsum} is considered to be I{exact}.
2394 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
2395 '''
2396 return self._fprs2.residual
2398 def RESIDUAL(self, *threshold):
2399 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
2400 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
2402 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
2403 L{ResidualError}s in division and exponention, if
2404 C{None}, restore the default set with env variable
2405 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
2406 current setting.
2408 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
2410 @raise ResidualError: Invalid B{C{threshold}}.
2412 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}
2413 C{residual / fsum} exceeds the given B{C{threshold}} and (2)
2414 the C{residual} is non-zero and (3) is I{significant} vs the
2415 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional
2416 keyword argument C{raiser=False} is missing. Specify a
2417 negative B{C{threshold}} for only non-zero C{residual}
2418 testing without the I{significant} case.
2419 '''
2420 r = self._RESIDUAL
2421 if threshold:
2422 t = threshold[0]
2423 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
2424 (_0_0 if t else _1_0) if isbool(t) else
2425 _threshold(t)) # ... backward compatibility
2426 return r
2428 def _ResidualError(self, op, other, residual, **mod_R):
2429 '''(INTERNAL) Non-zero B{C{residual}} etc.
2430 '''
2431 def _p(mod=None, R=0, **unused): # ratio=0
2432 return (_non_zero_ if R < 0 else _significant_) \
2433 if mod is None else _integer_
2435 t = _stresidual(_p(**mod_R), residual, **mod_R)
2436 return self._Error(op, other, ResidualError, txt=t)
2438 def root(self, root, **raiser_RESIDUAL):
2439 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
2441 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2442 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any
2443 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar}
2444 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2446 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
2448 @raise ResidualError: Non-zero, significant residual or invalid
2449 B{C{RESIDUAL}}.
2451 @see: Method L{Fsum.pow}.
2452 '''
2453 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL)
2454 f = self._copy_2(self.root)
2455 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
2457 def _scalar(self, other, op, **txt):
2458 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}.
2459 '''
2460 if isscalar(other):
2461 return other
2462 raise self._Error(op, other, _TypeError, **txt) # _invalid_
2464 def signOf(self, res=True):
2465 '''Determine the sign of this instance.
2467 @kwarg res: If C{True}, consider the residual,
2468 otherwise ignore the latter (C{bool}).
2470 @return: The sign (C{int}, -1, 0 or +1).
2471 '''
2472 s, r = self._nfprs2
2473 r = (-r) if res else 0
2474 return _signOf(s, r)
2476 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
2477 '''Return this C{Fsum} instance as representation.
2479 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
2480 for method L{Fsum.toStr}.
2482 @return: This instance (C{repr}).
2483 '''
2484 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
2486 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
2487 '''Return this C{Fsum} instance as string.
2489 @kwarg lenc: If C{True}, include the current C{[len]} of this
2490 L{Fsum} enclosed in I{[brackets]} (C{bool}).
2491 @kwarg prec_sep_fmt: Optional keyword arguments for method
2492 L{Fsum2Tuple.toStr}.
2494 @return: This instance (C{str}).
2495 '''
2496 p = self.classname
2497 if lenc:
2498 p = Fmt.SQUARE(p, len(self))
2499 n = _enquote(self.name, white=_UNDER_)
2500 t = self._nfprs2.toStr(**prec_sep_fmt)
2501 return NN(p, _SPACE_, n, t)
2503 def _truediv(self, other, op, **raiser_RESIDUAL):
2504 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
2505 '''
2506 f = self._copy_2(self.__truediv__)
2507 return f._ftruediv(other, op, **raiser_RESIDUAL)
2509 def _update(self, updated=True): # see ._fset
2510 '''(INTERNAL) Zap all cached C{Property_RO} values.
2511 '''
2512 if updated:
2513 _pop = self.__dict__.pop
2514 for p in _ROs:
2515 _ = _pop(p, None)
2516# Fsum._fint2._update(self)
2517# Fsum._fprs ._update(self)
2518# Fsum._fprs2._update(self)
2519 return self # for .fset_
2521_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
2523if _NONFINITES == _std_: # PYCHOK no cover
2524 _ = nonfiniterrors(False)
2527def _Float_Int(arg, **name_Error):
2528 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit.
2529 '''
2530 U = Int if isint(arg) else Float
2531 return U(arg, **name_Error)
2534class DivMod2Tuple(_NamedTuple):
2535 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
2536 C{mod} results of a C{divmod} operation.
2538 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2539 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2540 '''
2541 _Names_ = ('div', 'mod')
2542 _Units_ = (_Float_Int, Fsum)
2545class Fsum2Tuple(_NamedTuple): # in .fstats
2546 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2547 and the C{residual}, the sum of the remaining partials. Each
2548 item is C{float} or C{int}.
2550 @note: If the C{residual is INT0}, the C{fsum} is considered
2551 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2552 '''
2553 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2554 _Units_ = (_Float_Int, _Float_Int)
2556 def __abs__(self): # in .fmath
2557 return self._Fsum.__abs__()
2559 def __bool__(self): # PYCHOK Python 3+
2560 return bool(self._Fsum)
2562 def __eq__(self, other):
2563 return self._other_op(other, self.__eq__)
2565 def __float__(self):
2566 return self._Fsum.__float__()
2568 def __ge__(self, other):
2569 return self._other_op(other, self.__ge__)
2571 def __gt__(self, other):
2572 return self._other_op(other, self.__gt__)
2574 def __le__(self, other):
2575 return self._other_op(other, self.__le__)
2577 def __lt__(self, other):
2578 return self._other_op(other, self.__lt__)
2580 def __int__(self):
2581 return self._Fsum.__int__()
2583 def __ne__(self, other):
2584 return self._other_op(other, self.__ne__)
2586 def __neg__(self):
2587 return self._Fsum.__neg__()
2589 __nonzero__ = __bool__ # Python 2-
2591 def __pos__(self):
2592 return self._Fsum.__pos__()
2594 def as_integer_ratio(self):
2595 '''Return this instance as the ratio of 2 integers.
2597 @see: Method L{Fsum.as_integer_ratio} for further details.
2598 '''
2599 return self._Fsum.as_integer_ratio()
2601 @property_RO
2602 def _fint2(self):
2603 return self._Fsum._fint2
2605 @property_RO
2606 def _fprs2(self):
2607 return self._Fsum._fprs2
2609 @Property_RO
2610 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2611 s, r = _s_r(*self)
2612 ps = (r, s) if r else (s,)
2613 return _Psum(ps, name=self.name)
2615 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL):
2616 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2617 '''
2618 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL)
2620 def is_exact(self):
2621 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2622 '''
2623 return self._Fsum.is_exact()
2625 def is_finite(self): # in .constants
2626 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}).
2628 @see: Function L{isfinite<pygeodesy.isfinite>}.
2629 '''
2630 return self._Fsum.is_finite()
2632 def is_integer(self):
2633 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2634 '''
2635 return self._Fsum.is_integer()
2637 def _mul_scalar(self, other, op): # for Fsum._fmul
2638 return self._Fsum._mul_scalar(other, op)
2640 @property_RO
2641 def _n(self):
2642 return self._Fsum._n
2644 def _other_op(self, other, which):
2645 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2646 return getattr(C, which.__name__)(s, other)
2648 @property_RO
2649 def _ps(self):
2650 return self._Fsum._ps
2652 @property_RO
2653 def _ps_neg(self):
2654 return self._Fsum._ps_neg
2656 def signOf(self, **res):
2657 '''Like method L{Fsum.signOf}.
2658 '''
2659 return self._Fsum.signOf(**res)
2661 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2662 '''Return this L{Fsum2Tuple} as string (C{str}).
2664 @kwarg fmt: Optional C{float} format (C{letter}).
2665 @kwarg prec_sep: Optional keyword arguments for function
2666 L{fstr<streprs.fstr>}.
2667 '''
2668 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2670_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2673class ResidualError(_ValueError):
2674 '''Error raised for a division, power or root operation of
2675 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2676 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2678 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2679 '''
2680 pass
2683try:
2684 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2686 # make sure _fsum works as expected (XXX check
2687 # float.__getformat__('float')[:4] == 'IEEE'?)
2688 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2689 del _fsum # nope, remove _fsum ...
2690 raise ImportError() # ... use _fsum below
2692 _sum = _fsum # in .elliptic
2693except ImportError:
2694 _sum = sum # in .elliptic
2696 def _fsum(xs):
2697 '''(INTERNAL) Precision summation, Python 2.5-.
2698 '''
2699 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True)
2700 return float(F._facc(xs, up=False))
2703def fsum(xs, nonfinites=None, **floats):
2704 '''Precision floating point summation from Python's C{math.fsum}.
2706 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2707 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if
2708 C{False} I{non-finites} raise an Overflow-/ValueError or if
2709 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}).
2710 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use
2711 keyword argument C{B{nonfinites}=False} instead.
2713 @return: Precision C{fsum} (C{float}).
2715 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow.
2717 @raise TypeError: Invalid B{C{xs}} item.
2719 @raise ValueError: Invalid or C{NAN} B{C{xs}} item.
2721 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites},
2722 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}.
2723 '''
2724 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0
2727def fsum_(*xs, **nonfinites):
2728 '''Precision floating point summation of all positional items.
2730 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2731 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2733 @see: Function L{fsum<fsums.fsum>} for further details.
2734 '''
2735 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1?
2738def fsumf_(*xs):
2739 '''Precision floating point summation of all positional items with I{non-finites} C{OK}.
2741 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
2742 all positional.
2744 @see: Function L{fsum_<fsums.fsum_>} for further details.
2745 '''
2746 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1?
2749def fsum1(xs, **nonfinites):
2750 '''Precision floating point summation, 1-primed.
2752 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2753 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2755 @see: Function L{fsum<fsums.fsum>} for further details.
2756 '''
2757 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0
2760def fsum1_(*xs, **nonfinites):
2761 '''Precision floating point summation of all positional items, 1-primed.
2763 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2764 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2766 @see: Function L{fsum_<fsums.fsum_>} for further details.
2767 '''
2768 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1?
2771def fsum1f_(*xs):
2772 '''Precision floating point summation of all positional items, 1-primed and
2773 with I{non-finites} C{OK}.
2775 @see: Function L{fsum_<fsums.fsum_>} for further details.
2776 '''
2777 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0
2780def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers.
2781 _x_kwds = dict(_x= (_passarg if nfOK else _2finite),
2782 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds
2783 _x_kwds.update(kwds)
2784 return _x_kwds
2787def _X_ps(X): # default C{_X} handler
2788 return X._ps # lambda X: X._ps
2791def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc
2792 origin=0, which=None, **_Cdot):
2793 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s.
2794 '''
2795 i, x = 0, xs
2796 try:
2797 for i, x in enumerate(_xiterable(xs)):
2798 if _isFsum_2Tuple(x):
2799 for p in _X(x):
2800 yield p if _isfine(p) else _nfError(p)
2801 else:
2802 f = _x(x)
2803 yield f if _isfine(f) else _nfError(f)
2805 except (OverflowError, TypeError, ValueError) as X:
2806 t = _xsError(X, xs, i + origin, x)
2807 if which: # prefix invokation
2808 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot)
2809 t = _COMMASPACE_(w, t)
2810 raise _xError(X, t, txt=None)
2813def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0
2814 '''(INTERNAL) Precision summation of C{xs} with conditions.
2815 '''
2816 if floats: # for backward compatibility
2817 nonfinites = _xkwds_get1(floats, floats=nonfinites)
2818 elif nonfinites is None:
2819 nonfinites = not nonfiniterrors()
2820 fs = _xs(xs, **_x_isfine(nonfinites, which=which))
2821 return _fsum(_1primed(fs) if primed else fs)
2824# delete all decorators, etc.
2825del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \
2826 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \
2827 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _getPYGEODESY, _std_
2829if __name__ == '__main__':
2831 # usage: python3 -m pygeodesy.fsums
2833 def _test(n):
2834 # copied from Hettinger, see L{Fsum} reference
2835 from pygeodesy import frandoms, printf
2837 printf(_fsum.__name__, end=_COMMASPACE_)
2838 printf(_psum.__name__, end=_COMMASPACE_)
2840 F = Fsum()
2841 if F.is_math_fsum():
2842 for t in frandoms(n, seeded=True):
2843 assert float(F.fset_(*t)) == _fsum(t)
2844 printf(_DOT_, end=NN)
2845 printf(NN)
2847 _test(128)
2849# **) MIT License
2850#
2851# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
2852#
2853# Permission is hereby granted, free of charge, to any person obtaining a
2854# copy of this software and associated documentation files (the "Software"),
2855# to deal in the Software without restriction, including without limitation
2856# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2857# and/or sell copies of the Software, and to permit persons to whom the
2858# Software is furnished to do so, subject to the following conditions:
2859#
2860# The above copyright notice and this permission notice shall be included
2861# in all copies or substantial portions of the Software.
2862#
2863# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2864# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2865# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2866# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2867# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2868# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2869# OTHER DEALINGS IN THE SOFTWARE.