Coverage for pygeodesy/fsums.py: 95%
1095 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-09 11:05 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-09 11:05 -0400
2# -*- coding: utf-8 -*-
4u'''Class L{Fsum} for precision floating point summation similar to
5Python's C{math.fsum} enhanced with I{running} summation and as an
6option, accurate I{TwoProduct} multiplication.
8Accurate multiplication is based on the C{math.fma} function for
9Python 3.13 and newer or one of two equivalent C{fma} implementations
10for Python 3.12 and older. To enable accurate multiplication, set
11env variable C{PYGEODESY_FSUM_F2PRODUCT} to C{"std"} or any non-empty
12string or invoke function C{pygeodesy.f2product(True)} or set. With
13C{"std"} the C{fma} implemention follows the C{math.fma} function,
14otherwise the C{PyGeodesy 24.09.09} release.
16Generally, an L{Fsum} instance is considered a C{float} plus a small or
17zero C{residue} aka C{residual} value, see property L{Fsum.residual}.
19Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater
20than C{"0.0"} as the threshold to throw a L{ResidualError} for a division,
21power or root operation of an L{Fsum} with a C{residual} I{ratio} exceeding
22the threshold. See methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
23and L{Fsum.__itruediv__}.
25There are several C{integer} L{Fsum} cases, for example the result from
26functions C{ceil}, C{floor}, C{Fsum.__floordiv__} and methods L{Fsum.fint},
27L{Fsum.fint2} and L{Fsum.is_integer}. Also, L{Fsum} methods L{Fsum.pow},
28L{Fsum.__ipow__}, L{Fsum.__pow__} and L{Fsum.__rpow__} return a (very long)
29C{int} if invoked with optional argument C{mod} set to C{None}. The
30C{residual} of an C{integer} L{Fsum} is between C{-1.0} and C{+1.0} and
31will be C{INT0} if that is considered to be I{exact}.
33Set env variable C{PYGEODESY_FSUM_NONFINITES} to C{"std"} or use function
34C{pygeodesy.nonfiniterrors(False)} to allow I{non-finite} C{float}s like
35C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} and to ignore C{OverflowError}
36respectively C{ValueError} exceptions. However, in that case I{non-finite}
37results may differ from Python's C{math.fsum} results.
38'''
39# make sure int/int division yields float quotient, see .basics
40from __future__ import division as _; del _ # PYCHOK semicolon
42from pygeodesy.basics import _gcd, 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__ = '25.01.12'
69from pygeodesy.interns import (
70 _PLUS_ as _add_op_, # in .auxilats.auxAngle
71 _DSLASH_ as _floordiv_op_,
72 _EQUAL_ as _fset_op_,
73 _RANGLE_ as _gt_op_,
74 _LANGLE_ as _lt_op_,
75 _PERCENT_ as _mod_op_,
76 _STAR_ as _mul_op_,
77 _NOTEQUAL_ as _ne_op_,
78 _DSTAR_ as _pow_op_,
79 _DASH_ as _sub_op_, # in .auxilats.auxAngle
80 _SLASH_ as _truediv_op_
81)
82_divmod_op_ = _floordiv_op_ + _mod_op_
83_F2PRODUCT = _getPYGEODESY('FSUM_F2PRODUCT')
84_iadd_op_ = _add_op_ + _fset_op_ # in .auxilats.auxAngle, .fstats
85_integer_ = 'integer'
86_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle
87_NONFINITEr = _0_0 # NOT INT0!
88_NONFINITES = _getPYGEODESY('FSUM_NONFINITES')
89_non_zero_ = 'non-zero'
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
135 from pygeodesy.basics import _integer_ratio2
137 def _fma(*a_b_c): # PYCHOK no cover
138 # mimick C{math.fma} from Python 3.13+,
139 # the same accuracy, but ~14x slower
140 (na, da), (nb, db), (nc, dc) = map(_integer_ratio2, a_b_c)
141 n = na * nb * dc
142 n += da * db * nc
143 d = da * db * dc
144 try:
145 n, d = _n_d2(n, d)
146 r = float(n / d)
147 except OverflowError: # "integer division result too large ..."
148 r = NINF if (_signOf(n, 0) * _signOf(d, 0)) < 0 else INF
149 return r if _isfinite(r) else _fmaX(r, *a_b_c) # "overflow in fma"
150 else:
151 _integer_ratio2 = None # redef, in Fsum.is_math_fma
153 def _fma(a, b, c): # PYCHOK redef
154 # mimick C{math.fma} from Python 3.13+,
155 # the same accuracy, but ~13x slower
156 b3s = _2split3(b), # 1-tuple of 3-tuple
157 r = _fsum(_2products(a, b3s, c))
158 return r if _isfinite(r) else _fmaX(r, a, b, c)
160 def _fmaX(r, *a_b_c): # PYCHOK no cover
161 # handle non-finite fma result as Python 3.13+ C-function U{math_fma_impl
162 # <https://GitHub.com/python/cpython/blob/main/Modules/mathmodule.c#L2305>}:
163 # raise a ValueError for a NAN result from non-NAN C{a_b_c}s otherwise an
164 # OverflowError for a non-finite, non-NAN result from all finite C{a_b_c}s.
165 if isnan(r):
166 def _x(x):
167 return not isnan(x)
168 else: # non-finite, non-NAN
169 _x = _isfinite
170 if all(map(_x, a_b_c)):
171 raise _nfError(r, unstr(_fma, *a_b_c))
172 return r
174 def _2products(x, y3s, *zs): # PYCHOK in _fma, ...
175 # yield(x * y3 for y3 in y3s) + yield(z in zs)
176 # TwoProduct U{Algorithm 3.3<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}, also
177 # in Python 3.13+ C{Modules/mathmodule.c} under #ifndef UNRELIABLE_FMA ... #else ...
178 _, a, b = _2split3(x)
179 for y, c, d in y3s:
180 y *= x
181 yield y
182 if _isfinite(y):
183 # yield b * d - (((y - a * c) - b * c) - a * d)
184 # = b * d + (a * d - ((y - a * c) - b * c))
185 # = b * d + (a * d + (b * c - (y - a * c)))
186 # = b * d + (a * d + (b * c + (a * c - y)))
187 yield a * c - y
188 yield b * c
189 if d:
190 yield a * d
191 yield b * d
192 for z in zs:
193 yield z
195 _2FACTOR = pow(2, (MANT_DIG + 1) // 2) + _1_0 # 134217729 if MANT_DIG == 53
197 def _2split3(x):
198 # Split U{Algorithm 3.2
199 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
200 a = c = x * _2FACTOR
201 a -= c - x
202 b = x - a
203 return x, a, b
205 def _2split3s(xs): # in Fsum.is_math_fma
206 return map(_2split3, xs)
209def f2product(two=None):
210 '''Turn accurate I{TwoProduct} multiplication on or off.
212 @kwarg two: If C{True}, turn I{TwoProduct} on, if C{False} off or
213 if C{None} or omitted, keep the current setting.
215 @return: The previous setting (C{bool}).
217 @see: I{TwoProduct} multiplication is based on the I{TwoProductFMA}
218 U{Algorithm 3.5 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
219 using function C{math.fma} from Python 3.13 and later or an
220 equivalent, slower implementation when not available.
221 '''
222 t = Fsum._f2product
223 if two is not None:
224 Fsum._f2product = bool(two)
225 return t
228def _Fsumf_(*xs): # in .auxLat, ...
229 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
230 '''
231 return Fsum()._facc_scalarf(xs, up=False)
234def _Fsum1f_(*xs): # in .albers
235 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}, 1-primed.
236 '''
237 return Fsum()._facc_scalarf(_1primed(xs), origin=-1, up=False)
240def _halfeven(s, r, p):
241 '''(INTERNAL) Round half-even.
242 '''
243 if (p > 0 and r > 0) or \
244 (p < 0 and r < 0): # signs match
245 r *= 2
246 t = s + r
247 if r == (t - s):
248 s = t
249 return s
252def _isFsum(x): # in .fmath
253 '''(INTERNAL) Is C{x} an C{Fsum} instance?
254 '''
255 return isinstance(x, Fsum)
258def _isFsum_2Tuple(x): # in .basics, .constants, .fmath, .fstats
259 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance?
260 '''
261 return isinstance(x, _Fsum_2Tuple_types)
264def _isOK(unused):
265 '''(INTERNAL) Helper for C{Fsum._fsum2} and C{Fsum.nonfinites}.
266 '''
267 return True
270def _isOK_or_finite(x, _isfine=_isfinite):
271 '''(INTERNAL) Is C{x} finite or is I{non-finite} OK?
272 '''
273 # assert _isfine in (_isOK, _isfinite)
274 return _isfine(x) # C{bool}
277def _n_d2(n, d):
278 '''(INTERNAL) Reduce C{n} and C{d} by C{gcd}.
279 '''
280 if n and d:
281 try:
282 c = _gcd(n, d)
283 if c > 1:
284 return (n // c), (d // c)
285 except TypeError: # non-int float
286 pass
287 return n, d
290def _nfError(x, *args):
291 '''(INTERNAL) Throw a C{not-finite} exception.
292 '''
293 E = _NonfiniteError(x)
294 t = Fmt.PARENSPACED(_not_finite_, x)
295 if args: # in _fmaX, _2sum
296 return E(txt=t, *args)
297 raise E(t, txt=None)
300def _NonfiniteError(x):
301 '''(INTERNAL) Return the Error class for C{x}, I{non-finite}.
302 '''
303 return _OverflowError if isinf(x) else (
304 _ValueError if isnan(x) else _AssertionError)
307def nonfiniterrors(raiser=None):
308 '''Throw C{OverflowError} and C{ValueError} exceptions for or
309 handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF},
310 C{nan} and C{NAN} in summations and multiplications.
312 @kwarg raiser: If C{True}, throw exceptions, if C{False} handle
313 I{non-finites} or if C{None} or omitted, leave
314 the setting unchanged.
316 @return: Previous setting (C{bool}).
318 @note: C{inf}, C{INF} and C{NINF} throw an C{OverflowError},
319 C{nan} and C{NAN} a C{ValueError}.
320 '''
321 d = Fsum._isfine
322 if raiser is not None:
323 Fsum._isfine = {} if bool(raiser) else Fsum._nonfinites_isfine_kwds[True]
324 return (False if d is Fsum._nonfinites_isfine_kwds[True] else
325 _xkwds_get1(d, _isfine=_isfinite) is _isfinite) if d else True
328def _1primed(xs): # in .fmath
329 '''(INTERNAL) 1-Primed summation of iterable C{xs}
330 items, all I{known} to be C{scalar}.
331 '''
332 yield _1_0
333 for x in xs:
334 yield x
335 yield _N_1_0
338def _psum(ps, **_isfine): # PYCHOK used!
339 '''(INTERNAL) Partials summation, updating C{ps}.
340 '''
341 # assert isinstance(ps, list)
342 i = len(ps) - 1
343 s = _0_0 if i < 0 else ps[i]
344 while i > 0:
345 i -= 1
346 s, r = _2sum(s, ps[i], **_isfine)
347 if r: # sum(ps) became inexact
348 if s:
349 ps[i:] = r, s
350 if i > 0:
351 s = _halfeven(s, r, ps[i-1])
352 break # return s
353 s = r # PYCHOK no cover
354 elif not _isfinite(s): # non-finite OK
355 i = 0 # collapse ps
356 if ps:
357 s += sum(ps)
358 ps[i:] = s,
359 return s
362def _Psum(ps, **name_f2product_nonfinites_RESIDUAL):
363 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
364 '''
365 F = Fsum(**name_f2product_nonfinites_RESIDUAL)
366 if ps:
367 F._ps[:] = ps
368 F._n = len(F._ps)
369 return F
372def _Psum_(*ps, **name_f2product_nonfinites_RESIDUAL): # in .fmath
373 '''(INTERNAL) Return an C{Fsum} from I{known scalar} C{ps}.
374 '''
375 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL)
378def _residue(other):
379 '''(INTERNAL) Return the C{residual} or C{None} for C{scalar}.
380 '''
381 try:
382 r = other.residual
383 except AttributeError:
384 r = None # float, int, other
385 return r
388def _s_r2(s, r):
389 '''(INTERNAL) Return C{(s, r)}, I{ordered}.
390 '''
391 if _isfinite(s):
392 if r:
393 if fabs(s) < fabs(r):
394 s, r = r, (s or INT0)
395 else:
396 r = INT0
397 else:
398 r = _NONFINITEr
399 return s, r
402def _strcomplex(s, *args):
403 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
404 '''
405 c = _strcomplex.__name__[4:]
406 n = _sub_op_(len(args), _arg_)
407 t = unstr(pow, *args)
408 return _SPACE_(c, s, _from_, n, t)
411def _stresidual(prefix, residual, R=0, **mod_ratio):
412 '''(INTERNAL) Residual error txt C{str}.
413 '''
414 p = _stresidual.__name__[3:]
415 t = Fmt.PARENSPACED(p, Fmt(residual))
416 for n, v in itemsorted(mod_ratio):
417 p = Fmt.PARENSPACED(n, Fmt(v))
418 t = _COMMASPACE_(t, p)
419 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_)
422def _2sum(a, b, _isfine=_isfinite): # in .testFmath
423 '''(INTERNAL) Return C{a + b} as 2-tuple C{(sum, residual)} with finite C{sum},
424 otherwise as 2-tuple C{(nonfinite, 0)} iff I{non-finites} are OK.
425 '''
426 # FastTwoSum U{Algorithm 1.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
428 # Neumaier, A. U{Rundungsfehleranalyse einiger Verfahren zur Summation endlicher
429 # Summen<https://OnlineLibrary.Wiley.com/doi/epdf/10.1002/zamm.19740540106>},
430 # 1974, Zeitschrift für Angewandte Mathmatik und Mechanik, vol 51, nr 1, p 39-51
431 # <https://StackOverflow.com/questions/78633770/can-neumaier-summation-be-sped-up>
432 s = a + b
433 if _isfinite(s):
434 if fabs(a) < fabs(b):
435 r = (b - s) + a
436 else:
437 r = (a - s) + b
438 elif _isfine(s):
439 r = _NONFINITEr
440 else: # non-finite and not OK
441 t = unstr(_2sum, a, b)
442 raise _nfError(s, t)
443 return s, r
446def _threshold(threshold=_0_0, **kwds):
447 '''(INTERNAL) Get the L{ResidualError}s threshold,
448 optionally from single kwds C{B{RESIDUAL}=scalar}.
449 '''
450 if kwds:
451 threshold = _xkwds_get1(kwds, RESIDUAL=threshold)
452 try:
453 return _2finite(threshold) # PYCHOK None
454 except Exception as x:
455 raise ResidualError(threshold=threshold, cause=x)
458def _2tuple2(other):
459 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
460 C{float} or C{as-is} and C{r} the residual of C{as-is} or 0.
461 '''
462 if _isFsum_2Tuple(other):
463 s, r = other._fint2
464 if r:
465 s, r = other._nfprs2
466 if r: # PYCHOK no cover
467 s = other # L{Fsum} as-is
468 else:
469 r = 0
470 s = other # C{type} as-is
471 if isint(s, both=True):
472 s = int(s)
473 return s, r
476class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase, .fstats, ...
477 '''Precision floating point summation, I{running} summation and accurate multiplication.
479 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
480 I{running}, precision floating point summations. Accumulation may continue after any
481 intermediate, I{running} summuation.
483 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances,
484 i.e. any C{type} having method C{__float__}.
486 @note: Handling of I{non-finites} as C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} is
487 determined by function L{nonfiniterrors<fsums.nonfiniterrors>} for the default
488 and by method L{nonfinites<Fsum.nonfinites>} for individual C{Fsum} instances,
489 overruling the default. For backward compatibility, I{non-finites} raise
490 exceptions by default.
492 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/
493 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>},
494 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
495 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
496 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
497 <https://Bugs.Python.org/issue2819>}.
499 @see: Method L{f2product<Fsum.f2product>} for details about accurate I{TwoProduct}
500 multiplication.
502 @see: Module L{fsums<pygeodesy.fsums>} for env variables C{PYGEODESY_FSUM_F2PRODUCT},
503 C{PYGEODESY_FSUM_NONFINITES} and C{PYGEODESY_FSUM_RESIDUAL}.
504 '''
505 _f2product = _MODS.sys_version_info2 > (3, 12) or bool(_F2PRODUCT)
506 _isfine = {} # == _isfinite, see nonfiniterrors()
507 _n = 0
508# _ps = [] # partial sums
509# _ps_max = 0 # max(Fsum._ps_max, len(Fsum._ps)) # 41
510 _RESIDUAL = _threshold(_RESIDUAL_0_0)
512 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL):
513 '''New L{Fsum}.
515 @arg xs: No, one or more initial items to accumulate (each C{scalar}, an
516 L{Fsum} or L{Fsum2Tuple}), all positional.
517 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str})
518 and settings C{B{f2product}=None} (C{bool}), C{B{nonfinites}=None}
519 (C{bool}) and C{B{RESIDUAL}=0.0} threshold (C{scalar}) for this
520 L{Fsum}.
522 @see: Methods L{Fsum.f2product}, L{Fsum.nonfinites}, L{Fsum.RESIDUAL},
523 L{Fsum.fadd} and L{Fsum.fadd_}.
524 '''
525 if name_f2product_nonfinites_RESIDUAL:
526 self._optionals(**name_f2product_nonfinites_RESIDUAL)
527 self._ps = [] # [_0_0], see L{Fsum._fprs}
528 if xs:
529 self._facc_args(xs, up=False)
531 def __abs__(self):
532 '''Return C{abs(self)} as an L{Fsum}.
533 '''
534 s = self.signOf() # == self._cmp_0(0)
535 return (-self) if s < 0 else self._copy_2(self.__abs__)
537 def __add__(self, other):
538 '''Return C{B{self} + B{other}} as an L{Fsum}.
540 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
542 @return: The sum (L{Fsum}).
544 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
545 '''
546 f = self._copy_2(self.__add__)
547 return f._fadd(other)
549 def __bool__(self): # PYCHOK Python 3+
550 '''Return C{bool(B{self})}, C{True} iff C{residual} is zero.
551 '''
552 s, r = self._nfprs2
553 return bool(s or r) and s != -r # == self != 0
555 def __call__(self, other, **up): # in .fmath
556 '''Reset this C{Fsum} to C{other}, default C{B{up}=True}.
557 '''
558 self._ps[:] = 0, # clear for errors
559 self._fset(other, op=_fset_op_, **up)
560 return self
563 def __ceil__(self): # PYCHOK not special in Python 2-
564 '''Return this instance' C{math.ceil} as C{int} or C{float}.
566 @return: An C{int} in Python 3+, but C{float} in Python 2-.
568 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
569 '''
570 return self.ceil
572 def __cmp__(self, other): # PYCHOK no cover
573 '''Compare this with an other instance or C{scalar}, Python 2-.
575 @return: -1, 0 or +1 (C{int}).
577 @raise TypeError: Incompatible B{C{other}} C{type}.
578 '''
579 s = self._cmp_0(other, self.cmp.__name__)
580 return _signOf(s, 0)
582 def __divmod__(self, other, **raiser_RESIDUAL):
583 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
584 with quotient C{div} an C{int} in Python 3+ or C{float}
585 in Python 2- and remainder C{mod} an L{Fsum} instance.
587 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
588 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
589 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
590 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
592 @raise ResidualError: Non-zero, significant residual or invalid
593 B{C{RESIDUAL}}.
595 @see: Method L{Fsum.fdiv}.
596 '''
597 f = self._copy_2(self.__divmod__)
598 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
600 def __eq__(self, other):
601 '''Return C{(B{self} == B{other})} as C{bool} where B{C{other}}
602 is C{scalar}, an other L{Fsum} or L{Fsum2Tuple}.
603 '''
604 return self._cmp_0(other, _fset_op_ + _fset_op_) == 0
606 def __float__(self):
607 '''Return this instance' current, precision running sum as C{float}.
609 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
610 '''
611 return float(self._fprs)
613 def __floor__(self): # PYCHOK not special in Python 2-
614 '''Return this instance' C{math.floor} as C{int} or C{float}.
616 @return: An C{int} in Python 3+, but C{float} in Python 2-.
618 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
619 '''
620 return self.floor
622 def __floordiv__(self, other):
623 '''Return C{B{self} // B{other}} as an L{Fsum}.
625 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
627 @return: The C{floor} quotient (L{Fsum}).
629 @see: Methods L{Fsum.__ifloordiv__}.
630 '''
631 f = self._copy_2(self.__floordiv__)
632 return f._floordiv(other, _floordiv_op_)
634 def __ge__(self, other):
635 '''Return C{(B{self} >= B{other})}, see C{__eq__}.
636 '''
637 return self._cmp_0(other, _gt_op_ + _fset_op_) >= 0
639 def __gt__(self, other):
640 '''Return C{(B{self} > B{other})}, see C{__eq__}.
641 '''
642 return self._cmp_0(other, _gt_op_) > 0
644 def __hash__(self): # PYCHOK no cover
645 '''Return C{hash(B{self})} as C{float}.
646 '''
647 # @see: U{Notes for type implementors<https://docs.Python.org/
648 # 3/library/numbers.html#numbers.Rational>}
649 return hash(self.partials) # tuple.__hash__()
651 def __iadd__(self, other):
652 '''Apply C{B{self} += B{other}} to this instance.
654 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
655 an iterable of several of the former.
657 @return: This instance, updated (L{Fsum}).
659 @raise TypeError: Invalid B{C{other}}, not
660 C{scalar} nor L{Fsum}.
662 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
663 '''
664 try:
665 return self._fadd(other, op=_iadd_op_)
666 except TypeError:
667 pass
668 _xiterable(other)
669 return self._facc(other)
671 def __ifloordiv__(self, other):
672 '''Apply C{B{self} //= B{other}} to this instance.
674 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
676 @return: This instance, updated (L{Fsum}).
678 @raise ResidualError: Non-zero, significant residual
679 in B{C{other}}.
681 @raise TypeError: Invalid B{C{other}} type.
683 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
685 @raise ZeroDivisionError: Zero B{C{other}}.
687 @see: Methods L{Fsum.__itruediv__}.
688 '''
689 return self._floordiv(other, _floordiv_op_ + _fset_op_)
691 def __imatmul__(self, other): # PYCHOK no cover
692 '''Not implemented.'''
693 return _NotImplemented(self, other)
695 def __imod__(self, other):
696 '''Apply C{B{self} %= B{other}} to this instance.
698 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
700 @return: This instance, updated (L{Fsum}).
702 @see: Method L{Fsum.__divmod__}.
703 '''
704 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
706 def __imul__(self, other):
707 '''Apply C{B{self} *= B{other}} to this instance.
709 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
711 @return: This instance, updated (L{Fsum}).
713 @raise OverflowError: Partial C{2sum} overflow.
715 @raise TypeError: Invalid B{C{other}} type.
717 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
718 '''
719 return self._fmul(other, _mul_op_ + _fset_op_)
721 def __int__(self):
722 '''Return this instance as an C{int}.
724 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
725 and L{Fsum.floor}.
726 '''
727 i, _ = self._fint2
728 return i
730 def __invert__(self): # PYCHOK no cover
731 '''Not implemented.'''
732 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
733 return _NotImplemented(self)
735 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
736 '''Apply C{B{self} **= B{other}} to this instance.
738 @arg other: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
739 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
740 C{pow(B{self}, B{other}, B{mod})} version.
741 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
742 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
743 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
745 @return: This instance, updated (L{Fsum}).
747 @note: If B{C{mod}} is given, the result will be an C{integer}
748 L{Fsum} in Python 3+ if this instance C{is_integer} or
749 set to C{as_integer} and B{C{mod}} is given and C{None}.
751 @raise OverflowError: Partial C{2sum} overflow.
753 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
754 is non-zero and significant and either
755 B{C{other}} is a fractional or negative
756 C{scalar} or B{C{mod}} is given and not
757 C{None}.
759 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
760 invocation failed.
762 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
763 instance is C{0} or B{C{other}} is a fractional
764 C{scalar} and this instance is negative or has a
765 non-zero and significant residual or B{C{mod}}
766 is given as C{0}.
768 @see: CPython function U{float_pow<https://GitHub.com/
769 python/cpython/blob/main/Objects/floatobject.c>}.
770 '''
771 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
773 def __isub__(self, other):
774 '''Apply C{B{self} -= B{other}} to this instance.
776 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
777 an iterable of several of the former.
779 @return: This instance, updated (L{Fsum}).
781 @raise TypeError: Invalid B{C{other}} type.
783 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
784 '''
785 try:
786 return self._fsub(other, _isub_op_)
787 except TypeError:
788 pass
789 _xiterable(other)
790 return self._facc_neg(other)
792 def __iter__(self):
793 '''Return an C{iter}ator over a C{partials} duplicate.
794 '''
795 return iter(self.partials)
797 def __itruediv__(self, other, **raiser_RESIDUAL):
798 '''Apply C{B{self} /= B{other}} to this instance.
800 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
801 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
802 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
803 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
805 @return: This instance, updated (L{Fsum}).
807 @raise OverflowError: Partial C{2sum} overflow.
809 @raise ResidualError: Non-zero, significant residual or invalid
810 B{C{RESIDUAL}}.
812 @raise TypeError: Invalid B{C{other}} type.
814 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
816 @raise ZeroDivisionError: Zero B{C{other}}.
818 @see: Method L{Fsum.__ifloordiv__}.
819 '''
820 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
822 def __le__(self, other):
823 '''Return C{(B{self} <= B{other})}, see C{__eq__}.
824 '''
825 return self._cmp_0(other, _lt_op_ + _fset_op_) <= 0
827 def __len__(self):
828 '''Return the number of values accumulated (C{int}).
829 '''
830 return self._n
832 def __lt__(self, other):
833 '''Return C{(B{self} < B{other})}, see C{__eq__}.
834 '''
835 return self._cmp_0(other, _lt_op_) < 0
837 def __matmul__(self, other): # PYCHOK no cover
838 '''Not implemented.'''
839 return _NotImplemented(self, other)
841 def __mod__(self, other):
842 '''Return C{B{self} % B{other}} as an L{Fsum}.
844 @see: Method L{Fsum.__imod__}.
845 '''
846 f = self._copy_2(self.__mod__)
847 return f._fdivmod2(other, _mod_op_).mod
849 def __mul__(self, other):
850 '''Return C{B{self} * B{other}} as an L{Fsum}.
852 @see: Method L{Fsum.__imul__}.
853 '''
854 f = self._copy_2(self.__mul__)
855 return f._fmul(other, _mul_op_)
857 def __ne__(self, other):
858 '''Return C{(B{self} != B{other})}, see C{__eq__}.
859 '''
860 return self._cmp_0(other, _ne_op_) != 0
862 def __neg__(self):
863 '''Return C{copy(B{self})}, I{negated}.
864 '''
865 f = self._copy_2(self.__neg__)
866 return f._fset(self._neg)
868 def __pos__(self):
869 '''Return this instance I{as-is}, like C{float.__pos__()}.
870 '''
871 return self if _pos_self else self._copy_2(self.__pos__)
873 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
874 '''Return C{B{self}**B{other}} as an L{Fsum}.
876 @see: Method L{Fsum.__ipow__}.
877 '''
878 f = self._copy_2(self.__pow__)
879 return f._fpow(other, _pow_op_, *mod)
881 def __radd__(self, other):
882 '''Return C{B{other} + B{self}} as an L{Fsum}.
884 @see: Method L{Fsum.__iadd__}.
885 '''
886 f = self._copy_2r(other, self.__radd__)
887 return f._fadd(self)
889 def __rdivmod__(self, other):
890 '''Return C{divmod(B{other}, B{self})} as 2-tuple
891 C{(quotient, remainder)}.
893 @see: Method L{Fsum.__divmod__}.
894 '''
895 f = self._copy_2r(other, self.__rdivmod__)
896 return f._fdivmod2(self, _divmod_op_)
898# turned off, called by _deepcopy and _copy
899# def __reduce__(self): # Python 3.8+
900# ''' Pickle, like std C{fractions.Fraction}, see U{__reduce__
901# <https://docs.Python.org/3/library/pickle.html#object.__reduce__>}
902# '''
903# dict_ = self._Fsum_as().__dict__ # no __setstate__
904# return (self.__class__, self.partials, dict_)
906# def __repr__(self):
907# '''Return the default C{repr(this)}.
908# '''
909# return self.toRepr(lenc=True)
911 def __rfloordiv__(self, other):
912 '''Return C{B{other} // B{self}} as an L{Fsum}.
914 @see: Method L{Fsum.__ifloordiv__}.
915 '''
916 f = self._copy_2r(other, self.__rfloordiv__)
917 return f._floordiv(self, _floordiv_op_)
919 def __rmatmul__(self, other): # PYCHOK no coveS
920 '''Not implemented.'''
921 return _NotImplemented(self, other)
923 def __rmod__(self, other):
924 '''Return C{B{other} % B{self}} as an L{Fsum}.
926 @see: Method L{Fsum.__imod__}.
927 '''
928 f = self._copy_2r(other, self.__rmod__)
929 return f._fdivmod2(self, _mod_op_).mod
931 def __rmul__(self, other):
932 '''Return C{B{other} * B{self}} as an L{Fsum}.
934 @see: Method L{Fsum.__imul__}.
935 '''
936 f = self._copy_2r(other, self.__rmul__)
937 return f._fmul(self, _mul_op_)
939 def __round__(self, *ndigits): # PYCHOK Python 3+
940 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
942 @arg ndigits: Optional number of digits (C{int}).
943 '''
944 f = self._copy_2(self.__round__)
945 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
946 return f._fset(round(float(self), *ndigits)) # can be C{int}
948 def __rpow__(self, other, *mod):
949 '''Return C{B{other}**B{self}} as an L{Fsum}.
951 @see: Method L{Fsum.__ipow__}.
952 '''
953 f = self._copy_2r(other, self.__rpow__)
954 return f._fpow(self, _pow_op_, *mod)
956 def __rsub__(self, other):
957 '''Return C{B{other} - B{self}} as L{Fsum}.
959 @see: Method L{Fsum.__isub__}.
960 '''
961 f = self._copy_2r(other, self.__rsub__)
962 return f._fsub(self, _sub_op_)
964 def __rtruediv__(self, other, **raiser_RESIDUAL):
965 '''Return C{B{other} / B{self}} as an L{Fsum}.
967 @see: Method L{Fsum.__itruediv__}.
968 '''
969 f = self._copy_2r(other, self.__rtruediv__)
970 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
972 def __str__(self):
973 '''Return the default C{str(self)}.
974 '''
975 return self.toStr(lenc=True)
977 def __sub__(self, other):
978 '''Return C{B{self} - B{other}} as an L{Fsum}.
980 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
982 @return: The difference (L{Fsum}).
984 @see: Method L{Fsum.__isub__}.
985 '''
986 f = self._copy_2(self.__sub__)
987 return f._fsub(other, _sub_op_)
989 def __truediv__(self, other, **raiser_RESIDUAL):
990 '''Return C{B{self} / B{other}} as an L{Fsum}.
992 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
993 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
994 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
995 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
997 @return: The quotient (L{Fsum}).
999 @raise ResidualError: Non-zero, significant residual or invalid
1000 B{C{RESIDUAL}}.
1002 @see: Method L{Fsum.__itruediv__}.
1003 '''
1004 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
1006 __trunc__ = __int__
1008 if _MODS.sys_version_info2 < (3, 0): # PYCHOK no cover
1009 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
1010 __div__ = __truediv__
1011 __idiv__ = __itruediv__
1012 __long__ = __int__
1013 __nonzero__ = __bool__
1014 __rdiv__ = __rtruediv__
1016 def as_integer_ratio(self):
1017 '''Return this instance as the ratio of 2 integers.
1019 @return: 2-Tuple C{(numerator, denominator)} both C{int} with
1020 C{numerator} signed and C{denominator} non-zero and
1021 positive. The C{numerator} is I{non-finite} if this
1022 instance is.
1024 @see: Method L{Fsum.fint2} and C{float.as_integer_ratio} in
1025 Python 2.7+.
1026 '''
1027 n, r = self._fint2
1028 if r:
1029 i, d = float(r).as_integer_ratio()
1030 n, d = _n_d2(n * d + i, d)
1031 else: # PYCHOK no cover
1032 d = 1
1033 return n, d
1035 @property_RO
1036 def as_iscalar(self):
1037 '''Get this instance I{as-is} (L{Fsum} with C{non-zero residual},
1038 C{scalar} or I{non-finite}).
1039 '''
1040 s, r = self._nfprs2
1041 return self if r else s
1043 @property_RO
1044 def ceil(self):
1045 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
1046 C{float} in Python 2-).
1048 @note: This C{ceil} takes the C{residual} into account.
1050 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
1051 L{Fsum.imag} and L{Fsum.real}.
1052 '''
1053 s, r = self._fprs2
1054 c = _ceil(s) + int(r) - 1
1055 while r > (c - s): # (s + r) > c
1056 c += 1
1057 return c # _ceil(self._n_d)
1059 cmp = __cmp__
1061 def _cmp_0(self, other, op):
1062 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
1063 '''
1064 if _isFsum_2Tuple(other):
1065 s = self._ps_1sum(*other._ps)
1066 elif self._scalar(other, op):
1067 s = self._ps_1sum(other)
1068 else:
1069 s = self.signOf() # res=True
1070 return s
1072 def copy(self, deep=False, **name):
1073 '''Copy this instance, C{shallow} or B{C{deep}}.
1075 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}).
1077 @return: The copy (L{Fsum}).
1078 '''
1079 n = _name__(name, name__=self.copy)
1080 f = _Named.copy(self, deep=deep, name=n)
1081 if f._ps is self._ps:
1082 f._ps = list(self._ps) # separate list
1083 if not deep:
1084 f._n = 1
1085 # assert f._f2product == self._f2product
1086 # assert f._Fsum is f
1087 # assert f._isfine is self._isfine
1088 # assert f._RESIDUAL is self._RESIDUAL
1089 return f
1091 def _copy_2(self, which, name=NN):
1092 '''(INTERNAL) Copy for I{dyadic} operators.
1093 '''
1094 n = name or which.__name__ # _DUNDER_nameof
1095 # NOT .classof due to .Fdot(a, *b) args, etc.
1096 f = _Named.copy(self, deep=False, name=n)
1097 f._ps = list(self._ps) # separate list
1098 # assert f._n == self._n
1099 # assert f._f2product == self._f2product
1100 # assert f._Fsum is f
1101 # assert f._isfine is self._isfine
1102 # assert f._RESIDUAL is self._RESIDUAL
1103 return f
1105 def _copy_2r(self, other, which):
1106 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
1107 '''
1108 return other._copy_2(which) if _isFsum(other) else \
1109 self._copy_2(which)._fset(other)
1111 divmod = __divmod__
1113 def _Error(self, op, other, Error, **txt_cause):
1114 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
1115 '''
1116 # self.as_iscalar causes RecursionError for ._fprs2 errors
1117 s = _Psum(self._ps, nonfinites=True, name=self.name)
1118 return Error(_SPACE_(s.as_iscalar, op, other), **txt_cause)
1120 def _ErrorX(self, X, op, other, *mod):
1121 '''(INTERNAL) Format the caught exception C{X}.
1122 '''
1123 E, t = _xError2(X)
1124 if mod:
1125 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
1126 return self._Error(op, other, E, txt=t, cause=X)
1128 def _ErrorXs(self, X, xs, **kwds): # in .fmath
1129 '''(INTERNAL) Format the caught exception C{X}.
1130 '''
1131 E, t = _xError2(X)
1132 u = unstr(self.named3, *xs, _ELLIPSIS=4, **kwds)
1133 return E(u, txt=t, cause=X)
1135 def _facc(self, xs, up=True, **_X_x_origin):
1136 '''(INTERNAL) Accumulate more C{scalar}s or L{Fsum}s.
1137 '''
1138 if xs:
1139 kwds = self._isfine
1140 if _X_x_origin:
1141 kwds = _xkwds(_X_x_origin, **kwds)
1142 fs = _xs(xs, **kwds) # PYCHOK yield
1143 ps = self._ps
1144 ps[:] = self._ps_acc(list(ps), fs, up=up)
1145# if len(ps) > 16:
1146# _ = _psum(ps, **self._isfine)
1147 return self
1149 def _facc_args(self, xs, **up):
1150 '''(INTERNAL) Accumulate 0, 1 or more C{xs}, all positional
1151 arguments in the caller of this method.
1152 '''
1153 return self._fadd(xs[0], **up) if len(xs) == 1 else \
1154 self._facc(xs, **up) # origin=1?
1156 def _facc_dot(self, n, xs, ys, **kwds): # in .fmath
1157 '''(INTERNAL) Accumulate C{fdot(B{xs}, *B{ys})}.
1158 '''
1159 if n > 0:
1160 _f = Fsum(**kwds)
1161 self._facc(_f(x).fmul(y) for x, y in zip(xs, ys)) # PYCHOK attr?
1162 return self
1164 def _facc_neg(self, xs, **up_origin):
1165 '''(INTERNAL) Accumulate more C{xs}, negated.
1166 '''
1167 def _N(X):
1168 return X._ps_neg
1170 def _n(x):
1171 return -float(x)
1173 return self._facc(xs, _X=_N, _x=_n, **up_origin)
1175 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
1176 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
1177 '''
1178 def _Pow4(p):
1179 r = 0
1180 if _isFsum_2Tuple(p):
1181 s, r = p._fprs2
1182 if r:
1183 m = Fsum._pow
1184 else: # scalar
1185 return _Pow4(s)
1186 elif isint(p, both=True) and int(p) >= 0:
1187 p = s = int(p)
1188 m = Fsum._pow_int
1189 else:
1190 p = s = _2float(power=p, **self._isfine)
1191 m = Fsum._pow_scalar
1192 return m, p, s, r
1194 _Pow, p, s, r = _Pow4(power)
1195 if p: # and xs:
1196 op = which.__name__
1197 _FsT = _Fsum_2Tuple_types
1198 _pow = self._pow_2_3
1200 def _P(X):
1201 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
1202 return f._ps if isinstance(f, _FsT) else (f,)
1204 def _p(x):
1205 x = float(x)
1206 f = _pow(x, s, power, op, **raiser_RESIDUAL)
1207 if f and r:
1208 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
1209 return f
1211 f = self._facc(xs, _X=_P, _x=_p) # origin=1?
1212 else:
1213 f = self._facc_scalar_(float(len(xs))) # x**0 == 1
1214 return f
1216 def _facc_scalar(self, xs, **up):
1217 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}.
1218 '''
1219 if xs:
1220 ps = self._ps
1221 ps[:] = self._ps_acc(list(ps), xs, **up)
1222 return self
1224 def _facc_scalar_(self, *xs, **up):
1225 '''(INTERNAL) Accumulate all positional C{xs}, each C{scalar}.
1226 '''
1227 return self._facc_scalar(xs, **up)
1229 def _facc_scalarf(self, xs, up=True, **origin_which):
1230 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}, an L{Fsum} or
1231 L{Fsum2Tuple}, like function C{_xsum}.
1232 '''
1233 _C = self.__class__
1234 fs = _xs(xs, **_x_isfine(self.nonfinitesOK, _Cdot=_C,
1235 **origin_which)) # PYCHOK yield
1236 return self._facc_scalar(fs, up=up)
1238# def _facc_up(self, up=True):
1239# '''(INTERNAL) Update the C{partials}, by removing
1240# and re-accumulating the final C{partial}.
1241# '''
1242# ps = self._ps
1243# while len(ps) > 1:
1244# p = ps.pop()
1245# if p:
1246# n = self._n
1247# _ = self._ps_acc(ps, (p,), up=False)
1248# self._n = n
1249# break
1250# return self._update() if up else self
1252 def fadd(self, xs=()):
1253 '''Add an iterable's items to this instance.
1255 @arg xs: Iterable of items to add (each C{scalar},
1256 an L{Fsum} or L{Fsum2Tuple}).
1258 @return: This instance (L{Fsum}).
1260 @raise OverflowError: Partial C{2sum} overflow.
1262 @raise TypeError: An invalid B{C{xs}} item.
1264 @raise ValueError: Invalid or I{non-finite} B{C{xs}} value.
1265 '''
1266 if _isFsum_2Tuple(xs):
1267 self._facc_scalar(xs._ps)
1268 elif isscalar(xs): # for backward compatibility # PYCHOK no cover
1269 x = _2float(x=xs, **self._isfine)
1270 self._facc_scalar_(x)
1271 elif xs: # _xiterable(xs)
1272 self._facc(xs)
1273 return self
1275 def fadd_(self, *xs):
1276 '''Add all positional items to this instance.
1278 @arg xs: Values to add (each C{scalar}, an L{Fsum}
1279 or L{Fsum2Tuple}), all positional.
1281 @see: Method L{Fsum.fadd} for further details.
1282 '''
1283 return self._facc_args(xs)
1285 def _fadd(self, other, op=_add_op_, **up):
1286 '''(INTERNAL) Apply C{B{self} += B{other}}.
1287 '''
1288 if _isFsum_2Tuple(other):
1289 self._facc_scalar(other._ps, **up)
1290 elif self._scalar(other, op):
1291 self._facc_scalar_(other, **up)
1292 return self
1294 fcopy = copy # for backward compatibility
1295 fdiv = __itruediv__
1296 fdivmod = __divmod__
1298 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1299 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1300 '''
1301 # result mostly follows CPython function U{float_divmod
1302 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1303 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1304 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1305 if q: # == float // other == floor(float / other)
1306 self -= self._Fsum_as(q) * other # NOT other * q!
1308 s = signOf(other) # make signOf(self) == signOf(other)
1309 if s and self.signOf() == -s: # PYCHOK no cover
1310 self += other
1311 q -= 1
1312# t = self.signOf()
1313# if t and t != s:
1314# raise self._Error(op, other, _AssertionError, txt__=signOf)
1315 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1317 def _fhorner(self, x, cs, where, incx=True): # in .fmath
1318 '''(INTERNAL) Add an L{Fhorner} evaluation of polynomial
1319 C{sum(c * B{x}**i for i, c in _e(cs))} where C{_e =
1320 enumerate if B{incx} else _enumereverse}.
1321 '''
1322 # assert _xiterablen(cs)
1323 try:
1324 n = len(cs)
1325 if n > 1 and _2finite(x, **self._isfine):
1326 H = self._Fsum_as(name__=self._fhorner)
1327 _m = H._mul_Fsum if _isFsum_2Tuple(x) else \
1328 H._mul_scalar
1329 for c in (reversed(cs) if incx else cs):
1330 H._fset(_m(x, _mul_op_), up=False)
1331 H._fadd(c, up=False)
1332 else: # x == 0
1333 H = cs[0] if n else 0
1334 self._fadd(H)
1335 except Exception as X:
1336 t = unstr(where, x, *cs, _ELLIPSIS=4, incx=incx)
1337 raise self._ErrorX(X, _add_op_, t)
1338 return self
1340 def _finite(self, other, op=None):
1341 '''(INTERNAL) Return B{C{other}} if C{finite}.
1342 '''
1343 if _isOK_or_finite(other, **self._isfine):
1344 return other
1345 E = _NonfiniteError(other)
1346 raise self._Error(op, other, E, txt=_not_finite_)
1348 def fint(self, name=NN, **raiser_RESIDUAL):
1349 '''Return this instance' current running sum as C{integer}.
1351 @kwarg name: Optional, overriding C{B{name}="fint"} (C{str}).
1352 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1353 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1354 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1356 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1357 with a zero or insignificant I{integer} residual.
1359 @raise ResidualError: Non-zero, significant residual or invalid
1360 B{C{RESIDUAL}}.
1362 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1363 '''
1364 i, r = self._fint2
1365 if r:
1366 R = self._raiser(r, i, **raiser_RESIDUAL)
1367 if R:
1368 t = _stresidual(_integer_, r, **R)
1369 raise ResidualError(_integer_, i, txt=t)
1370 return self._Fsum_as(i, name=_name__(name, name__=self.fint))
1372 def fint2(self, **name):
1373 '''Return this instance' current running sum as C{int} and the
1374 I{integer} residual.
1376 @kwarg name: Optional name (C{str}).
1378 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1379 an C{int} and I{integer} C{residual} a C{float} or
1380 C{INT0} if the C{fsum} is considered to be I{exact}.
1381 The C{fsum} is I{non-finite} if this instance is.
1382 '''
1383 return Fsum2Tuple(*self._fint2, **name)
1385 @Property
1386 def _fint2(self): # see ._fset
1387 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1388 '''
1389 s, r = self._nfprs2
1390 if _isfinite(s):
1391 i = int(s)
1392 r = (self._ps_1sum(i) if len(self._ps) > 1 else
1393 float(s - i)) or INT0
1394 else: # INF, NAN, NINF
1395 i = float(s)
1396# r = _NONFINITEr
1397 return i, r # Fsum2Tuple?
1399 @_fint2.setter_ # PYCHOK setter_UNDERscore!
1400 def _fint2(self, s): # in _fset
1401 '''(INTERNAL) Replace the C{_fint2} value.
1402 '''
1403 if _isfinite(s):
1404 i = int(s)
1405 r = (s - i) or INT0
1406 else: # INF, NAN, NINF
1407 i = float(s)
1408 r = _NONFINITEr
1409 return i, r # like _fint2.getter
1411 @deprecated_property_RO
1412 def float_int(self): # PYCHOK no cover
1413 '''DEPRECATED, use method C{Fsum.int_float}.'''
1414 return self.int_float() # raiser=False
1416 @property_RO
1417 def floor(self):
1418 '''Get this instance' C{floor} (C{int} in Python 3+, but
1419 C{float} in Python 2-).
1421 @note: This C{floor} takes the C{residual} into account.
1423 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1424 L{Fsum.imag} and L{Fsum.real}.
1425 '''
1426 s, r = self._fprs2
1427 f = _floor(s) + _floor(r) + 1
1428 while (f - s) > r: # f > (s + r)
1429 f -= 1
1430 return f # _floor(self._n_d)
1432# ffloordiv = __ifloordiv__ # for naming consistency?
1433# floordiv = __floordiv__ # for naming consistency?
1435 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1436 '''Apply C{B{self} //= B{other}}.
1437 '''
1438 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1439 return self._fset(q.floor) # floor(q)
1441 def fma(self, other1, other2, **nonfinites): # in .fmath.fma
1442 '''Fused-multiply-add C{self *= B{other1}; self += B{other2}}.
1444 @arg other1: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1445 @arg other2: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1446 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{False}, to
1447 override L{nonfinites<Fsum.nonfinites>} and
1448 L{nonfiniterrors} default (C{bool}).
1449 '''
1450 op = self.fma.__name__
1451 _fs = self._ps_other
1452 try:
1453 s, r = self._fprs2
1454 if r:
1455 f = self._f2mul(self.fma, (other1,), **nonfinites)
1456 f += other2
1457 elif _residue(other1) or _residue(other2):
1458 fs = _2split3s(_fs(op, other1))
1459 fs = _2products(s, fs, *_fs(op, other2))
1460 f = _Psum(self._ps_acc([], fs, up=False), name=op)
1461 else:
1462 f = _fma(s, other1, other2)
1463 f = _2finite(f, **self._isfine)
1464 except TypeError as X:
1465 raise self._ErrorX(X, op, (other1, other2))
1466 except (OverflowError, ValueError) as X: # from math.fma
1467 f = self._mul_reduce(s, other1) # INF, NAN, NINF
1468 f += sum(_fs(op, other2))
1469 f = self._nonfiniteX(X, op, f, **nonfinites)
1470 return self._fset(f)
1472 fmul = __imul__
1474 def _fmul(self, other, op):
1475 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1476 '''
1477 if _isFsum_2Tuple(other):
1478 if len(self._ps) != 1:
1479 f = self._mul_Fsum(other, op)
1480 elif len(other._ps) != 1: # and len(self._ps) == 1
1481 f = self._ps_mul(op, *other._ps) if other._ps else _0_0
1482 elif self._f2product: # len(other._ps) == 1
1483 f = self._mul_scalar(other._ps[0], op)
1484 else: # len(other._ps) == len(self._ps) == 1
1485 f = self._finite(self._ps[0] * other._ps[0], op=op)
1486 else:
1487 s = self._scalar(other, op)
1488 f = self._mul_scalar(s, op)
1489 return self._fset(f) # n=len(self) + 1
1491 @deprecated_method
1492 def f2mul(self, *others, **raiser):
1493 '''DEPRECATED on 2024.09.13, use method L{f2mul_<Fsum.f2mul_>}.'''
1494 return self._fset(self.f2mul_(others, **raiser))
1496 def f2mul_(self, *others, **f2product_nonfinites): # in .fmath.f2mul
1497 '''Return C{B{self} * B{other} * B{other} ...} for all B{C{others}} using cascaded,
1498 accurate multiplication like with L{f2product<Fsum.f2product>}C{(B{True})}.
1500 @arg others: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
1501 positional.
1502 @kwarg f2product_nonfinites: Use C{B{f2product=False}} to override the default
1503 C{True} and C{B{nonfinites}=True} or C{False}, to override
1504 settings L{nonfinites<Fsum.nonfinites>} and L{nonfiniterrors}.
1506 @return: The cascaded I{TwoProduct} (L{Fsum} or C{float}).
1508 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
1509 '''
1510 return self._f2mul(self.f2mul_, others, **f2product_nonfinites)
1512 def _f2mul(self, where, others, f2product=True, **nonfinites_raiser):
1513 '''(INTERNAL) See methods C{fma} and C{f2mul_}.
1514 '''
1515 f = _Psum(self._ps, f2product=f2product, name=where.__name__)
1516 if others and f:
1517 if f.f2product():
1518 def _pfs(f, ps):
1519 return _2products(f, _2split3s(ps))
1520 else:
1521 def _pfs(f, ps): # PYCHOK redef
1522 return (f * p for p in ps)
1524 op, ps = where.__name__, f._ps
1525 try: # as if self.f2product(True)
1526 for other in others: # to pinpoint errors
1527 for p in self._ps_other(op, other):
1528 ps[:] = f._ps_acc([], _pfs(p, ps), update=False)
1529 f._update()
1530 except TypeError as X:
1531 raise self._ErrorX(X, op, other)
1532 except (OverflowError, ValueError) as X:
1533 r = self._mul_reduce(sum(ps), other) # INF, NAN, NINF
1534 r = self._nonfiniteX(X, op, r, **nonfinites_raiser)
1535 f._fset(r)
1536 return f
1538 def fover(self, over, **raiser_RESIDUAL):
1539 '''Apply C{B{self} /= B{over}} and summate.
1541 @arg over: An L{Fsum} or C{scalar} denominator.
1542 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1543 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1544 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1546 @return: Precision running sum (C{float}).
1548 @raise ResidualError: Non-zero, significant residual or invalid
1549 B{C{RESIDUAL}}.
1551 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1552 '''
1553 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1555 fpow = __ipow__
1557 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1558 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1559 '''
1560 if mod:
1561 if mod[0] is not None: # == 3-arg C{pow}
1562 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1563 elif self.is_integer():
1564 # return an exact C{int} for C{int}**C{int}
1565 i, _ = self._fint2 # assert _ == 0
1566 x, r = _2tuple2(other) # C{int}, C{float} or other
1567 f = self._Fsum_as(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1568 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1569 else: # mod[0] is None, power(self, other)
1570 f = self._pow(other, other, op, **raiser_RESIDUAL)
1571 else: # pow(self, other)
1572 f = self._pow(other, other, op, **raiser_RESIDUAL)
1573 return self._fset(f) # n=max(len(self), 1)
1575 def f2product(self, *two):
1576 '''Get and set accurate I{TwoProduct} multiplication for this
1577 L{Fsum}, overriding the L{f2product} default.
1579 @arg two: If omitted, leave the override unchanged, if C{True},
1580 turn I{TwoProduct} on, if C{False} off, if C{None}e
1581 remove th override (C{bool} or C{None}).
1583 @return: The previous setting (C{bool} or C{None} if not set).
1585 @see: Function L{f2product<fsums.f2product>}.
1587 @note: Use C{f.f2product() or f2product()} to determine whether
1588 multiplication is accurate for L{Fsum} C{f}.
1589 '''
1590 if two: # delattrof(self, _f2product=None)
1591 t = _xkwds_pop(self.__dict__, _f2product=None)
1592 if two[0] is not None:
1593 self._f2product = bool(two[0])
1594 else: # getattrof(self, _f2product=None)
1595 t = _xkwds_get(self.__dict__, _f2product=None)
1596 return t
1598 @Property
1599 def _fprs(self):
1600 '''(INTERNAL) Get and cache this instance' precision
1601 running sum (C{float} or C{int}), ignoring C{residual}.
1603 @note: The precision running C{fsum} after a C{//=} or
1604 C{//} C{floor} division is C{int} in Python 3+.
1605 '''
1606 s, _ = self._fprs2
1607 return s # ._fprs2.fsum
1609 @_fprs.setter_ # PYCHOK setter_UNDERscore!
1610 def _fprs(self, s):
1611 '''(INTERNAL) Replace the C{_fprs} value.
1612 '''
1613 return s
1615 @Property
1616 def _fprs2(self):
1617 '''(INTERNAL) Get and cache this instance' precision
1618 running sum and residual (L{Fsum2Tuple}).
1619 '''
1620 ps = self._ps
1621 n = len(ps)
1622 try:
1623 if n > 2:
1624 s = _psum(ps, **self._isfine)
1625 if not _isfinite(s):
1626 ps[:] = s, # collapse ps
1627 return Fsum2Tuple(s, _NONFINITEr)
1628 n = len(ps)
1629# Fsum._ps_max = max(Fsum._ps_max, n)
1630 if n > 2:
1631 r = self._ps_1sum(s)
1632 return Fsum2Tuple(*_s_r2(s, r))
1633 if n > 1: # len(ps) == 2
1634 s, r = _s_r2(*_2sum(*ps, **self._isfine))
1635 ps[:] = (r, s) if r else (s,)
1636 elif ps: # len(ps) == 1
1637 s = ps[0]
1638 r = INT0 if _isfinite(s) else _NONFINITEr
1639 else: # len(ps) == 0
1640 s = _0_0
1641 r = INT0 if _isfinite(s) else _NONFINITEr
1642 ps[:] = s,
1643 except (OverflowError, ValueError) as X:
1644 op = _fset_op_ # INF, NAN, NINF
1645 ps[:] = sum(ps), # collapse ps
1646 s = self._nonfiniteX(X, op, ps[0])
1647 r = _NONFINITEr
1648 # assert self._ps is ps
1649 return Fsum2Tuple(s, r)
1651 @_fprs2.setter_ # PYCHOK setter_UNDERscore!
1652 def _fprs2(self, s_r):
1653 '''(INTERNAL) Replace the C{_fprs2} value.
1654 '''
1655 return Fsum2Tuple(s_r)
1657 def fset_(self, *xs):
1658 '''Apply C{B{self}.partials = Fsum(*B{xs}).partials}.
1660 @arg xs: Optional, new values (each C{scalar} or an L{Fsum}
1661 or L{Fsum2Tuple} instance), all positional.
1663 @return: This instance, replaced (C{Fsum}).
1665 @see: Method L{Fsum.fadd} for further details.
1666 '''
1667 f = (xs[0] if xs else _0_0) if len(xs) < 2 else \
1668 Fsum(*xs, nonfinites=self.nonfinites()) # self._Fsum_as(*xs)
1669 return self._fset(f, op=_fset_op_)
1671 def _fset(self, other, n=0, up=True, **op):
1672 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1673 '''
1674 if other is self:
1675 pass # from ._fmul, ._ftruediv and ._pow_0_1
1676 elif _isFsum_2Tuple(other):
1677 if op: # and not self.nonfinitesOK:
1678 self._finite(other._fprs, **op)
1679 self._ps[:] = other._ps
1680 self._n = n or other._n
1681 if up: # use or zap the C{Property_RO} values
1682 Fsum._fint2._update_from(self, other)
1683 Fsum._fprs ._update_from(self, other)
1684 Fsum._fprs2._update_from(self, other)
1685 elif isscalar(other):
1686 s = float(self._finite(other, **op)) if op else other
1687 self._ps[:] = s,
1688 self._n = n or 1
1689 if up: # Property _fint2, _fprs and _fprs2 all have
1690 # @.setter_underscore and NOT @.setter because the
1691 # latter's _fset zaps the value set by @.setter
1692 self._fint2 = s
1693 self._fprs = s
1694 self._fprs2 = s, INT0
1695 # assert self._fprs is s
1696 else:
1697 op = _xkwds_get1(op, op=_fset_op_)
1698 raise self._Error(op, other, _TypeError)
1699 return self
1701 def fsub(self, xs=()):
1702 '''Subtract an iterable's items from this instance.
1704 @see: Method L{Fsum.fadd} for further details.
1705 '''
1706 return self._facc_neg(xs)
1708 def fsub_(self, *xs):
1709 '''Subtract all positional items from this instance.
1711 @see: Method L{Fsum.fadd_} for further details.
1712 '''
1713 return self._fsub(xs[0], _sub_op_) if len(xs) == 1 else \
1714 self._facc_neg(xs) # origin=1?
1716 def _fsub(self, other, op):
1717 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1718 '''
1719 if _isFsum_2Tuple(other):
1720 if other is self: # or other._fprs2 == self._fprs2:
1721 self._fset(_0_0, n=len(self) * 2)
1722 elif other._ps:
1723 self._facc_scalar(other._ps_neg)
1724 elif self._scalar(other, op):
1725 self._facc_scalar_(-other)
1726 return self
1728 def fsum(self, xs=()):
1729 '''Add an iterable's items, summate and return the current
1730 precision running sum.
1732 @arg xs: Iterable of items to add (each item C{scalar},
1733 an L{Fsum} or L{Fsum2Tuple}).
1735 @return: Precision running sum (C{float} or C{int}).
1737 @see: Method L{Fsum.fadd}.
1739 @note: Accumulation can continue after summation.
1740 '''
1741 return self._facc(xs)._fprs
1743 def fsum_(self, *xs):
1744 '''Add any positional items, summate and return the current
1745 precision running sum.
1747 @arg xs: Items to add (each C{scalar}, an L{Fsum} or
1748 L{Fsum2Tuple}), all positional.
1750 @return: Precision running sum (C{float} or C{int}).
1752 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1753 '''
1754 return self._facc_args(xs)._fprs
1756 def Fsum_(self, *xs, **name):
1757 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1759 @kwarg name: Optional name (C{str}).
1761 @return: Copy of this updated instance (L{Fsum}).
1762 '''
1763 return self._facc_args(xs)._copy_2(self.Fsum_, **name)
1765 def Fsum2Tuple_(self, *xs, **name):
1766 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1768 @kwarg name: Optional name (C{str}).
1770 @return: Precision running sum (L{Fsum2Tuple}).
1771 '''
1772 return Fsum2Tuple(self._facc_args(xs)._nfprs2, **name)
1774 @property_RO
1775 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, in .fstats
1776 return self # NOT @Property_RO, see .copy and ._copy_2
1778 def _Fsum_as(self, *xs, **name_f2product_nonfinites_RESIDUAL):
1779 '''(INTERNAL) Return an C{Fsum} with this C{Fsum}'s C{.f2product},
1780 C{.nonfinites} and C{.RESIDUAL} setting, optionally
1781 overridden with C{name_f2product_nonfinites_RESIDUAL} and
1782 with any C{xs} accumulated.
1783 '''
1784 kwds = _xkwds_not(None, Fsum._RESIDUAL, f2product =self.f2product(),
1785 nonfinites=self.nonfinites(),
1786 RESIDUAL =self.RESIDUAL())
1787 if name_f2product_nonfinites_RESIDUAL: # overwrites
1788 kwds.update(name_f2product_nonfinites_RESIDUAL)
1789 f = Fsum(**kwds)
1790 # assert all(v == self.__dict__[n] for n, v in f.__dict__.items())
1791 return (f._facc(xs, up=False) if len(xs) > 1 else
1792 f._fset(xs[0], op=_fset_op_)) if xs else f
1794 def fsum2(self, xs=(), **name):
1795 '''Add an iterable's items, summate and return the
1796 current precision running sum I{and} the C{residual}.
1798 @arg xs: Iterable of items to add (each item C{scalar},
1799 an L{Fsum} or L{Fsum2Tuple}).
1800 @kwarg name: Optional C{B{name}=NN} (C{str}).
1802 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1803 current precision running sum and C{residual}, the
1804 (precision) sum of the remaining C{partials}. The
1805 C{residual is INT0} if the C{fsum} is considered
1806 to be I{exact}.
1808 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1809 '''
1810 t = self._facc(xs)._fprs2
1811 return t.dup(name=name) if name else t
1813 def fsum2_(self, *xs):
1814 '''Add any positional items, summate and return the current
1815 precision running sum and the I{differential}.
1817 @arg xs: Values to add (each C{scalar}, an L{Fsum} or
1818 L{Fsum2Tuple}), all positional.
1820 @return: 2Tuple C{(fsum, delta)} with the current, precision
1821 running C{fsum} like method L{Fsum.fsum} and C{delta},
1822 the difference with previous running C{fsum}, C{float}.
1824 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1825 '''
1826 return self._fsum2(xs, self._facc_args)
1828 def _fsum2(self, xs, _facc, **facc_kwds):
1829 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1830 '''
1831 p, q = self._fprs2
1832 if xs:
1833 s, r = _facc(xs, **facc_kwds)._fprs2
1834 if _isfinite(s): # _fsum(_1primed((s, -p, r, -q))
1835 d, r = _2sum(s - p, r - q, _isfine=_isOK)
1836 r, _ = _s_r2(d, r)
1837 return s, (r if _isfinite(r) else _NONFINITEr)
1838 else:
1839 return p, _0_0
1841 def fsumf_(self, *xs):
1842 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}}, each I{known to be}
1843 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1844 '''
1845 return self._facc_scalarf(xs, which=self.fsumf_)._fprs # origin=1?
1847 def Fsumf_(self, *xs):
1848 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}}, each I{known to be}
1849 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1850 '''
1851 return self._facc_scalarf(xs, which=self.Fsumf_)._copy_2(self.Fsumf_) # origin=1?
1853 def fsum2f_(self, *xs):
1854 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}}, each I{known to be}
1855 C{scalar}, an L{Fsum} or L{Fsum2Tuple}.
1856 '''
1857 return self._fsum2(xs, self._facc_scalarf, which=self.fsum2f_) # origin=1?
1859# ftruediv = __itruediv__ # for naming consistency?
1861 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1862 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1863 '''
1864 n = _1_0
1865 if _isFsum_2Tuple(other):
1866 if other is self or self == other:
1867 return self._fset(n, n=len(self))
1868 d, r = other._fprs2
1869 if r:
1870 R = self._raiser(r, d, **raiser_RESIDUAL)
1871 if R:
1872 raise self._ResidualError(op, other, r, **R)
1873 d, n = other.as_integer_ratio()
1874 else:
1875 d = self._scalar(other, op)
1876 try:
1877 s = n / d
1878 except Exception as X:
1879 raise self._ErrorX(X, op, other)
1880 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1881 return self._fset(f)
1883 @property_RO
1884 def imag(self):
1885 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1887 @see: Property L{Fsum.real}.
1888 '''
1889 return _0_0
1891 def int_float(self, **raiser_RESIDUAL):
1892 '''Return this instance' current running sum as C{int} or C{float}.
1894 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1895 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1896 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1898 @return: This C{int} sum if this instance C{is_integer} and
1899 I{finite}, otherwise the C{float} sum if the residual
1900 is zero or not significant.
1902 @raise ResidualError: Non-zero, significant residual or invalid
1903 B{C{RESIDUAL}}.
1905 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.is_integer},
1906 L{Fsum.RESIDUAL} and property L{Fsum.as_iscalar}.
1907 '''
1908 s, r = self._fint2
1909 if r:
1910 s, r = self._fprs2
1911 if r: # PYCHOK no cover
1912 R = self._raiser(r, s, **raiser_RESIDUAL)
1913 if R:
1914 t = _stresidual(_non_zero_, r, **R)
1915 raise ResidualError(int_float=s, txt=t)
1916 s = float(s)
1917 return s
1919 def is_exact(self):
1920 '''Is this instance' running C{fsum} considered to be exact?
1921 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1922 '''
1923 return self.residual is INT0
1925 def is_finite(self): # in .constants
1926 '''Is this instance C{finite}? (C{bool}).
1928 @see: Function L{isfinite<pygeodesy.isfinite>}.
1929 '''
1930 return _isfinite(sum(self._ps)) # == sum(self)
1932 def is_integer(self):
1933 '''Is this instance' running sum C{integer}? (C{bool}).
1935 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1936 '''
1937 s, r = self._fint2
1938 return False if r else (_isfinite(s) and isint(s))
1940 def is_math_fma(self):
1941 '''Is accurate L{f2product} multiplication based on Python's C{math.fma}?
1943 @return: C{True} if accurate multiplication uses C{math.fma}, C{False}
1944 an C{fma} implementation as C{math.fma} or C{None}, a previous
1945 C{PyGeodesy} implementation.
1946 '''
1947 return (_2split3s is _passarg) or (False if _integer_ratio2 is None else None)
1949 def is_math_fsum(self):
1950 '''Are the summation functions L{fsum}, L{fsum_}, L{fsumf_}, L{fsum1},
1951 L{fsum1_} and L{fsum1f_} based on Python's C{math.fsum}?
1953 @return: C{True} if summation functions use C{math.fsum}, C{False}
1954 otherwise.
1955 '''
1956 return _sum is _fsum # _fsum.__module__ is fabs.__module__
1958 def is_scalar(self, **raiser_RESIDUAL):
1959 '''Is this instance' running sum C{scalar} with C{0} residual or with
1960 a residual I{ratio} not exceeding the RESIDUAL threshold?
1962 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1963 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1964 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1966 @return: C{True} if this instance' residual is C{0} or C{insignificant},
1967 i.e. its residual C{ratio} doesn't exceed the L{RESIDUAL
1968 <Fsum.RESIDUAL>} threshold (C{bool}).
1970 @raise ResidualError: Non-zero, significant residual or invalid
1971 B{C{RESIDUAL}}.
1973 @see: Methods L{Fsum.RESIDUAL} and L{Fsum.is_integer} and property
1974 L{Fsum.as_iscalar}.
1975 '''
1976 s, r = self._fprs2
1977 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1979 def _mul_Fsum(self, other, op):
1980 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1981 '''
1982 # assert _isFsum_2Tuple(other)
1983 if self._ps and other._ps:
1984 try:
1985 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
1986 except Exception as X:
1987 raise self._ErrorX(X, op, other)
1988 else:
1989 f = _0_0
1990 return f
1992 def _mul_reduce(self, *others):
1993 '''(INTERNAL) Like fmath.fprod for I{non-finite} C{other}s.
1994 '''
1995 r = _1_0
1996 for f in others:
1997 r *= sum(f._ps) if _isFsum_2Tuple(f) else float(f)
1998 return r
2000 def _mul_scalar(self, factor, op):
2001 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
2002 '''
2003 # assert isscalar(factor)
2004 if self._ps and self._finite(factor, op=op):
2005 f = self if factor == _1_0 else (
2006 self._neg if factor == _N_1_0 else
2007 self._ps_mul(op, factor).as_iscalar)
2008 else:
2009 f = _0_0
2010 return f
2012# @property_RO
2013# def _n_d(self):
2014# n, d = self.as_integer_ratio()
2015# return n / d
2017 @property_RO
2018 def _neg(self):
2019 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
2020 '''
2021 return _Psum(self._ps_neg) if self._ps else NEG0
2023 @property_RO
2024 def _nfprs2(self):
2025 '''(INTERNAL) Handle I{non-finite} C{_fprs2}.
2026 '''
2027 try: # to handle nonfiniterrors, etc.
2028 t = self._fprs2
2029 except (OverflowError, ValueError):
2030 t = Fsum2Tuple(sum(self._ps), _NONFINITEr)
2031 return t
2033 def nonfinites(self, *OK):
2034 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan}
2035 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively
2036 C{ValueError} exceptions, overriding the L{nonfiniterrors} default.
2038 @arg OK: If omitted, leave the override unchanged, if C{True},
2039 I{non-finites} are C{OK}, if C{False} throw exceptions
2040 or if C{None} remove the override (C{bool} or C{None}).
2042 @return: The previous setting (C{bool} or C{None} if not set).
2044 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}.
2046 @note: Use property L{nonfinitesOK<Fsum.nonfinitesOK>} to determine
2047 whether I{non-finites} are C{OK} for this L{Fsum} and by the
2048 L{nonfiniterrors} default.
2049 '''
2050 _ks = Fsum._nonfinites_isfine_kwds
2051 if OK: # delattrof(self, _isfine=None)
2052 k = _xkwds_pop(self.__dict__, _isfine=None)
2053 if OK[0] is not None:
2054 self._isfine = _ks[bool(OK[0])]
2055 self._update()
2056 else: # getattrof(self, _isfine=None)
2057 k = _xkwds_get(self.__dict__, _isfine=None)
2058 # dict(map(reversed, _ks.items())).get(k, None)
2059 # raises a TypeError: unhashable type: 'dict'
2060 return True if k is _ks[True] else (
2061 False if k is _ks[False] else None)
2063 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK),
2064 False: dict(_isfine=_isfinite)}
2066 @property_RO
2067 def nonfinitesOK(self):
2068 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}).
2069 '''
2070# nf = self.nonfinites()
2071# if nf is None:
2072# nf = not nonfiniterrors()
2073 return _isOK_or_finite(INF, **self._isfine)
2075 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None):
2076 '''(INTERNAL) Handle a I{non-finite} exception.
2077 '''
2078 if nonfinites is None:
2079 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser)
2080 if not nonfinites:
2081 raise self._ErrorX(X, op, f)
2082 return f
2084 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL):
2085 '''(INTERNAL) Re/set options from keyword arguments.
2086 '''
2087 if f2product is not None:
2088 self.f2product(f2product)
2089 if nonfinites is not None:
2090 self.nonfinites(nonfinites)
2091 if name_RESIDUAL: # MUST be last
2092 n, kwds = _name2__(**name_RESIDUAL)
2093 if kwds:
2094 R = Fsum._RESIDUAL
2095 t = _threshold(R, **kwds)
2096 if t != R:
2097 self._RESIDUAL = t
2098 if n:
2099 self.name = n # self.rename(n)
2101 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over
2102 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
2103 '''
2104 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
2106 @property_RO
2107 def partials(self):
2108 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
2109 '''
2110 return tuple(self._ps)
2112 def pow(self, x, *mod, **raiser_RESIDUAL):
2113 '''Return C{B{self}**B{x}} as L{Fsum}.
2115 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2116 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
2117 C{pow(B{self}, B{other}, B{mod})} version.
2118 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
2119 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
2120 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2122 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
2123 result (L{Fsum}).
2125 @raise ResidualError: Non-zero, significant residual or invalid
2126 B{C{RESIDUAL}}.
2128 @note: If B{C{mod}} is given and C{None}, the result will be an
2129 C{integer} L{Fsum} provided this instance C{is_integer}
2130 or set to C{integer} by an L{Fsum.fint} call.
2132 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
2133 and L{Fsum.root}.
2134 '''
2135 f = self._copy_2(self.pow)
2136 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
2138 def _pow(self, other, unused, op, **raiser_RESIDUAL):
2139 '''Return C{B{self} ** B{other}}.
2140 '''
2141 if _isFsum_2Tuple(other):
2142 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
2143 elif self._scalar(other, op):
2144 x = self._finite(other, op=op)
2145 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2146 else:
2147 f = self._pow_0_1(0, other)
2148 return f
2150 def _pow_0_1(self, x, other):
2151 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
2152 '''
2153 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
2155 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
2156 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
2157 B{x}, int B{mod} or C{None})}, embellishing errors.
2158 '''
2160 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
2161 m = mod[0]
2162 # assert _isFsum_2Tuple(b)
2164 def _s(s, r):
2165 R = self._raiser(r, s, **raiser_RESIDUAL)
2166 if R:
2167 raise self._ResidualError(op, other, r, mod=m, **R)
2168 return s
2170 b = _s(*(b._fprs2 if m is None else b._fint2))
2171 x = _s(*_2tuple2(x))
2173 try:
2174 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
2175 s = pow(b, x, *mod)
2176 if iscomplex(s):
2177 # neg**frac == complex in Python 3+, but ValueError in 2-
2178 raise ValueError(_strcomplex(s, b, x, *mod))
2179 _ = _2finite(s, **self._isfine) # ignore float
2180 return s
2181 except Exception as X:
2182 raise self._ErrorX(X, op, other, *mod)
2184 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
2185 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}.
2186 '''
2187 # assert _isFsum_2Tuple(other)
2188 x, r = other._fprs2
2189 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2190 if f and r:
2191 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
2192 return f
2194 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
2195 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
2196 '''
2197 # assert isint(x) and x >= 0
2198 ps = self._ps
2199 if len(ps) > 1:
2200 _mul_Fsum = Fsum._mul_Fsum
2201 if x > 4:
2202 p = self
2203 f = self if (x & 1) else self._Fsum_as(_1_0)
2204 m = x >> 1 # // 2
2205 while m:
2206 p = _mul_Fsum(p, p, op) # p **= 2
2207 if (m & 1):
2208 f = _mul_Fsum(f, p, op) # f *= p
2209 m >>= 1 # //= 2
2210 elif x > 1: # self**2, 3, or 4
2211 f = _mul_Fsum(self, self, op)
2212 if x > 2: # self**3 or 4
2213 p = self if x < 4 else f
2214 f = _mul_Fsum(f, p, op)
2215 else: # self**1 or self**0 == 1 or _1_0
2216 f = self._pow_0_1(x, other)
2217 elif ps: # self._ps[0]**x
2218 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
2219 else: # PYCHOK no cover
2220 # 0**pos_int == 0, but 0**0 == 1
2221 f = 0 if x else 1
2222 return f
2224 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
2225 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
2226 '''
2227 s, r = self._fprs2
2228 if r:
2229 # assert s != 0
2230 if isint(x, both=True): # self**int
2231 x = int(x)
2232 y = abs(x)
2233 if y > 1:
2234 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
2235 if x > 0: # i.e. > 1
2236 return f # Fsum or scalar
2237 # assert x < 0 # i.e. < -1
2238 if _isFsum(f):
2239 s, r = f._fprs2
2240 if r:
2241 return self._1_Over(f, op, **raiser_RESIDUAL)
2242 else: # scalar
2243 s = f
2244 # use s**(-1) to get the CPython
2245 # float_pow error iff s is zero
2246 x = -1
2247 elif x < 0: # self**(-1)
2248 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self
2249 else: # self**1 or self**0
2250 return self._pow_0_1(x, other) # self, 1 or 1.0
2251 else: # self**fractional
2252 R = self._raiser(r, s, **raiser_RESIDUAL)
2253 if R:
2254 raise self._ResidualError(op, other, r, **R)
2255 n, d = self.as_integer_ratio()
2256 if abs(n) > abs(d):
2257 n, d, x = d, n, (-x)
2258 s = n / d
2259 # assert isscalar(s) and isscalar(x)
2260 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
2262 def _ps_acc(self, ps, xs, up=True, **unused):
2263 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.
2264 '''
2265 n = 0
2266 _2s = _2sum
2267 _fi = self._isfine
2268 for x in (tuple(xs) if xs is ps else xs):
2269 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine)
2270 if x:
2271 i = 0
2272 for p in ps:
2273 x, p = _2s(x, p, **_fi)
2274 if p:
2275 ps[i] = p
2276 i += 1
2277 ps[i:] = (x,) if x else ()
2278 n += 1
2279 if n:
2280 self._n += n
2281 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
2282 if up:
2283 self._update()
2284# x = sum(ps)
2285# if not _isOK_or_finite(x, **fi):
2286# ps[:] = x, # collapse ps
2287 return ps
2289 def _ps_mul(self, op, *factors):
2290 '''(INTERNAL) Multiply this instance' C{partials} with
2291 each scalar C{factor} and accumulate into an C{Fsum}.
2292 '''
2293 def _psfs(ps, fs, _isfine=_isfinite):
2294 if len(ps) < len(fs):
2295 ps, fs = fs, ps
2296 if self._f2product:
2297 fs, p = _2split3s(fs), fs
2298 if len(ps) > 1 and fs is not p:
2299 fs = tuple(fs) # several ps
2300 _pfs = _2products
2301 else:
2302 def _pfs(p, fs):
2303 return (p * f for f in fs)
2305 for p in ps:
2306 for x in _pfs(p, fs):
2307 yield x if _isfine(x) else _nfError(x)
2309 xs = _psfs(self._ps, factors, **self._isfine)
2310 f = _Psum(self._ps_acc([], xs, up=False), name=op)
2311 return f
2313 @property_RO
2314 def _ps_neg(self):
2315 '''(INTERNAL) Yield the partials, I{negated}.
2316 '''
2317 for p in self._ps:
2318 yield -p
2320 def _ps_other(self, op, other):
2321 '''(INTERNAL) Yield C{other} as C{scalar}s.
2322 '''
2323 if _isFsum_2Tuple(other):
2324 for p in other._ps:
2325 yield p
2326 else:
2327 yield self._scalar(other, op)
2329 def _ps_1sum(self, *less):
2330 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
2331 '''
2332 def _1psls(ps, ls):
2333 yield _1_0
2334 for p in ps:
2335 yield p
2336 for p in ls:
2337 yield -p
2338 yield _N_1_0
2340 return _fsum(_1psls(self._ps, less))
2342 def _raiser(self, r, s, raiser=True, **RESIDUAL):
2343 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
2344 I{and} is residual C{r} I{non-zero} or I{significant} (for a
2345 negative respectively positive C{RESIDUAL} threshold)?
2346 '''
2347 if r and raiser:
2348 t = self._RESIDUAL
2349 if RESIDUAL:
2350 t = _threshold(t, **RESIDUAL)
2351 if t < 0 or (s + r) != s:
2352 q = (r / s) if s else s # == 0.
2353 if fabs(q) > fabs(t):
2354 return dict(ratio=q, R=t)
2355 return {}
2357 rdiv = __rtruediv__
2359 @property_RO
2360 def real(self):
2361 '''Get the C{real} part of this instance (C{float}).
2363 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
2364 and properties L{Fsum.ceil}, L{Fsum.floor},
2365 L{Fsum.imag} and L{Fsum.residual}.
2366 '''
2367 return float(self)
2369 @property_RO
2370 def residual(self):
2371 '''Get this instance' residual or residue (C{float} or C{int}):
2372 the C{sum(partials)} less the precision running sum C{fsum}.
2374 @note: The C{residual is INT0} iff the precision running
2375 C{fsum} is considered to be I{exact}.
2377 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
2378 '''
2379 return self._fprs2.residual
2381 def RESIDUAL(self, *threshold):
2382 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
2383 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
2385 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
2386 L{ResidualError}s in division and exponention, if
2387 C{None}, restore the default set with env variable
2388 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
2389 current setting.
2391 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
2393 @raise ResidualError: Invalid B{C{threshold}}.
2395 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}
2396 C{residual / fsum} exceeds the given B{C{threshold}} and (2)
2397 the C{residual} is non-zero and (3) is I{significant} vs the
2398 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional
2399 keyword argument C{raiser=False} is missing. Specify a
2400 negative B{C{threshold}} for only non-zero C{residual}
2401 testing without the I{significant} case.
2402 '''
2403 r = self._RESIDUAL
2404 if threshold:
2405 t = threshold[0]
2406 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
2407 (_0_0 if t else _1_0) if isbool(t) else
2408 _threshold(t)) # ... backward compatibility
2409 return r
2411 def _ResidualError(self, op, other, residual, **mod_R):
2412 '''(INTERNAL) Non-zero B{C{residual}} etc.
2413 '''
2414 def _p(mod=None, R=0, **unused): # ratio=0
2415 return (_non_zero_ if R < 0 else _significant_) \
2416 if mod is None else _integer_
2418 t = _stresidual(_p(**mod_R), residual, **mod_R)
2419 return self._Error(op, other, ResidualError, txt=t)
2421 def root(self, root, **raiser_RESIDUAL):
2422 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
2424 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2425 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any
2426 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar}
2427 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2429 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
2431 @raise ResidualError: Non-zero, significant residual or invalid
2432 B{C{RESIDUAL}}.
2434 @see: Method L{Fsum.pow}.
2435 '''
2436 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL)
2437 f = self._copy_2(self.root)
2438 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
2440 def _scalar(self, other, op, **txt):
2441 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}.
2442 '''
2443 if isscalar(other):
2444 return other
2445 raise self._Error(op, other, _TypeError, **txt) # _invalid_
2447 def signOf(self, res=True):
2448 '''Determine the sign of this instance.
2450 @kwarg res: If C{True}, consider the residual,
2451 otherwise ignore the latter (C{bool}).
2453 @return: The sign (C{int}, -1, 0 or +1).
2454 '''
2455 s, r = self._nfprs2
2456 r = (-r) if res else 0
2457 return _signOf(s, r)
2459 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
2460 '''Return this C{Fsum} instance as representation.
2462 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
2463 for method L{Fsum.toStr}.
2465 @return: This instance (C{repr}).
2466 '''
2467 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
2469 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
2470 '''Return this C{Fsum} instance as string.
2472 @kwarg lenc: If C{True}, include the current C{[len]} of this
2473 L{Fsum} enclosed in I{[brackets]} (C{bool}).
2474 @kwarg prec_sep_fmt: Optional keyword arguments for method
2475 L{Fsum2Tuple.toStr}.
2477 @return: This instance (C{str}).
2478 '''
2479 p = self.classname
2480 if lenc:
2481 p = Fmt.SQUARE(p, len(self))
2482 n = _enquote(self.name, white=_UNDER_)
2483 t = self._nfprs2.toStr(**prec_sep_fmt)
2484 return NN(p, _SPACE_, n, t)
2486 def _truediv(self, other, op, **raiser_RESIDUAL):
2487 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
2488 '''
2489 f = self._copy_2(self.__truediv__)
2490 return f._ftruediv(other, op, **raiser_RESIDUAL)
2492 def _update(self, updated=True): # see ._fset
2493 '''(INTERNAL) Zap all cached C{Property_RO} values.
2494 '''
2495 if updated:
2496 _pop = self.__dict__.pop
2497 for p in _ROs:
2498 _ = _pop(p, None)
2499# Fsum._fint2._update(self)
2500# Fsum._fprs ._update(self)
2501# Fsum._fprs2._update(self)
2502 return self # for .fset_
2504_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
2506if _NONFINITES == _std_: # PYCHOK no cover
2507 _ = nonfiniterrors(False)
2510def _Float_Int(arg, **name_Error):
2511 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit.
2512 '''
2513 U = Int if isint(arg) else Float
2514 return U(arg, **name_Error)
2517class DivMod2Tuple(_NamedTuple):
2518 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
2519 C{mod} results of a C{divmod} operation.
2521 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2522 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2523 '''
2524 _Names_ = ('div', 'mod')
2525 _Units_ = (_Float_Int, Fsum)
2528class Fsum2Tuple(_NamedTuple): # in .fstats
2529 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2530 and the C{residual}, the sum of the remaining partials. Each
2531 item is C{float} or C{int}.
2533 @note: If the C{residual is INT0}, the C{fsum} is considered
2534 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2535 '''
2536 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2537 _Units_ = (_Float_Int, _Float_Int)
2539 def __abs__(self): # in .fmath
2540 return self._Fsum.__abs__()
2542 def __bool__(self): # PYCHOK Python 3+
2543 return bool(self._Fsum)
2545 def __eq__(self, other):
2546 return self._other_op(other, self.__eq__)
2548 def __float__(self):
2549 return self._Fsum.__float__()
2551 def __ge__(self, other):
2552 return self._other_op(other, self.__ge__)
2554 def __gt__(self, other):
2555 return self._other_op(other, self.__gt__)
2557 def __le__(self, other):
2558 return self._other_op(other, self.__le__)
2560 def __lt__(self, other):
2561 return self._other_op(other, self.__lt__)
2563 def __int__(self):
2564 return self._Fsum.__int__()
2566 def __ne__(self, other):
2567 return self._other_op(other, self.__ne__)
2569 def __neg__(self):
2570 return self._Fsum.__neg__()
2572 __nonzero__ = __bool__ # Python 2-
2574 def __pos__(self):
2575 return self._Fsum.__pos__()
2577 def as_integer_ratio(self):
2578 '''Return this instance as the ratio of 2 integers.
2580 @see: Method L{Fsum.as_integer_ratio} for further details.
2581 '''
2582 return self._Fsum.as_integer_ratio()
2584 @property_RO
2585 def _fint2(self):
2586 return self._Fsum._fint2
2588 @property_RO
2589 def _fprs2(self):
2590 return self._Fsum._fprs2
2592 @Property_RO
2593 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2594 s, r = _s_r2(*self)
2595 ps = (r, s) if r else (s,)
2596 return _Psum(ps, name=self.name)
2598 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL):
2599 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2600 '''
2601 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL)
2603 def is_exact(self):
2604 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2605 '''
2606 return self._Fsum.is_exact()
2608 def is_finite(self): # in .constants
2609 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}).
2611 @see: Function L{isfinite<pygeodesy.isfinite>}.
2612 '''
2613 return self._Fsum.is_finite()
2615 def is_integer(self):
2616 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2617 '''
2618 return self._Fsum.is_integer()
2620 def _mul_scalar(self, other, op): # for Fsum._fmul
2621 return self._Fsum._mul_scalar(other, op)
2623 @property_RO
2624 def _n(self):
2625 return self._Fsum._n
2627 def _other_op(self, other, which):
2628 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2629 return getattr(C, which.__name__)(s, other)
2631 @property_RO
2632 def _ps(self):
2633 return self._Fsum._ps
2635 @property_RO
2636 def _ps_neg(self):
2637 return self._Fsum._ps_neg
2639 def signOf(self, **res):
2640 '''Like method L{Fsum.signOf}.
2641 '''
2642 return self._Fsum.signOf(**res)
2644 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2645 '''Return this L{Fsum2Tuple} as string (C{str}).
2647 @kwarg fmt: Optional C{float} format (C{letter}).
2648 @kwarg prec_sep: Optional keyword arguments for function
2649 L{fstr<streprs.fstr>}.
2650 '''
2651 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2653_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2656class ResidualError(_ValueError):
2657 '''Error raised for a division, power or root operation of
2658 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2659 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2661 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2662 '''
2663 pass
2666try:
2667 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2669 # make sure _fsum works as expected (XXX check
2670 # float.__getformat__('float')[:4] == 'IEEE'?)
2671 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2672 del _fsum # nope, remove _fsum ...
2673 raise ImportError() # ... use _fsum below
2675 _sum = _fsum # in .elliptic
2676except ImportError:
2677 _sum = sum # in .elliptic
2679 def _fsum(xs):
2680 '''(INTERNAL) Precision summation, Python 2.5-.
2681 '''
2682 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True)
2683 return float(F._facc(xs, up=False))
2686def fsum(xs, nonfinites=None, **floats):
2687 '''Precision floating point summation from Python's C{math.fsum}.
2689 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2690 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if
2691 C{False} I{non-finites} raise an Overflow-/ValueError or if
2692 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}).
2693 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use
2694 keyword argument C{B{nonfinites}=False} instead.
2696 @return: Precision C{fsum} (C{float}).
2698 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow.
2700 @raise TypeError: Invalid B{C{xs}} item.
2702 @raise ValueError: Invalid or C{NAN} B{C{xs}} item.
2704 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites},
2705 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}.
2706 '''
2707 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0
2710def fsum_(*xs, **nonfinites):
2711 '''Precision floating point summation of all positional items.
2713 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2714 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2716 @see: Function L{fsum<fsums.fsum>} for further details.
2717 '''
2718 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1?
2721def fsumf_(*xs):
2722 '''Precision floating point summation of all positional items with I{non-finites} C{OK}.
2724 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
2725 all positional.
2727 @see: Function L{fsum_<fsums.fsum_>} for further details.
2728 '''
2729 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1?
2732def fsum1(xs, **nonfinites):
2733 '''Precision floating point summation, 1-primed.
2735 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2736 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2738 @see: Function L{fsum<fsums.fsum>} for further details.
2739 '''
2740 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0
2743def fsum1_(*xs, **nonfinites):
2744 '''Precision floating point summation of all positional items, 1-primed.
2746 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2747 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2749 @see: Function L{fsum_<fsums.fsum_>} for further details.
2750 '''
2751 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1?
2754def fsum1f_(*xs):
2755 '''Precision floating point summation of all positional items, 1-primed and
2756 with I{non-finites} C{OK}.
2758 @see: Function L{fsum_<fsums.fsum_>} for further details.
2759 '''
2760 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0
2763def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers.
2764 _x_kwds = dict(_x= (_passarg if nfOK else _2finite),
2765 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds
2766 _x_kwds.update(kwds)
2767 return _x_kwds
2770def _X_ps(X): # default C{_X} handler
2771 return X._ps # lambda X: X._ps
2774def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc
2775 origin=0, which=None, **_Cdot):
2776 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s.
2777 '''
2778 i, x = 0, xs
2779 try:
2780 for i, x in enumerate(_xiterable(xs)):
2781 if _isFsum_2Tuple(x):
2782 for p in _X(x):
2783 yield p if _isfine(p) else _nfError(p)
2784 else:
2785 f = _x(x)
2786 yield f if _isfine(f) else _nfError(f)
2788 except (OverflowError, TypeError, ValueError) as X:
2789 t = _xsError(X, xs, i + origin, x)
2790 if which: # prefix invokation
2791 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot)
2792 t = _COMMASPACE_(w, t)
2793 raise _xError(X, t, txt=None)
2796def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0
2797 '''(INTERNAL) Precision summation of C{xs} with conditions.
2798 '''
2799 if floats: # for backward compatibility
2800 nonfinites = _xkwds_get1(floats, floats=nonfinites)
2801 elif nonfinites is None:
2802 nonfinites = not nonfiniterrors()
2803 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) # PYCHOK yield
2804 return _fsum(_1primed(fs) if primed else fs)
2807# delete all decorators, etc.
2808del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \
2809 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \
2810 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _getPYGEODESY, _std_
2812if __name__ == '__main__':
2814 # usage: python3 -m pygeodesy.fsums
2816 def _test(n):
2817 # copied from Hettinger, see L{Fsum} reference
2818 from pygeodesy import frandoms, printf
2820 printf(_fsum.__name__, end=_COMMASPACE_)
2821 printf(_psum.__name__, end=_COMMASPACE_)
2823 F = Fsum()
2824 if F.is_math_fsum():
2825 for t in frandoms(n, seeded=True):
2826 assert float(F.fset_(*t)) == _fsum(t)
2827 printf(_DOT_, end=NN)
2828 printf(NN)
2830 _test(128)
2832# **) MIT License
2833#
2834# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
2835#
2836# Permission is hereby granted, free of charge, to any person obtaining a
2837# copy of this software and associated documentation files (the "Software"),
2838# to deal in the Software without restriction, including without limitation
2839# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2840# and/or sell copies of the Software, and to permit persons to whom the
2841# Software is furnished to do so, subject to the following conditions:
2842#
2843# The above copyright notice and this permission notice shall be included
2844# in all copies or substantial portions of the Software.
2845#
2846# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2847# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2848# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2849# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2850# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2851# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2852# OTHER DEALINGS IN THE SOFTWARE.