Coverage for pygeodesy/fsums.py: 95%
1098 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-06 12:20 -0500
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-06 12:20 -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.12.02'
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 C{x} 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, ...
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_r2(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 _strcomplex(s, *args):
419 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
420 '''
421 c = _strcomplex.__name__[4:]
422 n = _sub_op_(len(args), _arg_)
423 t = unstr(pow, *args)
424 return _SPACE_(c, s, _from_, n, t)
427def _stresidual(prefix, residual, R=0, **mod_ratio):
428 '''(INTERNAL) Residual error txt C{str}.
429 '''
430 p = _stresidual.__name__[3:]
431 t = Fmt.PARENSPACED(p, Fmt(residual))
432 for n, v in itemsorted(mod_ratio):
433 p = Fmt.PARENSPACED(n, Fmt(v))
434 t = _COMMASPACE_(t, p)
435 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_)
438def _2sum(a, b, _isfine=_isfinite): # in .testFmath
439 '''(INTERNAL) Return C{a + b} as 2-tuple C{(sum, residual)} with finite C{sum},
440 otherwise as 2-tuple C{(nonfinite, 0)} iff I{non-finites} are OK.
441 '''
442 # FastTwoSum U{Algorithm 1.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
444 # Neumaier, A. U{Rundungsfehleranalyse einiger Verfahren zur Summation endlicher
445 # Summen<https://OnlineLibrary.Wiley.com/doi/epdf/10.1002/zamm.19740540106>},
446 # 1974, Zeitschrift für Angewandte Mathmatik und Mechanik, vol 51, nr 1, p 39-51
447 # <https://StackOverflow.com/questions/78633770/can-neumaier-summation-be-sped-up>
448 s = a + b
449 if _isfinite(s):
450 if fabs(a) < fabs(b):
451 r = (b - s) + a
452 else:
453 r = (a - s) + b
454 elif _isfine(s):
455 r = _NONFINITEr
456 else: # non-finite and not OK
457 t = unstr(_2sum, a, b)
458 raise _nfError(s, t)
459 return s, r
462def _threshold(threshold=_0_0, **kwds):
463 '''(INTERNAL) Get the L{ResidualError}s threshold,
464 optionally from single kwds C{B{RESIDUAL}=scalar}.
465 '''
466 if kwds:
467 threshold = _xkwds_get1(kwds, RESIDUAL=threshold)
468 try:
469 return _2finite(threshold) # PYCHOK None
470 except Exception as x:
471 raise ResidualError(threshold=threshold, cause=x)
474def _2tuple2(other):
475 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
476 C{float} or C{as-is} and C{r} the residual of C{as-is} or 0.
477 '''
478 if _isFsum_2Tuple(other):
479 s, r = other._fint2
480 if r:
481 s, r = other._nfprs2
482 if r: # PYCHOK no cover
483 s = other # L{Fsum} as-is
484 else:
485 r = 0
486 s = other # C{type} as-is
487 if isint(s, both=True):
488 s = int(s)
489 return s, r
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 = _2tuple2(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_r2(s, r))
1649 if n > 1: # len(ps) == 2
1650 s, r = _s_r2(*_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 an L{Fsum}
1677 or L{Fsum2Tuple} instance), all positional.
1679 @return: This instance, replaced (C{Fsum}).
1681 @see: Method L{Fsum.fadd} for further details.
1682 '''
1683 f = (xs[0] if xs else _0_0) if len(xs) < 2 else \
1684 Fsum(*xs, nonfinites=self.nonfinites()) # self._Fsum_as(*xs)
1685 return self._fset(f, op=_fset_op_)
1687 def _fset(self, other, n=0, up=True, **op):
1688 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1689 '''
1690 if other is self:
1691 pass # from ._fmul, ._ftruediv and ._pow_0_1
1692 elif _isFsum_2Tuple(other):
1693 if op: # and not self.nonfinitesOK:
1694 self._finite(other._fprs, **op)
1695 self._ps[:] = other._ps
1696 self._n = n or other._n
1697 if up: # use or zap the C{Property_RO} values
1698 Fsum._fint2._update_from(self, other)
1699 Fsum._fprs ._update_from(self, other)
1700 Fsum._fprs2._update_from(self, other)
1701 elif isscalar(other):
1702 s = float(self._finite(other, **op)) if op else other
1703 self._ps[:] = s,
1704 self._n = n or 1
1705 if up: # Property _fint2, _fprs and _fprs2 all have
1706 # @.setter_underscore and NOT @.setter because the
1707 # latter's _fset zaps the value set by @.setter
1708 self._fint2 = s
1709 self._fprs = s
1710 self._fprs2 = s, INT0
1711 # assert self._fprs is s
1712 else:
1713 op = _xkwds_get1(op, op=_fset_op_)
1714 raise self._Error(op, other, _TypeError)
1715 return self
1717 def fsub(self, xs=()):
1718 '''Subtract an iterable's items from this instance.
1720 @see: Method L{Fsum.fadd} for further details.
1721 '''
1722 return self._facc_neg(xs)
1724 def fsub_(self, *xs):
1725 '''Subtract all positional items from this instance.
1727 @see: Method L{Fsum.fadd_} for further details.
1728 '''
1729 return self._fsub(xs[0], _sub_op_) if len(xs) == 1 else \
1730 self._facc_neg(xs) # origin=1?
1732 def _fsub(self, other, op):
1733 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1734 '''
1735 if _isFsum_2Tuple(other):
1736 if other is self: # or other._fprs2 == self._fprs2:
1737 self._fset(_0_0, n=len(self) * 2)
1738 elif other._ps:
1739 self._facc_scalar(other._ps_neg)
1740 elif self._scalar(other, op):
1741 self._facc_scalar_(-other)
1742 return self
1744 def fsum(self, xs=()):
1745 '''Add an iterable's items, summate and return the current
1746 precision running sum.
1748 @arg xs: Iterable of items to add (each item C{scalar},
1749 an L{Fsum} or L{Fsum2Tuple}).
1751 @return: Precision running sum (C{float} or C{int}).
1753 @see: Method L{Fsum.fadd}.
1755 @note: Accumulation can continue after summation.
1756 '''
1757 return self._facc(xs)._fprs
1759 def fsum_(self, *xs):
1760 '''Add any positional items, summate and return the current
1761 precision running sum.
1763 @arg xs: Items to add (each C{scalar}, an L{Fsum} or
1764 L{Fsum2Tuple}), all positional.
1766 @return: Precision running sum (C{float} or C{int}).
1768 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1769 '''
1770 return self._facc_args(xs)._fprs
1772 def Fsum_(self, *xs, **name):
1773 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1775 @kwarg name: Optional name (C{str}).
1777 @return: Copy of this updated instance (L{Fsum}).
1778 '''
1779 return self._facc_args(xs)._copy_2(self.Fsum_, **name)
1781 def Fsum2Tuple_(self, *xs, **name):
1782 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1784 @kwarg name: Optional name (C{str}).
1786 @return: Precision running sum (L{Fsum2Tuple}).
1787 '''
1788 return Fsum2Tuple(self._facc_args(xs)._nfprs2, **name)
1790 @property_RO
1791 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, in .fstats
1792 return self # NOT @Property_RO, see .copy and ._copy_2
1794 def _Fsum_as(self, *xs, **name_f2product_nonfinites_RESIDUAL):
1795 '''(INTERNAL) Return an C{Fsum} with this C{Fsum}'s C{.f2product},
1796 C{.nonfinites} and C{.RESIDUAL} setting, optionally
1797 overridden with C{name_f2product_nonfinites_RESIDUAL} and
1798 with any C{xs} accumulated.
1799 '''
1800 kwds = _xkwds_not(None, Fsum._RESIDUAL, f2product =self.f2product(),
1801 nonfinites=self.nonfinites(),
1802 RESIDUAL =self.RESIDUAL())
1803 if name_f2product_nonfinites_RESIDUAL: # overwrites
1804 kwds.update(name_f2product_nonfinites_RESIDUAL)
1805 f = Fsum(**kwds)
1806 # assert all(v == self.__dict__[n] for n, v in f.__dict__.items())
1807 return f._fset(xs[0], op=_fset_op_) if len(xs) == 1 else (
1808 f._facc(xs, up=False) if xs else f)
1810 def fsum2(self, xs=(), **name):
1811 '''Add an iterable's items, summate and return the
1812 current precision running sum I{and} the C{residual}.
1814 @arg xs: Iterable of items to add (each item C{scalar},
1815 an L{Fsum} or L{Fsum2Tuple}).
1816 @kwarg name: Optional C{B{name}=NN} (C{str}).
1818 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1819 current precision running sum and C{residual}, the
1820 (precision) sum of the remaining C{partials}. The
1821 C{residual is INT0} if the C{fsum} is considered
1822 to be I{exact}.
1824 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1825 '''
1826 t = self._facc(xs)._fprs2
1827 return t.dup(name=name) if name else t
1829 def fsum2_(self, *xs):
1830 '''Add any positional items, summate and return the current
1831 precision running sum and the I{differential}.
1833 @arg xs: Values to add (each C{scalar}, an L{Fsum} or
1834 L{Fsum2Tuple}), all positional.
1836 @return: 2Tuple C{(fsum, delta)} with the current, precision
1837 running C{fsum} like method L{Fsum.fsum} and C{delta},
1838 the difference with previous running C{fsum}, C{float}.
1840 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1841 '''
1842 return self._fsum2(xs, self._facc_args)
1844 def _fsum2(self, xs, _facc, **facc_kwds):
1845 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1846 '''
1847 p, q = self._fprs2
1848 if xs:
1849 s, r = _facc(xs, **facc_kwds)._fprs2
1850 if _isfinite(s): # _fsum(_1primed((s, -p, r, -q))
1851 d, r = _2sum(s - p, r - q, _isfine=_isOK)
1852 r, _ = _s_r2(d, r)
1853 return s, (r if _isfinite(r) else _NONFINITEr)
1854 else:
1855 return p, _0_0
1857 def fsumf_(self, *xs):
1858 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}}, each I{known to be}
1859 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1860 '''
1861 return self._facc_scalarf(xs, which=self.fsumf_)._fprs # origin=1?
1863 def Fsumf_(self, *xs):
1864 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}}, each I{known to be}
1865 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1866 '''
1867 return self._facc_scalarf(xs, which=self.Fsumf_)._copy_2(self.Fsumf_) # origin=1?
1869 def fsum2f_(self, *xs):
1870 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}}, each I{known to be}
1871 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1872 '''
1873 return self._fsum2(xs, self._facc_scalarf, which=self.fsum2f_) # origin=1?
1875# ftruediv = __itruediv__ # for naming consistency?
1877 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1878 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1879 '''
1880 n = _1_0
1881 if _isFsum_2Tuple(other):
1882 if other is self or self == other:
1883 return self._fset(n, n=len(self))
1884 d, r = other._fprs2
1885 if r:
1886 R = self._raiser(r, d, **raiser_RESIDUAL)
1887 if R:
1888 raise self._ResidualError(op, other, r, **R)
1889 d, n = other.as_integer_ratio()
1890 else:
1891 d = self._scalar(other, op)
1892 try:
1893 s = n / d
1894 except Exception as X:
1895 raise self._ErrorX(X, op, other)
1896 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1897 return self._fset(f)
1899 @property_RO
1900 def imag(self):
1901 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1903 @see: Property L{Fsum.real}.
1904 '''
1905 return _0_0
1907 def int_float(self, **raiser_RESIDUAL):
1908 '''Return this instance' current running sum as C{int} or C{float}.
1910 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1911 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1912 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1914 @return: This C{int} sum if this instance C{is_integer} and
1915 I{finite}, otherwise the C{float} sum if the residual
1916 is zero or not significant.
1918 @raise ResidualError: Non-zero, significant residual or invalid
1919 B{C{RESIDUAL}}.
1921 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.is_integer},
1922 L{Fsum.RESIDUAL} and property L{Fsum.as_iscalar}.
1923 '''
1924 s, r = self._fint2
1925 if r:
1926 s, r = self._fprs2
1927 if r: # PYCHOK no cover
1928 R = self._raiser(r, s, **raiser_RESIDUAL)
1929 if R:
1930 t = _stresidual(_non_zero_, r, **R)
1931 raise ResidualError(int_float=s, txt=t)
1932 s = float(s)
1933 return s
1935 def is_exact(self):
1936 '''Is this instance' running C{fsum} considered to be exact?
1937 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1938 '''
1939 return self.residual is INT0
1941 def is_finite(self): # in .constants
1942 '''Is this instance C{finite}? (C{bool}).
1944 @see: Function L{isfinite<pygeodesy.isfinite>}.
1945 '''
1946 return _isfinite(sum(self._ps)) # == sum(self)
1948 def is_integer(self):
1949 '''Is this instance' running sum C{integer}? (C{bool}).
1951 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1952 '''
1953 s, r = self._fint2
1954 return False if r else (_isfinite(s) and isint(s))
1956 def is_math_fma(self):
1957 '''Is accurate L{f2product} multiplication based on Python's C{math.fma}?
1959 @return: C{True} if accurate multiplication uses C{math.fma}, C{False}
1960 an C{fma} implementation as C{math.fma} or C{None}, a previous
1961 C{PyGeodesy} implementation.
1962 '''
1963 return (_2split3s is _passarg) or (False if _2n_d is None else None)
1965 def is_math_fsum(self):
1966 '''Are the summation functions L{fsum}, L{fsum_}, L{fsumf_}, L{fsum1},
1967 L{fsum1_} and L{fsum1f_} based on Python's C{math.fsum}?
1969 @return: C{True} if summation functions use C{math.fsum}, C{False}
1970 otherwise.
1971 '''
1972 return _sum is _fsum # _fsum.__module__ is fabs.__module__
1974 def is_scalar(self, **raiser_RESIDUAL):
1975 '''Is this instance' running sum C{scalar} with C{0} residual or with
1976 a residual I{ratio} not exceeding the RESIDUAL threshold?
1978 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1979 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1980 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1982 @return: C{True} if this instance' residual is C{0} or C{insignificant},
1983 i.e. its residual C{ratio} doesn't exceed the L{RESIDUAL
1984 <Fsum.RESIDUAL>} threshold (C{bool}).
1986 @raise ResidualError: Non-zero, significant residual or invalid
1987 B{C{RESIDUAL}}.
1989 @see: Methods L{Fsum.RESIDUAL} and L{Fsum.is_integer} and property
1990 L{Fsum.as_iscalar}.
1991 '''
1992 s, r = self._fprs2
1993 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1995 def _mul_Fsum(self, other, op):
1996 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1997 '''
1998 # assert _isFsum_2Tuple(other)
1999 if self._ps and other._ps:
2000 try:
2001 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
2002 except Exception as X:
2003 raise self._ErrorX(X, op, other)
2004 else:
2005 f = _0_0
2006 return f
2008 def _mul_reduce(self, *others):
2009 '''(INTERNAL) Like fmath.fprod for I{non-finite} C{other}s.
2010 '''
2011 r = _1_0
2012 for f in others:
2013 r *= sum(f._ps) if _isFsum_2Tuple(f) else float(f)
2014 return r
2016 def _mul_scalar(self, factor, op):
2017 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
2018 '''
2019 # assert isscalar(factor)
2020 if self._ps and self._finite(factor, op=op):
2021 f = self if factor == _1_0 else (
2022 self._neg if factor == _N_1_0 else
2023 self._ps_mul(op, factor).as_iscalar)
2024 else:
2025 f = _0_0
2026 return f
2028# @property_RO
2029# def _n_d(self):
2030# n, d = self.as_integer_ratio()
2031# return n / d
2033 @property_RO
2034 def _neg(self):
2035 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
2036 '''
2037 return _Psum(self._ps_neg) if self._ps else NEG0
2039 @property_RO
2040 def _nfprs2(self):
2041 '''(INTERNAL) Handle I{non-finite} C{_fprs2}.
2042 '''
2043 try: # to handle nonfiniterrors, etc.
2044 t = self._fprs2
2045 except (OverflowError, ValueError):
2046 t = Fsum2Tuple(sum(self._ps), _NONFINITEr)
2047 return t
2049 def nonfinites(self, *OK):
2050 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan}
2051 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively
2052 C{ValueError} exceptions, overriding the L{nonfiniterrors} default.
2054 @arg OK: If omitted, leave the override unchanged, if C{True},
2055 I{non-finites} are C{OK}, if C{False} throw exceptions
2056 or if C{None} remove the override (C{bool} or C{None}).
2058 @return: The previous setting (C{bool} or C{None} if not set).
2060 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}.
2062 @note: Use property L{nonfinitesOK<Fsum.nonfinitesOK>} to determine
2063 whether I{non-finites} are C{OK} for this L{Fsum} and by the
2064 L{nonfiniterrors} default.
2065 '''
2066 _ks = Fsum._nonfinites_isfine_kwds
2067 if OK: # delattrof(self, _isfine=None)
2068 k = _xkwds_pop(self.__dict__, _isfine=None)
2069 if OK[0] is not None:
2070 self._isfine = _ks[bool(OK[0])]
2071 self._update()
2072 else: # getattrof(self, _isfine=None)
2073 k = _xkwds_get(self.__dict__, _isfine=None)
2074 # dict(map(reversed, _ks.items())).get(k, None)
2075 # raises a TypeError: unhashable type: 'dict'
2076 return True if k is _ks[True] else (
2077 False if k is _ks[False] else None)
2079 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK),
2080 False: dict(_isfine=_isfinite)}
2082 @property_RO
2083 def nonfinitesOK(self):
2084 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}).
2085 '''
2086# nf = self.nonfinites()
2087# if nf is None:
2088# nf = not nonfiniterrors()
2089 return _isOK_or_finite(INF, **self._isfine)
2091 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None):
2092 '''(INTERNAL) Handle a I{non-finite} exception.
2093 '''
2094 if nonfinites is None:
2095 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser)
2096 if not nonfinites:
2097 raise self._ErrorX(X, op, f)
2098 return f
2100 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL):
2101 '''(INTERNAL) Re/set options from keyword arguments.
2102 '''
2103 if f2product is not None:
2104 self.f2product(f2product)
2105 if nonfinites is not None:
2106 self.nonfinites(nonfinites)
2107 if name_RESIDUAL: # MUST be last
2108 n, kwds = _name2__(**name_RESIDUAL)
2109 if kwds:
2110 R = Fsum._RESIDUAL
2111 t = _threshold(R, **kwds)
2112 if t != R:
2113 self._RESIDUAL = t
2114 if n:
2115 self.name = n # self.rename(n)
2117 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over
2118 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
2119 '''
2120 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
2122 @property_RO
2123 def partials(self):
2124 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
2125 '''
2126 return tuple(self._ps)
2128 def pow(self, x, *mod, **raiser_RESIDUAL):
2129 '''Return C{B{self}**B{x}} as L{Fsum}.
2131 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2132 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
2133 C{pow(B{self}, B{other}, B{mod})} version.
2134 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
2135 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
2136 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2138 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
2139 result (L{Fsum}).
2141 @raise ResidualError: Non-zero, significant residual or invalid
2142 B{C{RESIDUAL}}.
2144 @note: If B{C{mod}} is given and C{None}, the result will be an
2145 C{integer} L{Fsum} provided this instance C{is_integer}
2146 or set to C{integer} by an L{Fsum.fint} call.
2148 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
2149 and L{Fsum.root}.
2150 '''
2151 f = self._copy_2(self.pow)
2152 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
2154 def _pow(self, other, unused, op, **raiser_RESIDUAL):
2155 '''Return C{B{self} ** B{other}}.
2156 '''
2157 if _isFsum_2Tuple(other):
2158 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
2159 elif self._scalar(other, op):
2160 x = self._finite(other, op=op)
2161 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2162 else:
2163 f = self._pow_0_1(0, other)
2164 return f
2166 def _pow_0_1(self, x, other):
2167 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
2168 '''
2169 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
2171 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
2172 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
2173 B{x}, int B{mod} or C{None})}, embellishing errors.
2174 '''
2176 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
2177 m = mod[0]
2178 # assert _isFsum_2Tuple(b)
2180 def _s(s, r):
2181 R = self._raiser(r, s, **raiser_RESIDUAL)
2182 if R:
2183 raise self._ResidualError(op, other, r, mod=m, **R)
2184 return s
2186 b = _s(*(b._fprs2 if m is None else b._fint2))
2187 x = _s(*_2tuple2(x))
2189 try:
2190 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
2191 s = pow(b, x, *mod)
2192 if iscomplex(s):
2193 # neg**frac == complex in Python 3+, but ValueError in 2-
2194 raise ValueError(_strcomplex(s, b, x, *mod))
2195 _ = _2finite(s, **self._isfine) # ignore float
2196 return s
2197 except Exception as X:
2198 raise self._ErrorX(X, op, other, *mod)
2200 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
2201 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}.
2202 '''
2203 # assert _isFsum_2Tuple(other)
2204 x, r = other._fprs2
2205 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2206 if f and r:
2207 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
2208 return f
2210 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
2211 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
2212 '''
2213 # assert isint(x) and x >= 0
2214 ps = self._ps
2215 if len(ps) > 1:
2216 _mul_Fsum = Fsum._mul_Fsum
2217 if x > 4:
2218 p = self
2219 f = self if (x & 1) else self._Fsum_as(_1_0)
2220 m = x >> 1 # // 2
2221 while m:
2222 p = _mul_Fsum(p, p, op) # p **= 2
2223 if (m & 1):
2224 f = _mul_Fsum(f, p, op) # f *= p
2225 m >>= 1 # //= 2
2226 elif x > 1: # self**2, 3, or 4
2227 f = _mul_Fsum(self, self, op)
2228 if x > 2: # self**3 or 4
2229 p = self if x < 4 else f
2230 f = _mul_Fsum(f, p, op)
2231 else: # self**1 or self**0 == 1 or _1_0
2232 f = self._pow_0_1(x, other)
2233 elif ps: # self._ps[0]**x
2234 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
2235 else: # PYCHOK no cover
2236 # 0**pos_int == 0, but 0**0 == 1
2237 f = 0 if x else 1
2238 return f
2240 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
2241 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
2242 '''
2243 s, r = self._fprs2
2244 if r:
2245 # assert s != 0
2246 if isint(x, both=True): # self**int
2247 x = int(x)
2248 y = abs(x)
2249 if y > 1:
2250 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
2251 if x > 0: # i.e. > 1
2252 return f # Fsum or scalar
2253 # assert x < 0 # i.e. < -1
2254 if _isFsum(f):
2255 s, r = f._fprs2
2256 if r:
2257 return self._1_Over(f, op, **raiser_RESIDUAL)
2258 else: # scalar
2259 s = f
2260 # use s**(-1) to get the CPython
2261 # float_pow error iff s is zero
2262 x = -1
2263 elif x < 0: # self**(-1)
2264 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self
2265 else: # self**1 or self**0
2266 return self._pow_0_1(x, other) # self, 1 or 1.0
2267 else: # self**fractional
2268 R = self._raiser(r, s, **raiser_RESIDUAL)
2269 if R:
2270 raise self._ResidualError(op, other, r, **R)
2271 n, d = self.as_integer_ratio()
2272 if abs(n) > abs(d):
2273 n, d, x = d, n, (-x)
2274 s = n / d
2275 # assert isscalar(s) and isscalar(x)
2276 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
2278 def _ps_acc(self, ps, xs, up=True, **unused):
2279 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.
2280 '''
2281 n = 0
2282 _2s = _2sum
2283 _fi = self._isfine
2284 for x in (tuple(xs) if xs is ps else xs):
2285 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine)
2286 if x:
2287 i = 0
2288 for p in ps:
2289 x, p = _2s(x, p, **_fi)
2290 if p:
2291 ps[i] = p
2292 i += 1
2293 ps[i:] = (x,) if x else ()
2294 n += 1
2295 if n:
2296 self._n += n
2297 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
2298 if up:
2299 self._update()
2300# x = sum(ps)
2301# if not _isOK_or_finite(x, **fi):
2302# ps[:] = x, # collapse ps
2303 return ps
2305 def _ps_mul(self, op, *factors):
2306 '''(INTERNAL) Multiply this instance' C{partials} with
2307 each scalar C{factor} and accumulate into an C{Fsum}.
2308 '''
2309 def _psfs(ps, fs, _isfine=_isfinite):
2310 if len(ps) < len(fs):
2311 ps, fs = fs, ps
2312 if self._f2product:
2313 fs, p = _2split3s(fs), fs
2314 if len(ps) > 1 and fs is not p:
2315 fs = tuple(fs) # several ps
2316 _pfs = _2products
2317 else:
2318 def _pfs(p, fs):
2319 return (p * f for f in fs)
2321 for p in ps:
2322 for x in _pfs(p, fs):
2323 yield x if _isfine(x) else _nfError(x)
2325 xs = _psfs(self._ps, factors, **self._isfine)
2326 f = _Psum(self._ps_acc([], xs, up=False), name=op)
2327 return f
2329 @property_RO
2330 def _ps_neg(self):
2331 '''(INTERNAL) Yield the partials, I{negated}.
2332 '''
2333 for p in self._ps:
2334 yield -p
2336 def _ps_other(self, op, other):
2337 '''(INTERNAL) Yield C{other} as C{scalar}s.
2338 '''
2339 if _isFsum_2Tuple(other):
2340 for p in other._ps:
2341 yield p
2342 else:
2343 yield self._scalar(other, op)
2345 def _ps_1sum(self, *less):
2346 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
2347 '''
2348 def _1psls(ps, ls):
2349 yield _1_0
2350 for p in ps:
2351 yield p
2352 for p in ls:
2353 yield -p
2354 yield _N_1_0
2356 return _fsum(_1psls(self._ps, less))
2358 def _raiser(self, r, s, raiser=True, **RESIDUAL):
2359 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
2360 I{and} is residual C{r} I{non-zero} or I{significant} (for a
2361 negative respectively positive C{RESIDUAL} threshold)?
2362 '''
2363 if r and raiser:
2364 t = self._RESIDUAL
2365 if RESIDUAL:
2366 t = _threshold(t, **RESIDUAL)
2367 if t < 0 or (s + r) != s:
2368 q = (r / s) if s else s # == 0.
2369 if fabs(q) > fabs(t):
2370 return dict(ratio=q, R=t)
2371 return {}
2373 rdiv = __rtruediv__
2375 @property_RO
2376 def real(self):
2377 '''Get the C{real} part of this instance (C{float}).
2379 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
2380 and properties L{Fsum.ceil}, L{Fsum.floor},
2381 L{Fsum.imag} and L{Fsum.residual}.
2382 '''
2383 return float(self)
2385 @property_RO
2386 def residual(self):
2387 '''Get this instance' residual or residue (C{float} or C{int}):
2388 the C{sum(partials)} less the precision running sum C{fsum}.
2390 @note: The C{residual is INT0} iff the precision running
2391 C{fsum} is considered to be I{exact}.
2393 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
2394 '''
2395 return self._fprs2.residual
2397 def RESIDUAL(self, *threshold):
2398 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
2399 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
2401 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
2402 L{ResidualError}s in division and exponention, if
2403 C{None}, restore the default set with env variable
2404 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
2405 current setting.
2407 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
2409 @raise ResidualError: Invalid B{C{threshold}}.
2411 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}
2412 C{residual / fsum} exceeds the given B{C{threshold}} and (2)
2413 the C{residual} is non-zero and (3) is I{significant} vs the
2414 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional
2415 keyword argument C{raiser=False} is missing. Specify a
2416 negative B{C{threshold}} for only non-zero C{residual}
2417 testing without the I{significant} case.
2418 '''
2419 r = self._RESIDUAL
2420 if threshold:
2421 t = threshold[0]
2422 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
2423 (_0_0 if t else _1_0) if isbool(t) else
2424 _threshold(t)) # ... backward compatibility
2425 return r
2427 def _ResidualError(self, op, other, residual, **mod_R):
2428 '''(INTERNAL) Non-zero B{C{residual}} etc.
2429 '''
2430 def _p(mod=None, R=0, **unused): # ratio=0
2431 return (_non_zero_ if R < 0 else _significant_) \
2432 if mod is None else _integer_
2434 t = _stresidual(_p(**mod_R), residual, **mod_R)
2435 return self._Error(op, other, ResidualError, txt=t)
2437 def root(self, root, **raiser_RESIDUAL):
2438 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
2440 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2441 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any
2442 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar}
2443 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2445 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
2447 @raise ResidualError: Non-zero, significant residual or invalid
2448 B{C{RESIDUAL}}.
2450 @see: Method L{Fsum.pow}.
2451 '''
2452 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL)
2453 f = self._copy_2(self.root)
2454 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
2456 def _scalar(self, other, op, **txt):
2457 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}.
2458 '''
2459 if isscalar(other):
2460 return other
2461 raise self._Error(op, other, _TypeError, **txt) # _invalid_
2463 def signOf(self, res=True):
2464 '''Determine the sign of this instance.
2466 @kwarg res: If C{True}, consider the residual,
2467 otherwise ignore the latter (C{bool}).
2469 @return: The sign (C{int}, -1, 0 or +1).
2470 '''
2471 s, r = self._nfprs2
2472 r = (-r) if res else 0
2473 return _signOf(s, r)
2475 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
2476 '''Return this C{Fsum} instance as representation.
2478 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
2479 for method L{Fsum.toStr}.
2481 @return: This instance (C{repr}).
2482 '''
2483 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
2485 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
2486 '''Return this C{Fsum} instance as string.
2488 @kwarg lenc: If C{True}, include the current C{[len]} of this
2489 L{Fsum} enclosed in I{[brackets]} (C{bool}).
2490 @kwarg prec_sep_fmt: Optional keyword arguments for method
2491 L{Fsum2Tuple.toStr}.
2493 @return: This instance (C{str}).
2494 '''
2495 p = self.classname
2496 if lenc:
2497 p = Fmt.SQUARE(p, len(self))
2498 n = _enquote(self.name, white=_UNDER_)
2499 t = self._nfprs2.toStr(**prec_sep_fmt)
2500 return NN(p, _SPACE_, n, t)
2502 def _truediv(self, other, op, **raiser_RESIDUAL):
2503 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
2504 '''
2505 f = self._copy_2(self.__truediv__)
2506 return f._ftruediv(other, op, **raiser_RESIDUAL)
2508 def _update(self, updated=True): # see ._fset
2509 '''(INTERNAL) Zap all cached C{Property_RO} values.
2510 '''
2511 if updated:
2512 _pop = self.__dict__.pop
2513 for p in _ROs:
2514 _ = _pop(p, None)
2515# Fsum._fint2._update(self)
2516# Fsum._fprs ._update(self)
2517# Fsum._fprs2._update(self)
2518 return self # for .fset_
2520_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
2522if _NONFINITES == _std_: # PYCHOK no cover
2523 _ = nonfiniterrors(False)
2526def _Float_Int(arg, **name_Error):
2527 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit.
2528 '''
2529 U = Int if isint(arg) else Float
2530 return U(arg, **name_Error)
2533class DivMod2Tuple(_NamedTuple):
2534 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
2535 C{mod} results of a C{divmod} operation.
2537 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2538 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2539 '''
2540 _Names_ = ('div', 'mod')
2541 _Units_ = (_Float_Int, Fsum)
2544class Fsum2Tuple(_NamedTuple): # in .fstats
2545 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2546 and the C{residual}, the sum of the remaining partials. Each
2547 item is C{float} or C{int}.
2549 @note: If the C{residual is INT0}, the C{fsum} is considered
2550 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2551 '''
2552 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2553 _Units_ = (_Float_Int, _Float_Int)
2555 def __abs__(self): # in .fmath
2556 return self._Fsum.__abs__()
2558 def __bool__(self): # PYCHOK Python 3+
2559 return bool(self._Fsum)
2561 def __eq__(self, other):
2562 return self._other_op(other, self.__eq__)
2564 def __float__(self):
2565 return self._Fsum.__float__()
2567 def __ge__(self, other):
2568 return self._other_op(other, self.__ge__)
2570 def __gt__(self, other):
2571 return self._other_op(other, self.__gt__)
2573 def __le__(self, other):
2574 return self._other_op(other, self.__le__)
2576 def __lt__(self, other):
2577 return self._other_op(other, self.__lt__)
2579 def __int__(self):
2580 return self._Fsum.__int__()
2582 def __ne__(self, other):
2583 return self._other_op(other, self.__ne__)
2585 def __neg__(self):
2586 return self._Fsum.__neg__()
2588 __nonzero__ = __bool__ # Python 2-
2590 def __pos__(self):
2591 return self._Fsum.__pos__()
2593 def as_integer_ratio(self):
2594 '''Return this instance as the ratio of 2 integers.
2596 @see: Method L{Fsum.as_integer_ratio} for further details.
2597 '''
2598 return self._Fsum.as_integer_ratio()
2600 @property_RO
2601 def _fint2(self):
2602 return self._Fsum._fint2
2604 @property_RO
2605 def _fprs2(self):
2606 return self._Fsum._fprs2
2608 @Property_RO
2609 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2610 s, r = _s_r2(*self)
2611 ps = (r, s) if r else (s,)
2612 return _Psum(ps, name=self.name)
2614 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL):
2615 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2616 '''
2617 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL)
2619 def is_exact(self):
2620 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2621 '''
2622 return self._Fsum.is_exact()
2624 def is_finite(self): # in .constants
2625 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}).
2627 @see: Function L{isfinite<pygeodesy.isfinite>}.
2628 '''
2629 return self._Fsum.is_finite()
2631 def is_integer(self):
2632 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2633 '''
2634 return self._Fsum.is_integer()
2636 def _mul_scalar(self, other, op): # for Fsum._fmul
2637 return self._Fsum._mul_scalar(other, op)
2639 @property_RO
2640 def _n(self):
2641 return self._Fsum._n
2643 def _other_op(self, other, which):
2644 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2645 return getattr(C, which.__name__)(s, other)
2647 @property_RO
2648 def _ps(self):
2649 return self._Fsum._ps
2651 @property_RO
2652 def _ps_neg(self):
2653 return self._Fsum._ps_neg
2655 def signOf(self, **res):
2656 '''Like method L{Fsum.signOf}.
2657 '''
2658 return self._Fsum.signOf(**res)
2660 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2661 '''Return this L{Fsum2Tuple} as string (C{str}).
2663 @kwarg fmt: Optional C{float} format (C{letter}).
2664 @kwarg prec_sep: Optional keyword arguments for function
2665 L{fstr<streprs.fstr>}.
2666 '''
2667 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2669_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2672class ResidualError(_ValueError):
2673 '''Error raised for a division, power or root operation of
2674 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2675 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2677 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2678 '''
2679 pass
2682try:
2683 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2685 # make sure _fsum works as expected (XXX check
2686 # float.__getformat__('float')[:4] == 'IEEE'?)
2687 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2688 del _fsum # nope, remove _fsum ...
2689 raise ImportError() # ... use _fsum below
2691 _sum = _fsum # in .elliptic
2692except ImportError:
2693 _sum = sum # in .elliptic
2695 def _fsum(xs):
2696 '''(INTERNAL) Precision summation, Python 2.5-.
2697 '''
2698 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True)
2699 return float(F._facc(xs, up=False))
2702def fsum(xs, nonfinites=None, **floats):
2703 '''Precision floating point summation from Python's C{math.fsum}.
2705 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2706 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if
2707 C{False} I{non-finites} raise an Overflow-/ValueError or if
2708 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}).
2709 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use
2710 keyword argument C{B{nonfinites}=False} instead.
2712 @return: Precision C{fsum} (C{float}).
2714 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow.
2716 @raise TypeError: Invalid B{C{xs}} item.
2718 @raise ValueError: Invalid or C{NAN} B{C{xs}} item.
2720 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites},
2721 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}.
2722 '''
2723 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0
2726def fsum_(*xs, **nonfinites):
2727 '''Precision floating point summation of all positional items.
2729 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2730 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2732 @see: Function L{fsum<fsums.fsum>} for further details.
2733 '''
2734 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1?
2737def fsumf_(*xs):
2738 '''Precision floating point summation of all positional items with I{non-finites} C{OK}.
2740 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
2741 all positional.
2743 @see: Function L{fsum_<fsums.fsum_>} for further details.
2744 '''
2745 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1?
2748def fsum1(xs, **nonfinites):
2749 '''Precision floating point summation, 1-primed.
2751 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2752 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2754 @see: Function L{fsum<fsums.fsum>} for further details.
2755 '''
2756 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0
2759def fsum1_(*xs, **nonfinites):
2760 '''Precision floating point summation of all positional items, 1-primed.
2762 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2763 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2765 @see: Function L{fsum_<fsums.fsum_>} for further details.
2766 '''
2767 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1?
2770def fsum1f_(*xs):
2771 '''Precision floating point summation of all positional items, 1-primed and
2772 with I{non-finites} C{OK}.
2774 @see: Function L{fsum_<fsums.fsum_>} for further details.
2775 '''
2776 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0
2779def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers.
2780 _x_kwds = dict(_x= (_passarg if nfOK else _2finite),
2781 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds
2782 _x_kwds.update(kwds)
2783 return _x_kwds
2786def _X_ps(X): # default C{_X} handler
2787 return X._ps # lambda X: X._ps
2790def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc
2791 origin=0, which=None, **_Cdot):
2792 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s.
2793 '''
2794 i, x = 0, xs
2795 try:
2796 for i, x in enumerate(_xiterable(xs)):
2797 if _isFsum_2Tuple(x):
2798 for p in _X(x):
2799 yield p if _isfine(p) else _nfError(p)
2800 else:
2801 f = _x(x)
2802 yield f if _isfine(f) else _nfError(f)
2804 except (OverflowError, TypeError, ValueError) as X:
2805 t = _xsError(X, xs, i + origin, x)
2806 if which: # prefix invokation
2807 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot)
2808 t = _COMMASPACE_(w, t)
2809 raise _xError(X, t, txt=None)
2812def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0
2813 '''(INTERNAL) Precision summation of C{xs} with conditions.
2814 '''
2815 if floats: # for backward compatibility
2816 nonfinites = _xkwds_get1(floats, floats=nonfinites)
2817 elif nonfinites is None:
2818 nonfinites = not nonfiniterrors()
2819 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) # PYCHOK yield
2820 return _fsum(_1primed(fs) if primed else fs)
2823# delete all decorators, etc.
2824del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \
2825 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \
2826 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _getPYGEODESY, _std_
2828if __name__ == '__main__':
2830 # usage: python3 -m pygeodesy.fsums
2832 def _test(n):
2833 # copied from Hettinger, see L{Fsum} reference
2834 from pygeodesy import frandoms, printf
2836 printf(_fsum.__name__, end=_COMMASPACE_)
2837 printf(_psum.__name__, end=_COMMASPACE_)
2839 F = Fsum()
2840 if F.is_math_fsum():
2841 for t in frandoms(n, seeded=True):
2842 assert float(F.fset_(*t)) == _fsum(t)
2843 printf(_DOT_, end=NN)
2844 printf(NN)
2846 _test(128)
2848# **) MIT License
2849#
2850# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
2851#
2852# Permission is hereby granted, free of charge, to any person obtaining a
2853# copy of this software and associated documentation files (the "Software"),
2854# to deal in the Software without restriction, including without limitation
2855# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2856# and/or sell copies of the Software, and to permit persons to whom the
2857# Software is furnished to do so, subject to the following conditions:
2858#
2859# The above copyright notice and this permission notice shall be included
2860# in all copies or substantial portions of the Software.
2861#
2862# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2863# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2864# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2865# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2866# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2867# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2868# OTHER DEALINGS IN THE SOFTWARE.