Coverage for pygeodesy/fsums.py: 95%
1064 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-09-25 17:40 -0400
« prev ^ index » next coverage.py v7.6.0, created at 2024-09-25 17:40 -0400
2# -*- coding: utf-8 -*-
4u'''Class L{Fsum} for precision floating point summation similar to
5Python's C{math.fsum} enhanced with I{running} summation and as an
6option, accurate I{TwoProduct} multiplication.
8Accurate multiplication is based on the C{math.fma} function for
9Python 3.13 and newer or one of two equivalent C{fma} implementations
10for Python 3.12 and older. To enable accurate multiplication, set
11env variable C{PYGEODESY_FSUM_F2PRODUCT} to C{"std"} or any non-empty
12string or invoke function C{pygeodesy.f2product(True)} or set. With
13C{"std"} the C{fma} implemention follows the C{math.fma} function,
14otherwise the C{PyGeodesy 24.09.09} release.
16Generally, an L{Fsum} instance is considered a C{float} plus a small or
17zero C{residue} aka C{residual} value, see property L{Fsum.residual}.
19Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater
20than C{"0.0"} as the threshold to throw a L{ResidualError} for a division,
21power or root operation of an L{Fsum} with a C{residual} I{ratio} exceeding
22the threshold. See methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
23and L{Fsum.__itruediv__}.
25There are several C{integer} L{Fsum} cases, for example the result from
26functions C{ceil}, C{floor}, C{Fsum.__floordiv__} and methods L{Fsum.fint},
27L{Fsum.fint2} and L{Fsum.is_integer}. Also, L{Fsum} methods L{Fsum.pow},
28L{Fsum.__ipow__}, L{Fsum.__pow__} and L{Fsum.__rpow__} return a (very long)
29C{int} if invoked with optional argument C{mod} set to C{None}. The
30C{residual} of an C{integer} L{Fsum} is between C{-1.0} and C{+1.0} and
31will be C{INT0} if that is considered to be I{exact}.
33Set env variable C{PYGEODESY_FSUM_NONFINITES} to C{"std"} or use function
34C{pygeodesy.nonfiniterrors(False)} to allow I{non-finite} C{float}s like
35C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} and to ignore C{OverflowError}
36respectively C{ValueError} exceptions. However, in that case I{non-finite}
37results may differ from Python's C{math.fsum} results.
38'''
39# make sure int/int division yields float quotient, see .basics
40from __future__ import division as _; del _ # PYCHOK semicolon
42from pygeodesy.basics import isbool, iscomplex, isint, isscalar, \
43 _signOf, itemsorted, signOf, _xiterable, \
44 _xiterablen
45from pygeodesy.constants import INF, INT0, MANT_DIG, NEG0, NINF, _0_0, \
46 _1_0, _N_1_0, _isfinite, _pos_self, \
47 Float, Int
48from pygeodesy.errors import _AssertionError, _OverflowError, _TypeError, \
49 _ValueError, _xError, _xError2, _xkwds_get, \
50 _xkwds, _xkwds_get1, _xkwds_not, _xkwds_pop
51from pygeodesy.internals import _enquote, _passarg
52from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DOT_, _from_, \
53 _not_finite_, _SPACE_, _std_, _UNDER_
54from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
55from pygeodesy.named import _name__, _name2__, _Named, _NamedTuple, \
56 _NotImplemented
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.09.25'
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_eq_op_ = _fset_op_ * 2 # _DEQUAL_
81_floordiv_op_ = _truediv_op_ * 2 # _DSLASH_
82_divmod_op_ = _floordiv_op_ + _mod_op_
83_F2PRODUCT = _getenv('PYGEODESY_FSUM_F2PRODUCT', NN)
84_ge_op_ = _gt_op_ + _fset_op_
85_iadd_op_ = _add_op_ + _fset_op_ # in .auxilats.auxAngle, .fstats
86_integer_ = 'integer'
87_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle
88_le_op_ = _lt_op_ + _fset_op_
89_NONFINITES = _getenv('PYGEODESY_FSUM_NONFINITES', NN) == _std_
90_non_zero_ = 'non-zero'
91_pow_op_ = _mul_op_ * 2 # _DSTAR_
92_RESIDUAL_0_0 = _getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)
93_significant_ = 'significant'
94_2split3s = _passarg
95_threshold_ = 'threshold'
98def _2finite(x): # in .fstats
99 '''(INTERNAL) return C{float(x)} if finite.
100 '''
101 return (float(x) if _isfinite(x) # and isscalar(x)
102 else _nfError(x))
105def _2float(index=None, _isfine=_isfinite, **name_value): # in .fmath, .fstats
106 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.
107 '''
108 n, v = name_value.popitem() # _xkwds_item2(name_value)
109 try:
110 f = float(v)
111 return f if _isfine(f) else _nfError(f)
112 except Exception as X:
113 raise _xError(X, Fmt.INDEX(n, index), v)
116def _X_ps(X): # for _2floats only
117 return X._ps
120def _2floats(xs, origin=0, _X=_X_ps, _x=float, _isfine=_isfinite):
121 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
122 '''
123 try:
124 i, x = origin, xs
125 _FsT = _Fsum_Fsum2Tuple_types
126 for x in _xiterable(xs):
127 if isinstance(x, _FsT):
128 for p in _X(x._Fsum):
129 yield p
130 else:
131 f = _x(x)
132 yield f if _isfine(f) else _nfError(f)
133 i += 1
134 except Exception as X:
135 raise _xsError(X, xs, i, x)
138try: # MCCABE 17
139 from math import fma as _fma
140except ImportError: # Python 3.12-
142 if _F2PRODUCT == _std_:
143 _2FACTOR = pow(2, (MANT_DIG + 1) // 2) + 1
145 def _fma(a, b, c):
146 # mimick C{math.fma} from Python 3.13+,
147 # the same accuracy, but ~13x slower
148 b3s = _2split3(b),
149 r = fsumf_(c, *_2products(a, b3s)) # two=True
150 return r if _isfinite(r) else _fmaX(r, a, b, c)
152 def _2split3(x):
153 # Split U{Algorithm 3.2
154 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
155 a = c = x * _2FACTOR
156 a -= c - x
157 b = x - a
158 return x, a, b
160 def _2split3s(xs): # overwrites
161 return tuple(map(_2split3, xs))
163 else:
164 def _fma(*a_b_c): # PYCHOK no cover
165 # mimick C{math.fma} from Python 3.13+,
166 # the same accuracy, but ~14x slower
167 (na, da), (nb, db), (nc, dc) = map(_2n_d, a_b_c)
168 n = na * nb * dc
169 n += da * db * nc
170 d = da * db * dc
171 try:
172 r = float(n / d)
173 except OverflowError: # "integer division result too large ..."
174 r = NINF if (_signOf(n, 0) * _signOf(d, 0)) < 0 else INF
175 return r if _isfinite(r) else _fmaX(r, *a_b_c) # "overflow in fma"
177 def _2n_d(x):
178 try: # int.as_integer_ratio in 3.8+
179 return x.as_integer_ratio()
180 except (AttributeError, OverflowError, TypeError, ValueError):
181 return (x if isint(x) else float(x)), 1
183 def _fmaX(r, *a_b_c): # like Python 3.13+ I{Modules/mathmodule.c}:
184 # raise a ValueError for a NAN result from non-NAN C{a_b_c}s or
185 # OverflowError for a non-NAN result from all finite C{a_b_c}s.
186 if isnan(r):
187 def _is(x):
188 return not isnan(x)
189 else:
190 _is = _isfinite
191 if all(map(_is, a_b_c)):
192 raise _nfError(r, unstr(_fma, *a_b_c))
193 return r
195if _2split3s is _passarg: # math._fma or _fma(*a_b_c)
197 def _2products(x, ys, **unused):
198 # TwoProductFMA U{Algorithm 3.5
199 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
200 for y in ys:
201 f = x * y
202 yield f
203 yield _fma(x, y, -f)
205else: # in _std_ _fma(a, b, c)
207 def _2products(x, y3s, two=False): # PYCHOK redef
208 # TwoProduct U{Algorithm 3.3
209 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
210 # also in Python 3.13+ C{Modules/marhmodule.c} under
211 # #ifndef UNRELIABLE_FMA ... #else ... #endif
212 _, a, b = _2split3(x)
213 for y, c, d in y3s:
214 y *= x
215 yield y
216 if two: # or not a:
217 yield b * d - (((y - a * c) - b * c) - a * d)
218 # = b * d + (a * d - ((y - a * c) - b * c))
219 # = b * d + (a * d + (b * c - (y - a * c)))
220 # = b * d + (a * d + (b * c + (a * c - y)))
221 else:
222 yield a * c - y
223 yield b * c
224 if d:
225 yield a * d
226 yield b * d
229def f2product(*two):
230 '''Turn accurate I{TwoProduct} multiplication on or off.
232 @arg two: If C{True}, turn I{TwoProduct} on, if C{False} off or
233 if C{None} or omitted, keep the current setting.
235 @return: The previous setting (C{bool}).
237 @see: I{TwoProduct} multiplication is based on the I{TwoProductFMA}
238 U{Algorithm 3.5 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
239 using function C{math.fma} from Python 3.13 and later or an
240 equivalent, slower implementation when not available.
241 '''
242 t = Fsum._f2product
243 if two and two[0] is not None:
244 Fsum._f2product = bool(two[0])
245 return t
248def _Fsumf_(*xs): # in .auxLat, .ltp, ...
249 '''(INTERNAL) An C{Fsum} of I{known scalars}.
250 '''
251 return Fsum()._facc_scalar(xs, up=False)
254def _Fsum1f_(*xs): # in .albers
255 '''(INTERNAL) An C{Fsum} of I{known scalars}, 1-primed.
256 '''
257 return Fsum()._facc_scalar(_1primed(xs), up=False)
260def _2halfeven(s, r, p):
261 '''(INTERNAL) Round half-even.
262 '''
263 if (p > 0 and r > 0) or \
264 (p < 0 and r < 0): # signs match
265 r *= 2
266 t = s + r
267 if r == (t - s):
268 s = t
269 return s
272def _isFsum(x): # in .fmath
273 '''(INTERNAL) Is C{x} an C{Fsum} instance?
274 '''
275 return isinstance(x, Fsum)
278def _isFsumTuple(x): # in .basics, .constants, .fmath, .fstats
279 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance?
280 '''
281 return isinstance(x, _Fsum_Fsum2Tuple_types)
284def _isOK(unused):
285 '''(INTERNAL) Helper for C{nonfiniterrors} and C{Fsum.nonfinites}.
286 '''
287 return True
290def _isOK_or_finite(x, _isfine=_isfinite):
291 '''(INTERNAL) Is C{x} finite or is I{non-finite} OK?.
292 '''
293 # assert _isfine in (_isOK, _isfinite)
294 return _isfine(x)
297def _nfError(x, *args):
298 '''(INTERNAL) Throw a C{not-finite} exception.
299 '''
300 E = _NonfiniteError(x)
301 t = Fmt.PARENSPACED(_not_finite_, x)
302 if args: # in _fma, _2sum
303 return E(txt=t, *args)
304 raise E(t, txt=None)
307def nonfiniterrors(*raiser):
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 @arg 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 and raiser[0] is not None:
323 Fsum._isfine = {} if bool(raiser[0]) else Fsum._nonfinites_isfine_kwds[True]
324 return _xkwds_get1(d, _isfine=_isfinite) is _isfinite
327def _NonfiniteError(x):
328 '''(INTERNAL) Return the Error class for C{x}, I{non-finite}.
329 '''
330 return _OverflowError if isinf(x) else (
331 _ValueError if isnan(x) else _AssertionError)
334def _1primed(xs): # in .fmath
335 '''(INTERNAL) 1-Primed summation of iterable C{xs}
336 items, all I{known} to be C{scalar}.
337 '''
338 yield _1_0
339 for x in xs:
340 yield x
341 yield _N_1_0
344def _psum(ps, **_isfine): # PYCHOK used!
345 '''(INTERNAL) Partials summation, updating C{ps}.
346 '''
347 # assert isinstance(ps, list)
348 i = len(ps) - 1
349 s = _0_0 if i < 0 else ps[i]
350 while i > 0:
351 i -= 1
352 s, r = _2sum(s, ps[i], **_isfine)
353 if r: # sum(ps) became inexact
354 if s:
355 ps[i:] = r, s
356 if i > 0:
357 s = _2halfeven(s, r, ps[i-1])
358 break # return s
359 s = r # PYCHOK no cover
360 elif not _isfinite(s): # non-finite OK
361 i = 0 # collapse ps
362 if ps:
363 s += _sum(ps) # _fsum(ps)
364 ps[i:] = s,
365 return s
368def _Psum(ps, **name_f2product_nonfinites_RESIDUAL):
369 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
370 '''
371 F = Fsum(**name_f2product_nonfinites_RESIDUAL)
372 if ps:
373 F._ps[:] = ps
374 F._n = len(F._ps)
375 return F
378def _Psum_(*ps, **name_f2product_nonfinites_RESIDUAL): # in .fmath
379 '''(INTERNAL) Return an C{Fsum} from I{known scalar} C{ps}.
380 '''
381 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL)
384def _2scalar2(other):
385 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int},
386 C{float} or C{as-is} and C{r} the residual of C{as-is}.
387 '''
388 if _isFsumTuple(other):
389 s, r = other._fint2
390 if r:
391 s, r = other._fprs2
392 if r: # PYCHOK no cover
393 s = other # L{Fsum} as-is
394 else:
395 r = 0
396 s = other # C{type} as-is
397 if isint(s, both=True):
398 s = int(s)
399 return s, r
402def _s_r(s, r):
403 '''(INTERNAL) Return C{(s, r)}, I{ordered}.
404 '''
405 if r and _isfinite(s):
406 if fabs(s) < fabs(r):
407 s, r = r, (s or INT0)
408 else:
409 r = INT0
410 return s, r
413def _strcomplex(s, *args):
414 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
415 '''
416 c = _strcomplex.__name__[4:]
417 n = _sub_op_(len(args), _arg_)
418 t = unstr(pow, *args)
419 return _SPACE_(c, s, _from_, n, t)
422def _stresidual(prefix, residual, R=0, **mod_ratio):
423 '''(INTERNAL) Residual error txt C{str}.
424 '''
425 p = _stresidual.__name__[3:]
426 t = Fmt.PARENSPACED(p, Fmt(residual))
427 for n, v in itemsorted(mod_ratio):
428 p = Fmt.PARENSPACED(n, Fmt(v))
429 t = _COMMASPACE_(t, p)
430 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_)
433def _2sum(a, b, _isfine=_isfinite): # in .testFmath
434 '''(INTERNAL) Return C{a + b} as 2-tuple C{(sum, residual)} with finite C{sum},
435 otherwise as 2-tuple C{(nonfinite, 0)} iff I{non-finites} are OK.
436 '''
437 # FastTwoSum U{Algorithm 1.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}
439 # Neumaier, A. U{Rundungsfehleranalyse einiger Verfahren zur Summation endlicher
440 # Summen<https://OnlineLibrary.Wiley.com/doi/epdf/10.1002/zamm.19740540106>},
441 # 1974, Zeitschrift für Angewandte Mathmatik und Mechanik, vol 51, nr 1, p 39-51
442 # <https://StackOverflow.com/questions/78633770/can-neumaier-summation-be-sped-up>
443 s = a + b
444 if _isfinite(s):
445 if fabs(a) < fabs(b):
446 r = (b - s) + a
447 else:
448 r = (a - s) + b
449 elif _isfine(s):
450 r = 0
451 else: # non-finite and not OK
452 t = unstr(_2sum, a, b)
453 raise _nfError(s, t)
454 return s, r
457def _threshold(threshold=_0_0, **kwds):
458 '''(INTERNAL) Get the L{ResidualError}s threshold,
459 optionally from single kwds C{B{RESIDUAL}=scalar}.
460 '''
461 if kwds:
462 threshold = _xkwds_get1(kwds, RESIDUAL=threshold)
463 try:
464 return _2finite(threshold) # PYCHOK None
465 except Exception as x:
466 raise ResidualError(threshold=threshold, cause=x)
469class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase, .fstats, ...
470 '''Precision floating point summation, I{running} summation and accurate multiplication.
472 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
473 I{running}, precision floating point summations. Accumulation may continue after any
474 intermediate, I{running} summuation.
476 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances,
477 i.e. any C{type} having method C{__float__}.
479 @note: Handling of I{non-finites} as C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} is
480 determined globally by function L{nonfiniterrors<fsums.nonfiniterrors>} and
481 by method L{nonfinites<Fsum.nonfinites>} for individual C{Fsum} instances,
482 overruling the global setting. By default and for backward compatibility,
483 I{non-finites} raise exceptions.
485 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/
486 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>},
487 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
488 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
489 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
490 <https://Bugs.Python.org/issue2819>}.
492 @see: Method L{f2product<Fsum.f2product>} for details about accurate I{TwoProduct}
493 multiplication.
495 @see: Module L{fsums<pygeodesy.fsums>} for env variables C{PYGEODESY_FSUM_F2PRODUCT},
496 C{PYGEODESY_FSUM_NONFINITES} and C{PYGEODESY_FSUM_RESIDUAL}.
497 '''
498 _f2product = _sys_version_info2 > (3, 12) or bool(_F2PRODUCT)
499 _isfine = {} # == _isfinite
500 _n = 0
501# _ps = [] # partial sums
502# _ps_max = 0 # max(Fsum._ps_max, len(Fsum._ps))
503 _RESIDUAL = _threshold(_RESIDUAL_0_0)
505 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL):
506 '''New L{Fsum}.
508 @arg xs: No, one or more initial items to accumulate (each C{scalar}, an
509 L{Fsum} or L{Fsum2Tuple}), all positional.
510 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str})
511 and settings C{B{f2product}=None} (C{bool}), C{B{nonfinites}=None}
512 (C{bool}) and C{B{RESIDUAL}=0.0} threshold (C{scalar}) for this
513 L{Fsum}.
515 @see: Methods L{Fsum.f2product}, L{Fsum.nonfinites}, L{Fsum.RESIDUAL},
516 L{Fsum.fadd} and L{Fsum.fadd_}.
517 '''
518 if name_f2product_nonfinites_RESIDUAL:
519 self._optionals(**name_f2product_nonfinites_RESIDUAL)
520 self._ps = [] # [_0_0], see L{Fsum._fprs}
521 if xs:
522 self._facc_args(xs, up=False)
524 def __abs__(self):
525 '''Return C{abs(self)} as an L{Fsum}.
526 '''
527 s = self.signOf() # == self._cmp_0(0)
528 return (-self) if s < 0 else self._copy_2(self.__abs__)
530 def __add__(self, other):
531 '''Return C{B{self} + B{other}} as an L{Fsum}.
533 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
535 @return: The sum (L{Fsum}).
537 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
538 '''
539 f = self._copy_2(self.__add__)
540 return f._fadd(other, _add_op_)
542 def __bool__(self): # PYCHOK Python 3+
543 '''Return C{bool(B{self})}, C{True} iff C{residual} is zero.
544 '''
545 s, r = self._fprs2
546 return bool(s or r) and s != -r # == self != 0
548 def __ceil__(self): # PYCHOK not special in Python 2-
549 '''Return this instance' C{math.ceil} as C{int} or C{float}.
551 @return: An C{int} in Python 3+, but C{float} in Python 2-.
553 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
554 '''
555 return self.ceil
557 def __cmp__(self, other): # PYCHOK no cover
558 '''Compare this with an other instance or C{scalar}, Python 2-.
560 @return: -1, 0 or +1 (C{int}).
562 @raise TypeError: Incompatible B{C{other}} C{type}.
563 '''
564 s = self._cmp_0(other, self.cmp.__name__)
565 return _signOf(s, 0)
567 def __divmod__(self, other, **raiser_RESIDUAL):
568 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
569 with quotient C{div} an C{int} in Python 3+ or C{float}
570 in Python 2- and remainder C{mod} an L{Fsum} instance.
572 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
573 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
574 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
575 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
577 @raise ResidualError: Non-zero, significant residual or invalid
578 B{C{RESIDUAL}}.
580 @see: Method L{Fsum.fdiv}.
581 '''
582 f = self._copy_2(self.__divmod__)
583 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL)
585 def __eq__(self, other):
586 '''Return C{(B{self} == B{other})} as C{bool} where B{C{other}}
587 is C{scalar}, an other L{Fsum} or L{Fsum2Tuple}.
588 '''
589 return self._cmp_0(other, _eq_op_) == 0
591 def __float__(self):
592 '''Return this instance' current, precision running sum as C{float}.
594 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
595 '''
596 return float(self._fprs)
598 def __floor__(self): # PYCHOK not special in Python 2-
599 '''Return this instance' C{math.floor} as C{int} or C{float}.
601 @return: An C{int} in Python 3+, but C{float} in Python 2-.
603 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
604 '''
605 return self.floor
607 def __floordiv__(self, other):
608 '''Return C{B{self} // B{other}} as an L{Fsum}.
610 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
612 @return: The C{floor} quotient (L{Fsum}).
614 @see: Methods L{Fsum.__ifloordiv__}.
615 '''
616 f = self._copy_2(self.__floordiv__)
617 return f._floordiv(other, _floordiv_op_)
619 def __format__(self, *other): # PYCHOK no cover
620 '''Not implemented.'''
621 return _NotImplemented(self, *other)
623 def __ge__(self, other):
624 '''Return C{(B{self} >= B{other})}, see C{__eq__}.
625 '''
626 return self._cmp_0(other, _ge_op_) >= 0
628 def __gt__(self, other):
629 '''Return C{(B{self} > B{other})}, see C{__eq__}.
630 '''
631 return self._cmp_0(other, _gt_op_) > 0
633 def __hash__(self): # PYCHOK no cover
634 '''Return C{hash(B{self})} as C{float}.
635 '''
636 # @see: U{Notes for type implementors<https://docs.Python.org/
637 # 3/library/numbers.html#numbers.Rational>}
638 return hash(self.partials) # tuple.__hash__()
640 def __iadd__(self, other):
641 '''Apply C{B{self} += B{other}} to this instance.
643 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
644 an iterable of several of the former.
646 @return: This instance, updated (L{Fsum}).
648 @raise TypeError: Invalid B{C{other}}, not
649 C{scalar} nor L{Fsum}.
651 @see: Methods L{Fsum.fadd_} and L{Fsum.fadd}.
652 '''
653 try:
654 return self._fadd(other, _iadd_op_)
655 except TypeError:
656 pass
657 _xiterable(other)
658 return self._facc(other)
660 def __ifloordiv__(self, other):
661 '''Apply C{B{self} //= B{other}} to this instance.
663 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
665 @return: This instance, updated (L{Fsum}).
667 @raise ResidualError: Non-zero, significant residual
668 in B{C{other}}.
670 @raise TypeError: Invalid B{C{other}} type.
672 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
674 @raise ZeroDivisionError: Zero B{C{other}}.
676 @see: Methods L{Fsum.__itruediv__}.
677 '''
678 return self._floordiv(other, _floordiv_op_ + _fset_op_)
680 def __imatmul__(self, other): # PYCHOK no cover
681 '''Not implemented.'''
682 return _NotImplemented(self, other)
684 def __imod__(self, other):
685 '''Apply C{B{self} %= B{other}} to this instance.
687 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus.
689 @return: This instance, updated (L{Fsum}).
691 @see: Method L{Fsum.__divmod__}.
692 '''
693 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
695 def __imul__(self, other):
696 '''Apply C{B{self} *= B{other}} to this instance.
698 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor.
700 @return: This instance, updated (L{Fsum}).
702 @raise OverflowError: Partial C{2sum} overflow.
704 @raise TypeError: Invalid B{C{other}} type.
706 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
707 '''
708 return self._fmul(other, _mul_op_ + _fset_op_)
710 def __int__(self):
711 '''Return this instance as an C{int}.
713 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}
714 and L{Fsum.floor}.
715 '''
716 i, _ = self._fint2
717 return i
719 def __invert__(self): # PYCHOK no cover
720 '''Not implemented.'''
721 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
722 return _NotImplemented(self)
724 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args
725 '''Apply C{B{self} **= B{other}} to this instance.
727 @arg other: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
728 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
729 C{pow(B{self}, B{other}, B{mod})} version.
730 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
731 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
732 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
734 @return: This instance, updated (L{Fsum}).
736 @note: If B{C{mod}} is given, the result will be an C{integer}
737 L{Fsum} in Python 3+ if this instance C{is_integer} or
738 set to C{as_integer} and B{C{mod}} is given and C{None}.
740 @raise OverflowError: Partial C{2sum} overflow.
742 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual
743 is non-zero and significant and either
744 B{C{other}} is a fractional or negative
745 C{scalar} or B{C{mod}} is given and not
746 C{None}.
748 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow}
749 invocation failed.
751 @raise ValueError: If B{C{other}} is a negative C{scalar} and this
752 instance is C{0} or B{C{other}} is a fractional
753 C{scalar} and this instance is negative or has a
754 non-zero and significant residual or B{C{mod}}
755 is given as C{0}.
757 @see: CPython function U{float_pow<https://GitHub.com/
758 python/cpython/blob/main/Objects/floatobject.c>}.
759 '''
760 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL)
762 def __isub__(self, other):
763 '''Apply C{B{self} -= B{other}} to this instance.
765 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or
766 an iterable of several of the former.
768 @return: This instance, updated (L{Fsum}).
770 @raise TypeError: Invalid B{C{other}} type.
772 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}.
773 '''
774 try:
775 return self._fsub(other, _isub_op_)
776 except TypeError:
777 pass
778 _xiterable(other)
779 return self._facc_neg(other)
781 def __iter__(self):
782 '''Return an C{iter}ator over a C{partials} duplicate.
783 '''
784 return iter(self.partials)
786 def __itruediv__(self, other, **raiser_RESIDUAL):
787 '''Apply C{B{self} /= B{other}} to this instance.
789 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
790 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
791 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
792 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
794 @return: This instance, updated (L{Fsum}).
796 @raise OverflowError: Partial C{2sum} overflow.
798 @raise ResidualError: Non-zero, significant residual or invalid
799 B{C{RESIDUAL}}.
801 @raise TypeError: Invalid B{C{other}} type.
803 @raise ValueError: Invalid or I{non-finite} B{C{other}}.
805 @raise ZeroDivisionError: Zero B{C{other}}.
807 @see: Method L{Fsum.__ifloordiv__}.
808 '''
809 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL)
811 def __le__(self, other):
812 '''Return C{(B{self} <= B{other})}, see C{__eq__}.
813 '''
814 return self._cmp_0(other, _le_op_) <= 0
816 def __len__(self):
817 '''Return the number of values accumulated (C{int}).
818 '''
819 return self._n
821 def __lt__(self, other):
822 '''Return C{(B{self} < B{other})}, see C{__eq__}.
823 '''
824 return self._cmp_0(other, _lt_op_) < 0
826 def __matmul__(self, other): # PYCHOK no cover
827 '''Not implemented.'''
828 return _NotImplemented(self, other)
830 def __mod__(self, other):
831 '''Return C{B{self} % B{other}} as an L{Fsum}.
833 @see: Method L{Fsum.__imod__}.
834 '''
835 f = self._copy_2(self.__mod__)
836 return f._fdivmod2(other, _mod_op_).mod
838 def __mul__(self, other):
839 '''Return C{B{self} * B{other}} as an L{Fsum}.
841 @see: Method L{Fsum.__imul__}.
842 '''
843 f = self._copy_2(self.__mul__)
844 return f._fmul(other, _mul_op_)
846 def __ne__(self, other):
847 '''Return C{(B{self} != B{other})}, see C{__eq__}.
848 '''
849 return self._cmp_0(other, _ne_op_) != 0
851 def __neg__(self):
852 '''Return C{copy(B{self})}, I{negated}.
853 '''
854 f = self._copy_2(self.__neg__)
855 return f._fset(self._neg)
857 def __pos__(self):
858 '''Return this instance I{as-is}, like C{float.__pos__()}.
859 '''
860 return self if _pos_self else self._copy_2(self.__pos__)
862 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
863 '''Return C{B{self}**B{other}} as an L{Fsum}.
865 @see: Method L{Fsum.__ipow__}.
866 '''
867 f = self._copy_2(self.__pow__)
868 return f._fpow(other, _pow_op_, *mod)
870 def __radd__(self, other):
871 '''Return C{B{other} + B{self}} as an L{Fsum}.
873 @see: Method L{Fsum.__iadd__}.
874 '''
875 f = self._copy_2r(other, self.__radd__)
876 return f._fadd(self, _add_op_)
878 def __rdivmod__(self, other):
879 '''Return C{divmod(B{other}, B{self})} as 2-tuple
880 C{(quotient, remainder)}.
882 @see: Method L{Fsum.__divmod__}.
883 '''
884 f = self._copy_2r(other, self.__rdivmod__)
885 return f._fdivmod2(self, _divmod_op_)
887# def __repr__(self):
888# '''Return the default C{repr(this)}.
889# '''
890# return self.toRepr(lenc=True)
892 def __rfloordiv__(self, other):
893 '''Return C{B{other} // B{self}} as an L{Fsum}.
895 @see: Method L{Fsum.__ifloordiv__}.
896 '''
897 f = self._copy_2r(other, self.__rfloordiv__)
898 return f._floordiv(self, _floordiv_op_)
900 def __rmatmul__(self, other): # PYCHOK no cover
901 '''Not implemented.'''
902 return _NotImplemented(self, other)
904 def __rmod__(self, other):
905 '''Return C{B{other} % B{self}} as an L{Fsum}.
907 @see: Method L{Fsum.__imod__}.
908 '''
909 f = self._copy_2r(other, self.__rmod__)
910 return f._fdivmod2(self, _mod_op_).mod
912 def __rmul__(self, other):
913 '''Return C{B{other} * B{self}} as an L{Fsum}.
915 @see: Method L{Fsum.__imul__}.
916 '''
917 f = self._copy_2r(other, self.__rmul__)
918 return f._fmul(self, _mul_op_)
920 def __round__(self, *ndigits): # PYCHOK Python 3+
921 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
923 @arg ndigits: Optional number of digits (C{int}).
924 '''
925 f = self._copy_2(self.__round__)
926 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
927 return f._fset(round(float(self), *ndigits)) # can be C{int}
929 def __rpow__(self, other, *mod):
930 '''Return C{B{other}**B{self}} as an L{Fsum}.
932 @see: Method L{Fsum.__ipow__}.
933 '''
934 f = self._copy_2r(other, self.__rpow__)
935 return f._fpow(self, _pow_op_, *mod)
937 def __rsub__(self, other):
938 '''Return C{B{other} - B{self}} as L{Fsum}.
940 @see: Method L{Fsum.__isub__}.
941 '''
942 f = self._copy_2r(other, self.__rsub__)
943 return f._fsub(self, _sub_op_)
945 def __rtruediv__(self, other, **raiser_RESIDUAL):
946 '''Return C{B{other} / B{self}} as an L{Fsum}.
948 @see: Method L{Fsum.__itruediv__}.
949 '''
950 f = self._copy_2r(other, self.__rtruediv__)
951 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL)
953 def __str__(self):
954 '''Return the default C{str(self)}.
955 '''
956 return self.toStr(lenc=True)
958 def __sub__(self, other):
959 '''Return C{B{self} - B{other}} as an L{Fsum}.
961 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}.
963 @return: The difference (L{Fsum}).
965 @see: Method L{Fsum.__isub__}.
966 '''
967 f = self._copy_2(self.__sub__)
968 return f._fsub(other, _sub_op_)
970 def __truediv__(self, other, **raiser_RESIDUAL):
971 '''Return C{B{self} / B{other}} as an L{Fsum}.
973 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor.
974 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
975 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
976 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
978 @return: The quotient (L{Fsum}).
980 @raise ResidualError: Non-zero, significant residual or invalid
981 B{C{RESIDUAL}}.
983 @see: Method L{Fsum.__itruediv__}.
984 '''
985 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL)
987 __trunc__ = __int__
989 if _sys_version_info2 < (3, 0): # PYCHOK no cover
990 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
991 __div__ = __truediv__
992 __idiv__ = __itruediv__
993 __long__ = __int__
994 __nonzero__ = __bool__
995 __rdiv__ = __rtruediv__
997 def as_integer_ratio(self):
998 '''Return this instance as the ratio of 2 integers.
1000 @return: 2-Tuple C{(numerator, denominator)} both C{int} with
1001 C{numerator} signed and C{denominator} non-zero and
1002 positive. The C{numerator} is I{non-finite} if this
1003 instance is.
1005 @see: Method L{Fsum.fint2} and C{float.as_integer_ratio} in
1006 Python 2.7+.
1007 '''
1008 n, r = self._fint2
1009 if r:
1010 i, d = float(r).as_integer_ratio()
1011 n *= d
1012 n += i
1013 else: # PYCHOK no cover
1014 d = 1
1015 return n, d
1017 @property_RO
1018 def as_iscalar(self):
1019 '''Get this instance I{as-is} (L{Fsum} with C{non-zero residual},
1020 C{scalar} or I{non-finite}).
1021 '''
1022 s, r = self._fprs2
1023 return self if r else s
1025 @property_RO
1026 def ceil(self):
1027 '''Get this instance' C{ceil} value (C{int} in Python 3+, but
1028 C{float} in Python 2-).
1030 @note: This C{ceil} takes the C{residual} into account.
1032 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
1033 L{Fsum.imag} and L{Fsum.real}.
1034 '''
1035 s, r = self._fprs2
1036 c = _ceil(s) + int(r) - 1
1037 while r > (c - s): # (s + r) > c
1038 c += 1
1039 return c # _ceil(self._n_d)
1041 cmp = __cmp__
1043 def _cmp_0(self, other, op):
1044 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
1045 '''
1046 if _isFsumTuple(other):
1047 s = self._ps_1sum(*other._ps)
1048 elif self._scalar(other, op):
1049 s = self._ps_1sum(other)
1050 else:
1051 s = self.signOf() # res=True
1052 return s
1054 def copy(self, deep=False, **name):
1055 '''Copy this instance, C{shallow} or B{C{deep}}.
1057 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}).
1059 @return: The copy (L{Fsum}).
1060 '''
1061 n = _name__(name, name__=self.copy)
1062 f = _Named.copy(self, deep=deep, name=n)
1063 if f._ps is self._ps:
1064 f._ps = list(self._ps) # separate list
1065 if not deep:
1066 f._n = 1
1067 # assert f._f2product == self._f2product
1068 # assert f._Fsum is f
1069 return f
1071 def _copy_2(self, which, name=NN):
1072 '''(INTERNAL) Copy for I{dyadic} operators.
1073 '''
1074 n = name or which.__name__ # _dunder_nameof
1075 # NOT .classof due to .Fdot(a, *b) args, etc.
1076 f = _Named.copy(self, deep=False, name=n)
1077 f._ps = list(self._ps) # separate list
1078 # assert f._n == self._n
1079 # assert f._f2product == self._f2product
1080 # assert f._Fsum is f
1081 return f
1083 def _copy_2r(self, other, which):
1084 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
1085 '''
1086 return other._copy_2(which) if _isFsum(other) else \
1087 self._copy_2(which)._fset(other)
1089 divmod = __divmod__
1091 def _Error(self, op, other, Error, **txt_cause):
1092 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
1093 '''
1094 return Error(_SPACE_(self.as_iscalar, op, other), **txt_cause)
1096 def _ErrorX(self, X, op, other, *mod):
1097 '''(INTERNAL) Format the caught exception C{X}.
1098 '''
1099 E, t = _xError2(X)
1100 if mod:
1101 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
1102 return self._Error(op, other, E, txt=t, cause=X)
1104 def _ErrorXs(self, X, xs, **kwds): # in .fmath
1105 '''(INTERNAL) Format the caught exception C{X}.
1106 '''
1107 E, t = _xError2(X)
1108 u = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
1109 return E(u, txt=t, cause=X)
1111 def _facc(self, xs, up=True, **origin_X_x):
1112 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s.
1113 '''
1114 if xs:
1115 kwds = _xkwds(self._isfine, **origin_X_x)
1116 _xs = _2floats(xs, **kwds) # PYCHOK yield
1117 ps = self._ps
1118 ps[:] = self._ps_acc(list(ps), _xs, up=up)
1119 return self
1121 def _facc_args(self, xs, **up):
1122 '''(INTERNAL) Accumulate 0, 1 or more C{xs}, all positional
1123 arguments in the caller of this method.
1124 '''
1125 return self._facc(xs, origin=1, **up) if len(xs) != 1 else \
1126 self._fadd(xs[0], _add_op_, **up)
1128 def _facc_neg(self, xs, **up_origin):
1129 '''(INTERNAL) Accumulate more C{xs}, negated.
1130 '''
1131 def _N(X):
1132 return X._ps_neg
1134 def _n(x):
1135 return -float(x)
1137 return self._facc(xs, _X=_N, _x=_n, **up_origin)
1139 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath
1140 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
1141 '''
1142 def _Pow4(p):
1143 r = 0
1144 if _isFsumTuple(p):
1145 s, r = p._fprs2
1146 if r:
1147 m = Fsum._pow
1148 else: # scalar
1149 return _Pow4(s)
1150 elif isint(p, both=True) and int(p) >= 0:
1151 p = s = int(p)
1152 m = Fsum._pow_int
1153 else:
1154 p = s = _2float(power=p, **self._isfine)
1155 m = Fsum._pow_scalar
1156 return m, p, s, r
1158 _Pow, p, s, r = _Pow4(power)
1159 if p: # and xs:
1160 op = which.__name__
1161 _FsT = _Fsum_Fsum2Tuple_types
1162 _pow = self._pow_2_3
1164 def _P(X):
1165 f = _Pow(X, p, power, op, **raiser_RESIDUAL)
1166 return f._ps if isinstance(f, _FsT) else (f,)
1168 def _p(x):
1169 x = float(x)
1170 f = _pow(x, s, power, op, **raiser_RESIDUAL)
1171 if f and r:
1172 f *= _pow(x, r, power, op, **raiser_RESIDUAL)
1173 return f
1175 f = self._facc(xs, origin=1, _X=_P, _x=_p)
1176 else:
1177 f = self._facc_scalar_(float(len(xs))) # x**0 == 1
1178 return f
1180 def _facc_scalar(self, xs, **up):
1181 '''(INTERNAL) Accumulate all C{xs}, known to be scalar.
1182 '''
1183 if xs:
1184 _ = self._ps_acc(self._ps, xs, **up)
1185 return self
1187 def _facc_scalar_(self, *xs, **up):
1188 '''(INTERNAL) Accumulate all positional C{xs}, known to be scalar.
1189 '''
1190 if xs:
1191 _ = self._ps_acc(self._ps, xs, **up)
1192 return self
1194# def _facc_up(self, up=True):
1195# '''(INTERNAL) Update the C{partials}, by removing
1196# and re-accumulating the final C{partial}.
1197# '''
1198# ps = self._ps
1199# while len(ps) > 1:
1200# p = ps.pop()
1201# if p:
1202# n = self._n
1203# _ = self._ps_acc(ps, (p,), up=False)
1204# self._n = n
1205# break
1206# return self._update() if up else self
1208 def fadd(self, xs=()):
1209 '''Add an iterable's items to this instance.
1211 @arg xs: Iterable of items to add (each C{scalar}
1212 or an L{Fsum} or L{Fsum2Tuple} instance).
1214 @return: This instance (L{Fsum}).
1216 @raise OverflowError: Partial C{2sum} overflow.
1218 @raise TypeError: An invalid B{C{xs}} item.
1220 @raise ValueError: Invalid or I{non-finite} B{C{xs}} value.
1221 '''
1222 if _isFsumTuple(xs):
1223 self._facc_scalar(xs._ps)
1224 elif isscalar(xs): # for backward compatibility # PYCHOK no cover
1225 x = _2float(x=xs, **self._isfine)
1226 self._facc_scalar_(x)
1227 elif xs: # _xiterable(xs)
1228 self._facc(xs)
1229 return self
1231 def fadd_(self, *xs):
1232 '''Add all positional items to this instance.
1234 @arg xs: Values to add (each C{scalar} or an L{Fsum}
1235 or L{Fsum2Tuple} instance), all positional.
1237 @see: Method L{Fsum.fadd} for further details.
1238 '''
1239 return self._facc_args(xs)
1241 def _fadd(self, other, op, **up): # in .fmath.Fhorner
1242 '''(INTERNAL) Apply C{B{self} += B{other}}.
1243 '''
1244 if _isFsumTuple(other):
1245 if self._ps:
1246 self._facc_scalar(other._ps, **up)
1247 else:
1248 self._fset(other, op=op, **up)
1249 elif self._scalar(other, op):
1250 if self._ps:
1251 self._facc_scalar_(other, **up)
1252 else:
1253 self._fset(other, op=op, **up)
1254 return self
1256 fcopy = copy # for backward compatibility
1257 fdiv = __itruediv__
1258 fdivmod = __divmod__
1260 def _fdivmod2(self, other, op, **raiser_RESIDUAL):
1261 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
1262 '''
1263 # result mostly follows CPython function U{float_divmod
1264 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
1265 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
1266 q = self._truediv(other, op, **raiser_RESIDUAL).floor
1267 if q: # == float // other == floor(float / other)
1268 self -= self._Fsum_as(q) * other # NOT other * q!
1270 s = signOf(other) # make signOf(self) == signOf(other)
1271 if s and self.signOf() == -s: # PYCHOK no cover
1272 self += other
1273 q -= 1
1274# t = self.signOf()
1275# if t and t != s:
1276# raise self._Error(op, other, _AssertionError, txt__=signOf)
1277 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
1279 def _fhorner(self, x, cs, op, incx=True): # in .fmath
1280 '''(INTERNAL) Add an L{Fhorner} evaluation of polynomial
1281 C{sum(cs[i] * B{x}**i for i=0..len(cs)-1) if B{incx}
1282 else sum(... i=len(cs)-1..0)}.
1283 '''
1284 if _xiterablen(cs):
1285 H = self._Fsum_as(name__=self._fhorner)
1286 if _isFsumTuple(x):
1287 _mul = H._mul_Fsum
1288 else:
1289 _mul = H._mul_scalar
1290 x = _2float(x=x, **self._isfine)
1291 if len(cs) > 1 and x:
1292 for c in (reversed(cs) if incx else cs):
1293 H._fset_ps(_mul(x, op))
1294 H._fadd(c, op, up=False)
1295 else: # x == 0
1296 H = cs[0] if cs else _0_0
1297 self._fadd(H, op)
1298 return self
1300 def _finite(self, other, op=None):
1301 '''(INTERNAL) Return B{C{other}} if C{finite}.
1302 '''
1303 if _isOK_or_finite(other, **self._isfine):
1304 return other
1305 E = _NonfiniteError(other)
1306 raise self._Error(op, other, E, txt=_not_finite_)
1308 def fint(self, name=NN, **raiser_RESIDUAL):
1309 '''Return this instance' current running sum as C{integer}.
1311 @kwarg name: Optional, overriding C{B{name}="fint"} (C{str}).
1312 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1313 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1314 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1316 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer}
1317 with a zero or insignificant I{integer} residual.
1319 @raise ResidualError: Non-zero, significant residual or invalid
1320 B{C{RESIDUAL}}.
1322 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}.
1323 '''
1324 i, r = self._fint2
1325 if r:
1326 R = self._raiser(r, i, **raiser_RESIDUAL)
1327 if R:
1328 t = _stresidual(_integer_, r, **R)
1329 raise ResidualError(_integer_, i, txt=t)
1330 return self._Fsum_as(i, name=_name__(name, name__=self.fint))
1332 def fint2(self, **name):
1333 '''Return this instance' current running sum as C{int} and the
1334 I{integer} residual.
1336 @kwarg name: Optional name (C{str}).
1338 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1339 an C{int} and I{integer} C{residual} a C{float} or
1340 C{INT0} if the C{fsum} is considered to be I{exact}.
1341 The C{fsum} is I{non-finite} if this instance is.
1342 '''
1343 return Fsum2Tuple(*self._fint2, **name)
1345 @Property
1346 def _fint2(self): # see ._fset
1347 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1348 '''
1349 s, _ = self._fprs2
1350 try:
1351 i = int(s)
1352 r = (self._ps_1sum(i) if len(self._ps) > 1 else
1353 float(s - i)) or INT0
1354 except (OverflowError, ValueError) as X:
1355 r = 0 # INF, NAN, NINF
1356 i = self._fintX(X, sum(self._ps))
1357 return i, r # Fsum2Tuple?
1359 @_fint2.setter_ # PYCHOK setter_UNDERscore!
1360 def _fint2(self, s): # in _fset
1361 '''(INTERNAL) Replace the C{_fint2} value.
1362 '''
1363 try:
1364 i = int(s)
1365 r = (s - i) or INT0
1366 except (OverflowError, ValueError) as X:
1367 r = 0 # INF, NAN, NINF
1368 i = self._fintX(X, float(s))
1369 return i, r # like _fint2.getter
1371 def _fintX(self, X, i): # PYCHOK X
1372 '''(INTERNAL) Handle I{non-finite} C{int}.
1373 '''
1374 # "cannot convert float infinity to integer"
1375 return i # ignore such Overflow-/ValueErrors
1376 # op = int.__name__
1377 # return self._nonfiniteX(X, op, i)
1379 @deprecated_property_RO
1380 def float_int(self): # PYCHOK no cover
1381 '''DEPRECATED, use method C{Fsum.int_float}.'''
1382 return self.int_float() # raiser=False
1384 @property_RO
1385 def floor(self):
1386 '''Get this instance' C{floor} (C{int} in Python 3+, but
1387 C{float} in Python 2-).
1389 @note: This C{floor} takes the C{residual} into account.
1391 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1392 L{Fsum.imag} and L{Fsum.real}.
1393 '''
1394 s, r = self._fprs2
1395 f = _floor(s) + _floor(r) + 1
1396 while (f - s) > r: # f > (s + r)
1397 f -= 1
1398 return f # _floor(self._n_d)
1400# ffloordiv = __ifloordiv__ # for naming consistency?
1401# floordiv = __floordiv__ # for naming consistency?
1403 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv?
1404 '''Apply C{B{self} //= B{other}}.
1405 '''
1406 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self
1407 return self._fset(q.floor) # floor(q)
1409 def fma(self, other1, other2, raiser=False): # in .fmath.fma
1410 '''Fused-multiply-add C{self *= B{other1}; self += B{other2}}.
1412 @arg other1: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1413 @arg other2: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
1414 @kwarg raiser: If C{True}, throw an exception, otherwise pass
1415 the I{non-finite} result (C{bool}).
1417 @note: Uses C{math.fma} in Python 3.13+, provided C{self},
1418 B{C{other1}} and B{C{other2}} are all C{scalar}.
1419 '''
1420 f, r = self._fprs2
1421 if r == 0 and isscalar(other1, both=True) \
1422 and isscalar(other2, both=True):
1423 try:
1424 f = _fma(f, other1, other2)
1425 except (OverflowError, TypeError, ValueError) as X: # from math.fma
1426 op = self.fma.__name__ # INF, NAN, NINF
1427 f = self._mul_reduce(op, f, other1)
1428 f = _sum(self._ps_other(op, f, other2))
1429 if raiser:
1430 f = self._nonfiniteX(X, op, f)
1431 else:
1432 f = self._f2mul(self.fma, other1, raiser=raiser)
1433 f += other2
1434 return self._fset(f)
1436 fmul = __imul__
1438 def _fmul(self, other, op):
1439 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1440 '''
1441 if _isFsumTuple(other):
1442 if len(self._ps) != 1:
1443 f = self._mul_Fsum(other, op)
1444 elif len(other._ps) != 1: # and len(self._ps) == 1
1445 f = self._ps_mul(op, *other._ps)
1446 elif self._f2product: # len(other._ps) == 1
1447 f = self._mul_scalar(other._ps[0], op)
1448 else: # len(other._ps) == len(self._ps) == 1
1449 f = self._finite(self._ps[0] * other._ps[0], op=op)
1450 else:
1451 s = self._scalar(other, op)
1452 f = self._mul_scalar(s, op)
1453 return self._fset(f) # n=len(self) + 1
1455 @deprecated_method
1456 def f2mul(self, *others, **raiser):
1457 '''DEPRECATED on 2024.09.13, use method L{f2mul_<Fsum.f2mul_>}.'''
1458 return self._fset(self.f2mul_(*others, **raiser))
1460 def f2mul_(self, *others, **raiser): # in .fmath.f2mul
1461 '''Return C{B{self} * B{other} * B{other} ...} for all B{C{others}} using cascaded,
1462 accurate multiplication like with L{f2product<Fsum.f2product>} set to C{True}.
1464 @arg others: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all
1465 positional.
1466 @kwarg raiser: Keyword argument C{B{raiser}=False}, if C{True}, throw an exception,
1467 otherwise pass the I{non-finite} result (C{bool}).
1469 @return: The cascaded I{TwoProduct} (L{Fsum} or C{float}).
1471 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}
1472 '''
1473 return self._f2mul(self.f2mul_, *others, **raiser)
1475 def _f2mul(self, where, *others, **raiser):
1476 '''(INTERNAL) See methods C{fma} and C{f2mul_}.
1477 '''
1478 f = self._copy_2(where)
1479 if others:
1480 op = where.__name__
1481 ps = f._ps
1482 if ps:
1483 try:
1484 for p in self._ps_other(op, *others):
1485 pfs = _2products(p, _2split3s(ps))
1486 ps[:] = f._ps_acc([], pfs, up=False)
1487 f._update()
1488 except (OverflowError, TypeError, ValueError) as X:
1489 r = self._mul_reduce(op, _sum(ps), *others) # INF, NAN, NINF
1490 if _xkwds_get1(raiser, raiser=False):
1491 r = self._nonfiniteX(X, op, r)
1492 f._fset(r)
1493 return f
1495 def fover(self, over, **raiser_RESIDUAL):
1496 '''Apply C{B{self} /= B{over}} and summate.
1498 @arg over: An L{Fsum} or C{scalar} denominator.
1499 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1500 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1501 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1503 @return: Precision running sum (C{float}).
1505 @raise ResidualError: Non-zero, significant residual or invalid
1506 B{C{RESIDUAL}}.
1508 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1509 '''
1510 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs)
1512 fpow = __ipow__
1514 def _fpow(self, other, op, *mod, **raiser_RESIDUAL):
1515 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1516 '''
1517 if mod:
1518 if mod[0] is not None: # == 3-arg C{pow}
1519 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL)
1520 elif self.is_integer():
1521 # return an exact C{int} for C{int}**C{int}
1522 i, _ = self._fint2 # assert _ == 0
1523 x, r = _2scalar2(other) # C{int}, C{float} or other
1524 f = self._Fsum_as(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \
1525 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL)
1526 else: # mod[0] is None, power(self, other)
1527 f = self._pow(other, other, op, **raiser_RESIDUAL)
1528 else: # pow(self, other)
1529 f = self._pow(other, other, op, **raiser_RESIDUAL)
1530 return self._fset(f) # n=max(len(self), 1)
1532 def f2product(self, *two):
1533 '''Get and set accurate I{TwoProduct} multiplication for this
1534 L{Fsum}, I{overriding the global setting} from function
1535 L{f2product<fsums.f2product>}.
1537 @arg two: If omitted, leave the override unchanged, if C{True},
1538 turn I{TwoProduct} on, if C{False} off, if C{None}e
1539 remove th override (C{bool} or C{None}).
1541 @return: The previous setting (C{bool} or C{None} if not set).
1543 @see: Function L{f2product<fsums.f2product>}.
1545 @note: Use C{f.f2product() or f2product()} to determine whether
1546 multiplication is accurate for L{Fsum} C{f}.
1547 '''
1548 if two: # delattrof(self, _f2product=None)
1549 t = _xkwds_pop(self.__dict__, _f2product=None)
1550 if two[0] is not None:
1551 self._f2product = bool(two[0])
1552 else: # getattrof(self, _f2product=None)
1553 t = _xkwds_get(self.__dict__, _f2product=None)
1554 return t
1556 @Property
1557 def _fprs(self):
1558 '''(INTERNAL) Get and cache this instance' precision
1559 running sum (C{float} or C{int}), ignoring C{residual}.
1561 @note: The precision running C{fsum} after a C{//=} or
1562 C{//} C{floor} division is C{int} in Python 3+.
1563 '''
1564 s, _ = self._fprs2
1565 return s # ._fprs2.fsum
1567 @_fprs.setter_ # PYCHOK setter_underscore!
1568 def _fprs(self, s):
1569 '''(INTERNAL) Replace the C{_fprs} value.
1570 '''
1571 return s
1573 @Property
1574 def _fprs2(self):
1575 '''(INTERNAL) Get and cache this instance' precision
1576 running sum and residual (L{Fsum2Tuple}).
1577 '''
1578 ps = self._ps
1579 try:
1580 n = len(ps) - 2
1581 if n > 0: # len(ps) > 2
1582 s = _psum(ps, **self._isfine)
1583 n = len(ps) - 2
1584 if n > 0:
1585 r = self._ps_1sum(s)
1586 return Fsum2Tuple(*_s_r(s, r))
1587 if n == 0: # len(ps) == 2
1588 s, r = _s_r(*_2sum(*ps, **self._isfine))
1589 ps[:] = (r, s) if r else (s,)
1590 elif ps: # len(ps) == 1
1591 s, r = ps[0], INT0
1592 else: # len(ps) == 0
1593 s, r = _0_0, INT0
1594 ps[:] = s,
1595 except (OverflowError, ValueError) as X:
1596 op = _sum.__name__ # INF, NAN, NINF
1597 s = self._nonfiniteX(X, op, _sum(self._ps))
1598 r = _0_0
1599 # assert self._ps is ps
1600 return Fsum2Tuple(s, r)
1602 @_fprs2.setter_ # PYCHOK setter_underscore!
1603 def _fprs2(self, s_r):
1604 '''(INTERNAL) Replace the C{_fprs2} value.
1605 '''
1606 return Fsum2Tuple(s_r)
1608 def fset_(self, *xs):
1609 '''Apply C{B{self}.partials = Fsum(*B{xs}).partials}.
1611 @arg xs: Optional, new values (each C{scalar} or
1612 an L{Fsum} or L{Fsum2Tuple} instance), all
1613 positional.
1615 @return: This instance, replaced (C{Fsum}).
1617 @see: Method L{Fsum.fadd} for further details.
1618 '''
1619 return self._fset(xs[0], op=_fset_op_) if len(xs) == 1 else \
1620 self._fset(_0_0)._facc_args(xs)
1622 def _fset(self, other, n=0, up=True, **op):
1623 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1624 '''
1625 if other is self:
1626 pass # from ._fmul, ._ftruediv and ._pow_0_1
1627 elif _isFsumTuple(other):
1628 self._ps[:] = other._ps
1629 self._n = n or other._n
1630 if up: # use or zap the C{Property_RO} values
1631 Fsum._fint2._update_from(self, other)
1632 Fsum._fprs ._update_from(self, other)
1633 Fsum._fprs2._update_from(self, other)
1634 elif isscalar(other):
1635 s = float(self._finite(other, **op)) if op else other
1636 self._ps[:] = s,
1637 self._n = n or 1
1638 if up: # Property _fint2, _fprs and _fprs2 all have
1639 # @.setter_underscore and NOT @.setter because the
1640 # latter's _fset zaps the value set by @.setter
1641 self._fint2 = s
1642 self._fprs = s
1643 self._fprs2 = s, INT0
1644 # assert self._fprs is s
1645 else:
1646 op = _xkwds_get1(op, op=_fset_op_)
1647 raise self._Error(op, other, _TypeError)
1648 return self
1650 def _fset_ps(self, other): # in .fmath._Fsum__init__
1651 '''(INTERNAL) Set partials from a known C{other}.
1652 '''
1653 return self._fset(other, up=False)
1655 def fsub(self, xs=()):
1656 '''Subtract an iterable's items from this instance.
1658 @see: Method L{Fsum.fadd} for further details.
1659 '''
1660 return self._facc_neg(xs)
1662 def fsub_(self, *xs):
1663 '''Subtract all positional items from this instance.
1665 @see: Method L{Fsum.fadd_} for further details.
1666 '''
1667 return self._facc_neg(xs, origin=1) if len(xs) != 1 else \
1668 self._fsub(xs[0], _sub_op_)
1670 def _fsub(self, other, op):
1671 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1672 '''
1673 if _isFsumTuple(other):
1674 if other is self: # or other._fprs2 == self._fprs2:
1675 self._fset(_0_0, n=len(self) * 2)
1676 elif other._ps:
1677 self._facc_scalar(other._ps_neg)
1678 elif self._scalar(other, op):
1679 self._facc_scalar_(-other)
1680 return self
1682 def fsum(self, xs=()):
1683 '''Add an iterable's items, summate and return the
1684 current precision running sum.
1686 @arg xs: Iterable of items to add (each item C{scalar}
1687 or an L{Fsum} or L{Fsum2Tuple} instance).
1689 @return: Precision running sum (C{float} or C{int}).
1691 @see: Method L{Fsum.fadd}.
1693 @note: Accumulation can continue after summation.
1694 '''
1695 return self._facc(xs)._fprs
1697 def fsum_(self, *xs):
1698 '''Add any positional items, summate and return the
1699 current precision running sum.
1701 @arg xs: Items to add (each C{scalar} or an L{Fsum}
1702 or L{Fsum2Tuple} instance), all positional.
1704 @return: Precision running sum (C{float} or C{int}).
1706 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}.
1707 '''
1708 return self._facc_args(xs)._fprs
1710 def Fsum_(self, *xs, **name):
1711 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}.
1713 @kwarg name: Optional name (C{str}).
1715 @return: Copy of this updated instance (L{Fsum}).
1716 '''
1717 return self._facc_args(xs)._copy_2(self.Fsum_, **name)
1719 def Fsum2Tuple_(self, *xs, **name):
1720 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}.
1722 @kwarg name: Optional name (C{str}).
1724 @return: Precision running sum (L{Fsum2Tuple}).
1725 '''
1726 return Fsum2Tuple(self._facc_args(xs)._fprs2, **name)
1728 @property_RO
1729 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, for C{_2floats}, .fstats
1730 return self # NOT @Property_RO, see .copy and ._copy_2
1732 def _Fsum_as(self, *xs, **name_f2product_nonfinites_RESIDUAL):
1733 '''(INTERNAL) Return an C{Fsum} with this C{Fsum}'s C{.f2product},
1734 C{.nonfinites} and C{.RESIDUAL} setting, optionally
1735 overridden with C{name_f2product_nonfinites_RESIDUAL} and
1736 with any C{xs} accumulated.
1737 '''
1738 kwds = _xkwds_not(None, Fsum._RESIDUAL, f2product =self.f2product(),
1739 nonfinites=self.nonfinites(),
1740 RESIDUAL =self.RESIDUAL())
1741 if name_f2product_nonfinites_RESIDUAL: # overwrites
1742 kwds.update(name_f2product_nonfinites_RESIDUAL)
1743 F = Fsum(**kwds)
1744 # assert all(v == self.__dict__[n] for n, v in F.__dict__.items())
1745 return F._fset(xs[0]) if len(xs) == 1 else (
1746 F._facc(xs, up=False) if xs else F)
1748 def fsum2(self, xs=(), **name):
1749 '''Add an iterable's items, summate and return the
1750 current precision running sum I{and} the C{residual}.
1752 @arg xs: Iterable of items to add (each item C{scalar}
1753 or an L{Fsum} or L{Fsum2Tuple} instance).
1754 @kwarg name: Optional C{B{name}=NN} (C{str}).
1756 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1757 current precision running sum and C{residual}, the
1758 (precision) sum of the remaining C{partials}. The
1759 C{residual is INT0} if the C{fsum} is considered
1760 to be I{exact}.
1762 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1763 '''
1764 t = self._facc(xs)._fprs2
1765 return t.dup(name=name) if name else t
1767 def fsum2_(self, *xs):
1768 '''Add any positional items, summate and return the current
1769 precision running sum and the I{differential}.
1771 @arg xs: Values to add (each C{scalar} or an L{Fsum} or
1772 L{Fsum2Tuple} instance), all positional.
1774 @return: 2Tuple C{(fsum, delta)} with the current, precision
1775 running C{fsum} like method L{Fsum.fsum} and C{delta},
1776 the difference with previous running C{fsum}, C{float}.
1778 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1779 '''
1780 return self._fsum2(xs, self._facc_args)
1782 def _fsum2(self, xs, _facc, **origin):
1783 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}.
1784 '''
1785 p, q = self._fprs2
1786 if xs:
1787 s, r = _facc(xs, **origin)._fprs2
1788 if _isfinite(s): # _fsum(_1primed((s, -p, r, -q))
1789 d, r = _2sum(s - p, r - q, _isfine=_isOK)
1790 r, _ = _s_r(d, r)
1791 return s, (r if _isfinite(r) else _0_0)
1792 else:
1793 return p, _0_0
1795 def fsumf_(self, *xs):
1796 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1797 '''
1798 return self._facc_scalar(xs)._fprs
1800 def Fsumf_(self, *xs):
1801 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.
1802 '''
1803 return self._facc_scalar(xs)._copy_2(self.Fsumf_)
1805 def fsum2f_(self, *xs):
1806 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}} are I{known to be scalar}.
1807 '''
1808 return self._fsum2(xs, self._facc_scalar, origin=1)
1810# ftruediv = __itruediv__ # for naming consistency?
1812 def _ftruediv(self, other, op, **raiser_RESIDUAL):
1813 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1814 '''
1815 n = _1_0
1816 if _isFsumTuple(other):
1817 if other is self or self == other:
1818 return self._fset(n, n=len(self))
1819 d, r = other._fprs2
1820 if r:
1821 R = self._raiser(r, d, **raiser_RESIDUAL)
1822 if R:
1823 raise self._ResidualError(op, other, r, **R)
1824 d, n = other.as_integer_ratio()
1825 else:
1826 d = self._scalar(other, op)
1827 try:
1828 s = n / d
1829 except Exception as X:
1830 raise self._ErrorX(X, op, other)
1831 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN
1832 return self._fset(f)
1834 @property_RO
1835 def imag(self):
1836 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1838 @see: Property L{Fsum.real}.
1839 '''
1840 return _0_0
1842 def int_float(self, **raiser_RESIDUAL):
1843 '''Return this instance' current running sum as C{int} or C{float}.
1845 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1846 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1847 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1849 @return: This C{integer} sum if this instance C{is_integer},
1850 otherwise return the C{float} sum if the residual is
1851 zero or not significant.
1853 @raise ResidualError: Non-zero, significant residual or invalid
1854 B{C{RESIDUAL}}.
1856 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.is_integer},
1857 L{Fsum.RESIDUAL} and property L{Fsum.as_iscalar}.
1858 '''
1859 s, r = self._fint2
1860 if r:
1861 s, r = self._fprs2
1862 if r: # PYCHOK no cover
1863 R = self._raiser(r, s, **raiser_RESIDUAL)
1864 if R:
1865 t = _stresidual(_non_zero_, r, **R)
1866 raise ResidualError(int_float=s, txt=t)
1867 s = float(s)
1868 return s
1870 def is_exact(self):
1871 '''Is this instance' running C{fsum} considered to be exact?
1872 (C{bool}), C{True} only if the C{residual is }L{INT0}.
1873 '''
1874 return self.residual is INT0
1876 def is_finite(self): # in .constants
1877 '''Is this instance C{finite}? (C{bool}).
1879 @see: Function L{isfinite<pygeodesy.isfinite>}.
1880 '''
1881 return _isfinite(_sum(self._ps)) # _sum(self)
1883 def is_integer(self):
1884 '''Is this instance' running sum C{integer}? (C{bool}).
1886 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}.
1887 '''
1888 s, r = self._fint2
1889 return False if r else (_isfinite(s) and isint(s))
1891 def is_math_fma(self):
1892 '''Is accurate L{f2product} multiplication based on Python's C{math.fma}?
1894 @return: C{True} if accurate multiplication uses C{math.fma}, C{False}
1895 an C{fma} implementation as C{math.fma} or C{None}, a previous
1896 C{PyGeodesy} implementation.
1897 '''
1898 return (_fma.__module__ is fabs.__module__ or None) if _2split3s is _passarg else False
1900 def is_math_fsum(self):
1901 '''Are the summation functions L{fsum}, L{fsum_}, L{fsumf_}, L{fsum1},
1902 L{fsum1_} and L{fsum1f_} based on Python's C{math.fsum}?
1904 @return: C{True} if summation functions use C{math.fsum}, C{False}
1905 otherwise.
1906 '''
1907 return _sum is _fsum # _fsum.__module__ is fabs.__module__
1909 def is_scalar(self, **raiser_RESIDUAL):
1910 '''Is this instance' running sum C{scalar} without residual or with
1911 a residual I{ratio} not exceeding the RESIDUAL threshold?
1913 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
1914 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
1915 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
1917 @return: C{True} if this instance' non-zero residual C{ratio} exceeds
1918 the L{RESIDUAL<Fsum.RESIDUAL>} threshold (C{bool}).
1920 @raise ResidualError: Non-zero, significant residual or invalid
1921 B{C{RESIDUAL}}.
1923 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property
1924 L{Fsum.as_iscalar}.
1925 '''
1926 s, r = self._fprs2
1927 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True
1929 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1930 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}.
1931 '''
1932 # assert _isFsumTuple(other)
1933 if self._ps and other._ps:
1934 f = self._ps_mul(op, *other._ps) # NO .as_iscalar!
1935 else:
1936 f = _0_0
1937 return f
1939 def _mul_reduce(self, op, start, *others):
1940 '''(INTERNAL) Like fmath.freduce(_operator.mul, ...)
1941 for I{non-finite} C{start} and/or C{others}.
1942 '''
1943 for p in self._ps_other(op, *others):
1944 start *= p
1945 return start
1947 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1948 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.
1949 '''
1950 # assert isscalar(factor)
1951 if self._ps and self._finite(factor, op):
1952 f = self if factor == _1_0 else (
1953 self._neg if factor == _N_1_0 else
1954 self._ps_mul(op, factor).as_iscalar)
1955 else:
1956 f = _0_0
1957 return f
1959# @property_RO
1960# def _n_d(self):
1961# n, d = self.as_integer_ratio()
1962# return n / d
1964 @property_RO
1965 def _neg(self):
1966 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.
1967 '''
1968 return _Psum(self._ps_neg) if self._ps else NEG0
1970 def nonfinites(self, *OK):
1971 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan}
1972 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively
1973 C{ValueError} exceptions, I{overriding the global setting} from
1974 function L{nonfiniterrors<fsums.nonfiniterrors>}.
1976 @arg OK: If omitted, leave the override unchanged, if C{True},
1977 I{non-finites} are C{OK}, if C{False} throw exceptions
1978 or if C{None} remove the override (C{bool} or C{None}).
1980 @return: The previous setting (C{bool} or C{None} if not set).
1982 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}.
1984 @note: Use C{f.nonfinites() or not nonfiniterrors()} to determine
1985 whether L{Fsum} C{f} handles I{non-finites}.
1986 '''
1987 _ks = Fsum._nonfinites_isfine_kwds
1988 if OK: # delattrof(self, _isfine=None)
1989 k = _xkwds_pop(self.__dict__, _isfine=None)
1990 if OK[0] is not None:
1991 self._isfine = _ks[bool(OK[0])]
1992 else: # getattrof(self, _isfine=None)
1993 k = _xkwds_get(self.__dict__, _isfine=None)
1994 # dict(map(reversed, _ks.items())).get(k, None)
1995 # raises a TypeError: unhashable type: 'dict'
1996 return True if k is _ks[True] else (
1997 False if k is _ks[False] else None)
1999 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK),
2000 False: dict(_isfine=_isfinite)}
2002 def _nonfiniteX(self, X, op, f):
2003 '''(INTERNAL) Handle a I{non-finite} exception.
2004 '''
2005 if not _isOK_or_finite(f, **self._isfine):
2006 raise self._ErrorX(X, op, f)
2007 return f
2009 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL):
2010 '''(INTERNAL) Re/set options from keyword arguments.
2011 '''
2012 if f2product is not None:
2013 self.f2product(f2product)
2014 if nonfinites is not None:
2015 self.nonfinites(nonfinites)
2016 if name_RESIDUAL: # MUST be last
2017 n, kwds = _name2__(**name_RESIDUAL)
2018 if kwds:
2019 R = Fsum._RESIDUAL
2020 t = _threshold(R, **kwds)
2021 if t != R:
2022 self._RESIDUAL = t
2023 if n:
2024 self.name = n # self.rename(n)
2026 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over
2027 '''(INTERNAL) Return C{Fsum(1) / B{x}}.
2028 '''
2029 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)
2031 @property_RO
2032 def partials(self):
2033 '''Get this instance' current, partial sums (C{tuple} of C{float}s).
2034 '''
2035 return tuple(self._ps)
2037 def pow(self, x, *mod, **raiser_RESIDUAL):
2038 '''Return C{B{self}**B{x}} as L{Fsum}.
2040 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2041 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
2042 C{pow(B{self}, B{other}, B{mod})} version.
2043 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore
2044 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}
2045 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2047 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
2048 result (L{Fsum}).
2050 @raise ResidualError: Non-zero, significant residual or invalid
2051 B{C{RESIDUAL}}.
2053 @note: If B{C{mod}} is given and C{None}, the result will be an
2054 C{integer} L{Fsum} provided this instance C{is_integer}
2055 or set to C{integer} by an L{Fsum.fint} call.
2057 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}
2058 and L{Fsum.root}.
2059 '''
2060 f = self._copy_2(self.pow)
2061 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)
2063 def _pow(self, other, unused, op, **raiser_RESIDUAL):
2064 '''Return C{B{self} ** B{other}}.
2065 '''
2066 if _isFsumTuple(other):
2067 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)
2068 elif self._scalar(other, op):
2069 x = self._finite(other, op)
2070 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2071 else:
2072 f = self._pow_0_1(0, other)
2073 return f
2075 def _pow_0_1(self, x, other):
2076 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
2077 '''
2078 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
2080 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):
2081 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},
2082 B{x}, int B{mod} or C{None})}, embellishing errors.
2083 '''
2085 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}
2086 m = mod[0]
2087 # assert _isFsumTuple(b)
2089 def _s(s, r):
2090 R = self._raiser(r, s, **raiser_RESIDUAL)
2091 if R:
2092 raise self._ResidualError(op, other, r, mod=m, **R)
2093 return s
2095 b = _s(*(b._fprs2 if m is None else b._fint2))
2096 x = _s(*_2scalar2(x))
2098 try:
2099 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)
2100 s = pow(b, x, *mod)
2101 if iscomplex(s):
2102 # neg**frac == complex in Python 3+, but ValueError in 2-
2103 raise ValueError(_strcomplex(s, b, x, *mod))
2104 return self._finite(s)
2105 except Exception as X:
2106 raise self._ErrorX(X, op, other, *mod)
2108 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):
2109 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsumTuple(other)}.
2110 '''
2111 # assert _isFsumTuple(other)
2112 x, r = other._fprs2
2113 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)
2114 if f and r:
2115 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)
2116 return f
2118 def _pow_int(self, x, other, op, **raiser_RESIDUAL):
2119 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
2120 '''
2121 # assert isint(x) and x >= 0
2122 ps = self._ps
2123 if len(ps) > 1:
2124 _mul_Fsum = Fsum._mul_Fsum
2125 if x > 4:
2126 p = self
2127 f = self if (x & 1) else self._Fsum_as(_1_0)
2128 m = x >> 1 # // 2
2129 while m:
2130 p = _mul_Fsum(p, p, op) # p **= 2
2131 if (m & 1):
2132 f = _mul_Fsum(f, p, op) # f *= p
2133 m >>= 1 # //= 2
2134 elif x > 1: # self**2, 3, or 4
2135 f = _mul_Fsum(self, self, op)
2136 if x > 2: # self**3 or 4
2137 p = self if x < 4 else f
2138 f = _mul_Fsum(f, p, op)
2139 else: # self**1 or self**0 == 1 or _1_0
2140 f = self._pow_0_1(x, other)
2141 elif ps: # self._ps[0]**x
2142 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)
2143 else: # PYCHOK no cover
2144 # 0**pos_int == 0, but 0**0 == 1
2145 f = 0 if x else 1
2146 return f
2148 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):
2149 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
2150 '''
2151 s, r = self._fprs2
2152 if r:
2153 # assert s != 0
2154 if isint(x, both=True): # self**int
2155 x = int(x)
2156 y = abs(x)
2157 if y > 1:
2158 f = self._pow_int(y, other, op, **raiser_RESIDUAL)
2159 if x > 0: # i.e. > 1
2160 return f # Fsum or scalar
2161 # assert x < 0 # i.e. < -1
2162 if _isFsum(f):
2163 s, r = f._fprs2
2164 if r:
2165 return self._1_Over(f, op, **raiser_RESIDUAL)
2166 else: # scalar
2167 s = f
2168 # use s**(-1) to get the CPython
2169 # float_pow error iff s is zero
2170 x = -1
2171 elif x < 0: # self**(-1)
2172 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self
2173 else: # self**1 or self**0
2174 return self._pow_0_1(x, other) # self, 1 or 1.0
2175 else: # self**fractional
2176 R = self._raiser(r, s, **raiser_RESIDUAL)
2177 if R:
2178 raise self._ResidualError(op, other, r, **R)
2179 n, d = self.as_integer_ratio()
2180 if abs(n) > abs(d):
2181 n, d, x = d, n, (-x)
2182 s = n / d
2183 # assert isscalar(s) and isscalar(x)
2184 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)
2186 def _ps_acc(self, ps, xs, up=True, **unused):
2187 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.
2188 '''
2189 n = 0
2190 _2s = _2sum
2191 _fi = self._isfine
2192 for x in (tuple(xs) if xs is ps else xs):
2193 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine)
2194 if x:
2195 i = 0
2196 for p in ps:
2197 x, p = _2s(x, p, **_fi)
2198 if p:
2199 ps[i] = p
2200 i += 1
2201 ps[i:] = (x,) if x else ()
2202 n += 1
2203 if n:
2204 self._n += n
2205# if _fi: # collapse ps if non-finite
2206# x = _sum(ps)
2207# if not _isfinite(x):
2208# ps[:] = x,
2209 # Fsum._ps_max = max(Fsum._ps_max, len(ps))
2210 if up:
2211 self._update()
2212 return ps
2214 def _ps_mul(self, op, *factors):
2215 '''(INTERNAL) Multiply this instance' C{partials} with
2216 each scalar C{factor} and accumulate into an C{Fsum}.
2217 '''
2218 def _psfs(ps, fs, _isfine=_isfinite):
2219 if len(ps) < len(fs):
2220 ps, fs = fs, ps
2221 if self._f2product:
2222 ps = _2split3s(ps)
2223 _fps = _2products
2224 else:
2225 def _fps(f, ps):
2226 return (f * p for p in ps)
2228 for f in fs:
2229 for p in _fps(f, ps):
2230 yield p if _isfine(p) else self._finite(p, op)
2232 F = self._Fsum_as(name=op) # assert F._ps is not self._ps
2233 _s = _psfs(self._ps, factors, **self._isfine)
2234 return F._facc_scalar(_s, up=False)
2236 @property_RO
2237 def _ps_neg(self):
2238 '''(INTERNAL) Yield the partials, I{negated}.
2239 '''
2240 for p in self._ps:
2241 yield -p
2243 def _ps_other(self, op, *others):
2244 '''(INTERNAL) Yield all C{other}s as C{scalar}.
2245 '''
2246 for other in others:
2247 if _isFsumTuple(other):
2248 for p in other._ps:
2249 yield p
2250 else:
2251 yield self._scalar(other, op)
2253 def _ps_1sum(self, *less):
2254 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.
2255 '''
2256 def _1psls(ps, ls):
2257 yield _1_0
2258 for p in ps:
2259 yield p
2260 for p in ls:
2261 yield -p
2262 yield _N_1_0
2264 return _fsum(_1psls(self._ps, less))
2266 def _raiser(self, r, s, raiser=True, **RESIDUAL):
2267 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold
2268 I{and} is residual C{r} I{non-zero} or I{significant} (for a
2269 negative respectively positive C{RESIDUAL} threshold)?
2270 '''
2271 if r and raiser:
2272 t = self._RESIDUAL
2273 if RESIDUAL:
2274 t = _threshold(t, **RESIDUAL)
2275 if t < 0 or (s + r) != s:
2276 q = (r / s) if s else s # == 0.
2277 if fabs(q) > fabs(t):
2278 return dict(ratio=q, R=t)
2279 return {}
2281 rdiv = __rtruediv__
2283 @property_RO
2284 def real(self):
2285 '''Get the C{real} part of this instance (C{float}).
2287 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
2288 and properties L{Fsum.ceil}, L{Fsum.floor},
2289 L{Fsum.imag} and L{Fsum.residual}.
2290 '''
2291 return float(self)
2293 @property_RO
2294 def residual(self):
2295 '''Get this instance' residual or residue (C{float} or C{int}):
2296 the C{sum(partials)} less the precision running sum C{fsum}.
2298 @note: The C{residual is INT0} iff the precision running
2299 C{fsum} is considered to be I{exact}.
2301 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
2302 '''
2303 return self._fprs2.residual
2305 def RESIDUAL(self, *threshold):
2306 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
2307 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
2309 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
2310 L{ResidualError}s in division and exponention, if
2311 C{None}, restore the default set with env variable
2312 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
2313 current setting.
2315 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.
2317 @raise ResidualError: Invalid B{C{threshold}}.
2319 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}
2320 C{residual / fsum} exceeds the given B{C{threshold}} and (2)
2321 the C{residual} is non-zero and (3) is I{significant} vs the
2322 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional
2323 keyword argument C{raiser=False} is missing. Specify a
2324 negative B{C{threshold}} for only non-zero C{residual}
2325 testing without the I{significant} case.
2326 '''
2327 r = self._RESIDUAL
2328 if threshold:
2329 t = threshold[0]
2330 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...
2331 (_0_0 if t else _1_0) if isbool(t) else
2332 _threshold(t)) # ... backward compatibility
2333 return r
2335 def _ResidualError(self, op, other, residual, **mod_R):
2336 '''(INTERNAL) Non-zero B{C{residual}} etc.
2337 '''
2338 def _p(mod=None, R=0, **unused): # ratio=0
2339 return (_non_zero_ if R < 0 else _significant_) \
2340 if mod is None else _integer_
2342 t = _stresidual(_p(**mod_R), residual, **mod_R)
2343 return self._Error(op, other, ResidualError, txt=t)
2345 def root(self, root, **raiser_RESIDUAL):
2346 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.
2348 @arg root: The order (C{scalar}, L{Fsum} or L{Fsum2Tuple}), non-zero.
2349 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any
2350 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar}
2351 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.
2353 @return: The C{self ** (1 / B{root})} result (L{Fsum}).
2355 @raise ResidualError: Non-zero, significant residual or invalid
2356 B{C{RESIDUAL}}.
2358 @see: Method L{Fsum.pow}.
2359 '''
2360 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL)
2361 f = self._copy_2(self.root)
2362 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)
2364 def _scalar(self, other, op, **txt):
2365 '''(INTERNAL) Return scalar C{other}.
2366 '''
2367 if isscalar(other):
2368 return other
2369 raise self._Error(op, other, _TypeError, **txt) # _invalid_
2371 def signOf(self, res=True):
2372 '''Determine the sign of this instance.
2374 @kwarg res: If C{True}, consider, otherwise ignore
2375 the residual (C{bool}).
2377 @return: The sign (C{int}, -1, 0 or +1).
2378 '''
2379 s, r = self._fprs2
2380 r = (-r) if res else 0
2381 return _signOf(s, r)
2383 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature
2384 '''Return this C{Fsum} instance as representation.
2386 @kwarg lenc_prec_sep_fmt: Optional keyword arguments
2387 for method L{Fsum.toStr}.
2389 @return: This instance (C{repr}).
2390 '''
2391 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))
2393 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature
2394 '''Return this C{Fsum} instance as string.
2396 @kwarg lenc: If C{True}, include the current C{[len]} of this
2397 L{Fsum} enclosed in I{[brackets]} (C{bool}).
2398 @kwarg prec_sep_fmt: Optional keyword arguments for method
2399 L{Fsum2Tuple.toStr}.
2401 @return: This instance (C{str}).
2402 '''
2403 p = self.classname
2404 if lenc:
2405 p = Fmt.SQUARE(p, len(self))
2406 n = _enquote(self.name, white=_UNDER_)
2407 t = self._fprs2.toStr(**prec_sep_fmt)
2408 return NN(p, _SPACE_, n, t)
2410 def _truediv(self, other, op, **raiser_RESIDUAL):
2411 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.
2412 '''
2413 f = self._copy_2(self.__truediv__)
2414 return f._ftruediv(other, op, **raiser_RESIDUAL)
2416 def _update(self, updated=True): # see ._fset
2417 '''(INTERNAL) Zap all cached C{Property_RO} values.
2418 '''
2419 if updated:
2420 _pop = self.__dict__.pop
2421 for p in _ROs:
2422 _ = _pop(p, None)
2423# Fsum._fint2._update(self)
2424# Fsum._fprs ._update(self)
2425# Fsum._fprs2._update(self)
2426 return self # for .fset_
2428_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update
2430if _NONFINITES: # PYCHOK no cover
2431 _ = nonfiniterrors(False)
2434def _Float_Int(arg, **name_Error):
2435 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit.
2436 '''
2437 U = Int if isint(arg) else Float
2438 return U(arg, **name_Error)
2441class DivMod2Tuple(_NamedTuple):
2442 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
2443 C{mod} results of a C{divmod} operation.
2445 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}
2446 in Python 2-. Remainder C{mod} an L{Fsum} instance.
2447 '''
2448 _Names_ = ('div', 'mod')
2449 _Units_ = (_Float_Int, Fsum)
2452class Fsum2Tuple(_NamedTuple): # in .fstats
2453 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
2454 and the C{residual}, the sum of the remaining partials. Each
2455 item is C{float} or C{int}.
2457 @note: If the C{residual is INT0}, the C{fsum} is considered
2458 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
2459 '''
2460 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
2461 _Units_ = (_Float_Int, _Float_Int)
2463 def __abs__(self): # in .fmath
2464 return self._Fsum.__abs__()
2466 def __bool__(self): # PYCHOK Python 3+
2467 return bool(self._Fsum)
2469 def __eq__(self, other):
2470 return self._other_op(other, self.__eq__)
2472 def __float__(self):
2473 return self._Fsum.__float__()
2475 def __ge__(self, other):
2476 return self._other_op(other, self.__ge__)
2478 def __gt__(self, other):
2479 return self._other_op(other, self.__gt__)
2481 def __le__(self, other):
2482 return self._other_op(other, self.__le__)
2484 def __lt__(self, other):
2485 return self._other_op(other, self.__lt__)
2487 def __int__(self):
2488 return self._Fsum.__int__()
2490 def __ne__(self, other):
2491 return self._other_op(other, self.__ne__)
2493 def __neg__(self):
2494 return self._Fsum.__neg__()
2496 __nonzero__ = __bool__ # Python 2-
2498 def __pos__(self):
2499 return self._Fsum.__pos__()
2501 def as_integer_ratio(self):
2502 '''Return this instance as the ratio of 2 integers.
2504 @see: Method L{Fsum.as_integer_ratio} for further details.
2505 '''
2506 return self._Fsum.as_integer_ratio()
2508 @property_RO
2509 def _fint2(self):
2510 return self._Fsum._fint2
2512 @property_RO
2513 def _fprs2(self):
2514 return self._Fsum._fprs2
2516 @Property_RO
2517 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats
2518 s, r = _s_r(*self)
2519 ps = (r, s) if r else (s,)
2520 return _Psum(ps, name=self.name)
2522 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL):
2523 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.
2524 '''
2525 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL)
2527 def is_exact(self):
2528 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
2529 '''
2530 return self._Fsum.is_exact()
2532 def is_finite(self): # in .constants
2533 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}).
2535 @see: Function L{isfinite<pygeodesy.isfinite>}.
2536 '''
2537 return self._Fsum.is_finite()
2539 def is_integer(self):
2540 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
2541 '''
2542 return self._Fsum.is_integer()
2544 def _mul_scalar(self, other, op): # for Fsum._fmul
2545 return self._Fsum._mul_scalar(other, op)
2547 @property_RO
2548 def _n(self):
2549 return self._Fsum._n
2551 def _other_op(self, other, which):
2552 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)
2553 return getattr(C, which.__name__)(s, other)
2555 @property_RO
2556 def _ps(self):
2557 return self._Fsum._ps
2559 @property_RO
2560 def _ps_neg(self):
2561 return self._Fsum._ps_neg
2563 def signOf(self, **res):
2564 '''Like method L{Fsum.signOf}.
2565 '''
2566 return self._Fsum.signOf(**res)
2568 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature
2569 '''Return this L{Fsum2Tuple} as string (C{str}).
2571 @kwarg fmt: Optional C{float} format (C{letter}).
2572 @kwarg prec_sep: Optional keyword arguments for function
2573 L{fstr<streprs.fstr>}.
2574 '''
2575 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))
2577_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines
2580class ResidualError(_ValueError):
2581 '''Error raised for a division, power or root operation of
2582 an L{Fsum} instance with a C{residual} I{ratio} exceeding
2583 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.
2585 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
2586 '''
2587 pass
2590try:
2591 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
2593 # make sure _fsum works as expected (XXX check
2594 # float.__getformat__('float')[:4] == 'IEEE'?)
2595 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
2596 del _fsum # nope, remove _fsum ...
2597 raise ImportError() # ... use _fsum below
2599 _sum = _fsum # in .elliptic
2600except ImportError:
2601 _sum = sum # in .elliptic
2603 def _fsum(xs):
2604 '''(INTERNAL) Precision summation, Python 2.5-.
2605 '''
2606 F = Fsum(name=_fsum.name, nonfinites=True)
2607 return float(F._facc(xs, up=False))
2610def fsum(xs, nonfinites=None, **floats):
2611 '''Precision floating point summation from Python's C{math.fsum}.
2613 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2614 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if
2615 C{False} I{non-finites} raise an Overflow-/ValueError or if
2616 C{None}, apply C{B{nonfinites}=not }L{nonfiniterrors()}
2617 (C{bool} or C{None}).
2618 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use
2619 keyword argument C{B{nonfinites}=False} instead.
2621 @return: Precision C{fsum} (C{float}).
2623 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow.
2625 @raise TypeError: Invalid B{C{xs}} item.
2627 @raise ValueError: Invalid or C{NAN} B{C{xs}} item.
2629 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites},
2630 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}.
2631 '''
2632 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0
2635def fsum_(*xs, **nonfinites):
2636 '''Precision floating point summation of all positional items.
2638 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2639 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2641 @see: Function L{fsum<fsums.fsum>} for further details.
2642 '''
2643 return _xsum(fsum_, xs, origin=1, **nonfinites) if xs else _0_0
2646def fsumf_(*xs):
2647 '''Precision floating point summation of all positional items with I{non-finites} C{OK}.
2649 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),
2650 all positional.
2652 @see: Function L{fsum_<fsums.fsum_>} for further details.
2653 '''
2654 return _xsum(fsumf_, xs, nonfinites=True, origin=1) if xs else _0_0
2657def fsum1(xs, **nonfinites):
2658 '''Precision floating point summation, 1-primed.
2660 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).
2661 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2663 @see: Function L{fsum<fsums.fsum>} for further details.
2664 '''
2665 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0
2668def fsum1_(*xs, **nonfinites):
2669 '''Precision floating point summation of all positional items, 1-primed.
2671 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.
2672 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).
2674 @see: Function L{fsum_<fsums.fsum_>} for further details.
2675 '''
2676 return _xsum(fsum1_, xs, origin=1, primed=1, **nonfinites) if xs else _0_0
2679def fsum1f_(*xs):
2680 '''Precision floating point summation of all positional items, 1-primed and
2681 with I{non-finites} C{OK}.
2683 @see: Function L{fsum_<fsums.fsum_>} for further details.
2684 '''
2685 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0
2688def _xs(xs, _x, i_x):
2689 '''(INTERNAL) Yield all C{xs} as C{scalar}.
2690 '''
2691 for i, x in enumerate(xs):
2692 i_x[:] = i, x
2693 if _isFsumTuple(x):
2694 for p in map(_x, x._ps):
2695 yield p
2696 else:
2697 yield _x(x)
2700def _xsError(X, xs, i, x, *n): # in _2floats, ._fstats
2701 '''(INTERNAL) Error for C{xs} or C{x}, item C{xs[i]}.
2702 '''
2703 return ((_xError(X, n[0], xs) if n else
2704 _xError(X, xs=xs)) if x is xs else
2705 _xError(X, Fmt.INDEX(xs=i), x))
2708def _xsum(which, xs, nonfinites=None, origin=0, primed=0, **floats):
2709 '''(INTERNAL) Precision summation of C{xs} with conditions.
2710 '''
2711 i_x = [0, xs]
2712 try:
2713 if nonfinites is None:
2714 nonfinites = not nonfiniterrors()
2715 elif floats:
2716 nonfinites = _xkwds_get1(floats, floats=nonfinites)
2717 fs = _xs(xs, (_passarg if nonfinites else _2finite), i_x)
2718 return _fsum(_1primed(fs) if primed else fs)
2719 except (OverflowError, TypeError, ValueError) as X:
2720 i, x = i_x
2721 i += origin - (1 if primed else 0)
2722 t = _xsError(X, xs, i, x)
2723 t = _COMMASPACE_(unstr(which), t)
2724 raise _xError(X, t, txt=None)
2727# delete all decorators, etc.
2728del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \
2729 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \
2730 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _getenv, _std_
2732if __name__ == '__main__':
2734 # usage: python3 -m pygeodesy.fsums
2736 def _test(n):
2737 # copied from Hettinger, see L{Fsum} reference
2738 from pygeodesy import frandoms, printf
2740 printf(_fsum.__name__, end=_COMMASPACE_)
2741 printf(_psum.__name__, end=_COMMASPACE_)
2743 F = Fsum()
2744 if F.is_math_fsum():
2745 for t in frandoms(n, seeded=True):
2746 assert float(F.fset_(*t)) == _fsum(t)
2747 printf(_DOT_, end=NN)
2748 printf(NN)
2750 _test(128)
2752# **) MIT License
2753#
2754# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
2755#
2756# Permission is hereby granted, free of charge, to any person obtaining a
2757# copy of this software and associated documentation files (the "Software"),
2758# to deal in the Software without restriction, including without limitation
2759# the rights to use, copy, modify, merge, publish, distribute, sublicense,
2760# and/or sell copies of the Software, and to permit persons to whom the
2761# Software is furnished to do so, subject to the following conditions:
2762#
2763# The above copyright notice and this permission notice shall be included
2764# in all copies or substantial portions of the Software.
2765#
2766# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2767# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2768# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
2769# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2770# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2771# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2772# OTHER DEALINGS IN THE SOFTWARE.