Coverage for pygeodesy/fsums.py: 95%
700 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-06-07 08:37 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2023-06-07 08:37 -0400
2# -*- coding: utf-8 -*-
4u'''Class L{Fsum} for precision floating point summation and I{running}
5summation based on, respectively similar to Python's C{math.fsum}.
7Generally, an L{Fsum} instance is considered a C{float} plus a small or zero
8C{residual} value, see property L{Fsum.residual}. However, there are several
9C{integer} L{Fsum} cases, for example the result of C{ceil}, C{floor},
10C{Fsum.__floordiv__} and methods L{Fsum.fint} and L{Fsum.fint2}.
12Also, L{Fsum} methods L{Fsum.pow}, L{Fsum.__ipow__}, L{Fsum.__pow__} and
13L{Fsum.__rpow__} return a (very long) C{int} if invoked with optional argument
14C{mod} set to C{None}. The C{residual} of an C{integer} L{Fsum} may be between
15C{-1.0} and C{+1.0}, including C{INT0} if considered to be I{exact}.
17Set env variable C{PYGEODESY_FSUM_PARTIALS} to an empty string (or anything
18other than C{"fsum"}) for backward compatible summation of L{Fsum} partials.
20Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater
21than C{"0.0"} as the threshold to throw a L{ResidualError} in division or
22exponention of an L{Fsum} instance with a I{relative} C{residual} exceeding
23the threshold, see methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
24and L{Fsum.__itruediv__}.
25'''
26# make sure int/int division yields float quotient, see .basics
27from __future__ import division as _; del _ # PYCHOK semicolon
29from pygeodesy.basics import iscomplex, isint, isscalar, signOf, _signOf
30from pygeodesy.constants import INT0, _isfinite, isinf, isnan, _pos_self, \
31 _0_0, _1_0, _N_1_0, Float, Int
32from pygeodesy.errors import itemsorted, _OverflowError, _TypeError, \
33 _ValueError, _xError2, _xkwds_get, _xkwds_get_, \
34 _ZeroDivisionError
35from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _EQUAL_, \
36 _exceeds_, _from_, _iadd_, _LANGLE_, _negative_, \
37 _NOTEQUAL_, _not_finite_, _not_scalar_, \
38 _PERCENT_, _PLUS_, _R_, _RANGLE_, _SLASH_, \
39 _SPACE_, _STAR_, _UNDER_
40from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
41from pygeodesy.named import _Named, _NamedTuple, _NotImplemented, Fmt, unstr
42from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \
43 Property_RO, property_RO
44# from pygeodesy.streprs import Fmt, unstr # from .named
45# from pygeodesy.units import Float, Int # from .constants
47from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp
49__all__ = _ALL_LAZY.fsums
50__version__ = '23.06.04'
52_add_op_ = _PLUS_
53_eq_op_ = _EQUAL_ * 2 # _DEQUAL_
54_COMMASPACE_R_ = _COMMASPACE_ + _R_
55_exceeds_R_ = _SPACE_ + _exceeds_(_R_)
56_floordiv_op_ = _SLASH_ * 2 # _DSLASH_
57_fset_op_ = _EQUAL_
58_ge_op_ = _RANGLE_ + _EQUAL_
59_gt_op_ = _RANGLE_
60_integer_ = 'integer'
61_le_op_ = _LANGLE_ + _EQUAL_
62_lt_op_ = _LANGLE_
63_mod_op_ = _PERCENT_
64_mul_op_ = _STAR_
65_ne_op_ = _NOTEQUAL_
66_non_zero_ = 'non-zero'
67_pow_op_ = _STAR_ * 2 # _DSTAR_, in .fmath
68_sub_op_ = _DASH_
69_truediv_op_ = _SLASH_
70_divmod_op_ = _floordiv_op_ + _mod_op_
73def _2float(index=None, **name_value): # in .fmath, .fstats
74 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.
75 '''
76 n, v = name_value.popitem() # _xkwds_popitem(name_value)
77 try:
78 v = float(v)
79 if _isfinite(v):
80 return v
81 E, t = _ValueError, _not_finite_
82 except Exception as e:
83 E, t = _xError2(e)
84 if index is not None:
85 n = Fmt.SQUARE(n, index)
86 raise E(n, v, txt=t)
89def _2floats(xs, origin=0, sub=False):
90 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
91 '''
92 try:
93 i, x = origin, None
94 _fin = _isfinite
95 _Fsum = Fsum
96 for x in xs:
97 if isinstance(x, _Fsum):
98 for p in x._ps:
99 yield (-p) if sub else p
100 else:
101 f = float(x)
102 if not _fin(f):
103 raise ValueError(_not_finite_)
104 if f:
105 yield (-f) if sub else f
106 i += 1
107 except Exception as e:
108 E, t = _xError2(e)
109 n = Fmt.SQUARE(xs=i)
110 raise E(n, x, txt=t)
113def _Powers(power, xs, origin=1): # in .fmath
114 '''(INTERNAL) Yield each C{xs} as C{float(x**power)}.
115 '''
116 if not isscalar(power):
117 raise _TypeError(power=power, txt=_not_scalar_)
118 try:
119 i, x = origin, None
120 _fin = _isfinite
121 _Fsum = Fsum
122 _pow = pow # XXX math.pow
123 for x in xs:
124 if isinstance(x, _Fsum):
125 P = x.pow(power)
126 for p in P._ps:
127 yield p
128 else:
129 p = _pow(float(x), power)
130 if not _fin(p):
131 raise ValueError(_not_finite_)
132 yield p
133 i += 1
134 except Exception as e:
135 E, t = _xError2(e)
136 n = Fmt.SQUARE(xs=i)
137 raise E(n, x, txt=t)
140def _1primed(xs):
141 '''(INTERNAL) 1-Prime the summation of C{xs}
142 arguments I{known} to be C{finite float}.
143 '''
144 yield _1_0
145 for x in xs:
146 if x:
147 yield x
148 yield _N_1_0
151def _psum(ps): # PYCHOK used!
152 '''(INTERNAL) Partials summation updating C{ps}, I{overridden below}.
153 '''
154 i = len(ps) - 1 # len(ps) > 2
155 s = ps[i]
156 _2s = _2sum
157 while i > 0:
158 i -= 1
159 s, r = _2s(s, ps[i])
160 if r: # sum(ps) became inexact
161 ps[i:] = [s, r] if s else [r]
162 if i > 0:
163 p = ps[i-1] # round half-even
164 if (p > 0 and r > 0) or \
165 (p < 0 and r < 0): # signs match
166 r *= 2
167 t = s + r
168 if r == (t - s):
169 s = t
170 break
171 ps[i:] = [s]
172 return s
175def _2scalar(other, _raiser=None):
176 '''(INTERNAL) Return B{C{other}} as C{int}, C{float} or C{as-is}.
177 '''
178 if isinstance(other, Fsum):
179 s, r = other._fint2
180 if r:
181 s, r = other._fprs2
182 if r: # PYCHOK no cover
183 if _raiser and _raiser(r, s):
184 raise ValueError(_stresidual(_non_zero_, r))
185 s = other # L{Fsum} as-is
186 else:
187 s = other # C{type} as-is
188 if isint(s, both=True):
189 s = int(s)
190 return s
193def _strcomplex(s, *args):
194 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error C{str}.
195 '''
196 c = iscomplex.__name__[2:]
197 n = _DASH_(len(args), _arg_)
198 t = _SPACE_(c, s, _from_, n, pow.__name__)
199 return unstr(t, *args)
202def _stresidual(prefix, residual, **name_values):
203 '''(INTERNAL) Residual error C{str}.
204 '''
205 p = _SPACE_(prefix, Fsum.residual.name)
206 t = Fmt.PARENSPACED(p, Fmt(residual))
207 for n, v in itemsorted(name_values):
208 n = n.replace(_UNDER_, _SPACE_)
209 p = Fmt.PARENSPACED(n, Fmt(v))
210 t = _COMMASPACE_(t, p)
211 return t
214def _2sum(a, b): # by .testFmath
215 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual).
216 '''
217 s = a + b
218 if not _isfinite(s):
219 u = unstr(_2sum.__name__, a, b)
220 t = Fmt.PARENSPACED(_not_finite_, s)
221 raise _OverflowError(u, txt=t)
222 r = (a - (s - b)) if fabs(a) < fabs(b) else \
223 (b - (s - a)) # fabs(a) >= fabs(b)
224 return s, r
227class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase
228 '''Precision floating point I{running} summation.
230 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
231 I{running} precision floating point summation. Accumulation may continue after
232 intermediate, I{running} summuation.
234 @note: Accumulated values may be L{Fsum} or C{scalar} instances with C{scalar} meaning
235 type C{float}, C{int} or any C{type} convertible to a single C{float}, having
236 method C{__float__}.
238 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from
239 Python's C{math.fsum}.
241 @see: U{Hettinger<https://GitHub.com/ActiveState/code/blob/master/recipes/Python/
242 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}, U{Kahan
243 <https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
244 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
245 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
246 <https://Bugs.Python.org/issue2819>}.
247 '''
248 _math_fsum = None
249 _n = 0
250# _ps = [] # partial sums
251# _px = 0
252 _ratio = None
253 _RESIDUAL = max(float(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)), _0_0)
255 def __init__(self, *xs, **name_RESIDUAL):
256 '''New L{Fsum} for precision floating point I{running} summation.
258 @arg xs: No, one or more initial values (each C{scalar} or an
259 L{Fsum} instance).
260 @kwarg name_RESIDUAL: Optional C{B{name}=NN} for this L{Fsum}
261 (C{str}) and C{B{RESIDUAL}=None} for the
262 L{ResidualError} threshold.
264 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.
265 '''
266 if name_RESIDUAL:
267 n, r = _xkwds_get_(name_RESIDUAL, name=NN, RESIDUAL=None)
268 if n: # set name ...
269 self.name = n
270 if r is not None:
271 self.RESIDUAL(r) # ... for ResidualError
272# self._n = 0
273 self._ps = [] # [_0_0], see L{Fsum._fprs}
274 if len(xs) > 1:
275 self._facc(_2floats(xs, origin=1), up=False) # PYCHOK yield
276 elif xs: # len(xs) == 1
277 self._ps = [_2float(x=xs[0])]
278 self._n = 1
280 def __abs__(self):
281 '''Return this instance' absolute value as an L{Fsum}.
282 '''
283 s = _fsum(self._ps_1()) # == self._cmp_0(0, ...)
284 return self._copy_n(self.__abs__) if s < 0 else \
285 self._copy_2(self.__abs__)
287 def __add__(self, other):
288 '''Return the C{Fsum(B{self}, B{other})}.
290 @arg other: An L{Fsum} or C{scalar}.
292 @return: The sum (L{Fsum}).
294 @see: Method L{Fsum.__iadd__}.
295 '''
296 f = self._copy_2(self.__add__)
297 return f._fadd(other, _add_op_)
299 def __bool__(self): # PYCHOK not special in Python 2-
300 '''Return C{True} if this instance is I{exactly} non-zero.
301 '''
302 s, r = self._fprs2
303 return bool(s or r) and s != -r # == self != 0
305 def __ceil__(self): # PYCHOK not special in Python 2-
306 '''Return this instance' C{math.ceil} as C{int} or C{float}.
308 @return: An C{int} in Python 3+, but C{float} in Python 2-.
310 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
311 '''
312 return self.ceil
314 def __cmp__(self, other): # Python 2-
315 '''Compare this with an other instance or C{scalar}.
317 @return: -1, 0 or +1 (C{int}).
319 @raise TypeError: Incompatible B{C{other}} C{type}.
320 '''
321 s = self._cmp_0(other, self.cmp.__name__)
322 return _signOf(s, 0)
324 cmp = __cmp__
326 def __divmod__(self, other):
327 '''Return C{divmod(B{self}, B{other})} as 2-tuple C{(quotient,
328 remainder)}, an C{int} in Python 3+ or C{float} in Python 2-
329 and an L{Fsum}.
331 @arg other: An L{Fsum} or C{scalar} modulus.
333 @see: Method L{Fsum.__itruediv__}.
334 '''
335 f = self._copy_2(self.__divmod__)
336 return f._fdivmod2(other, _divmod_op_)
338 def __eq__(self, other):
339 '''Compare this with an other instance or C{scalar}.
340 '''
341 return self._cmp_0(other, _eq_op_) == 0
343 def __float__(self):
344 '''Return this instance' current precision running sum as C{float}.
346 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
347 '''
348 return float(self._fprs)
350 def __floor__(self): # PYCHOK not special in Python 2-
351 '''Return this instance' C{math.floor} as C{int} or C{float}.
353 @return: An C{int} in Python 3+, but C{float} in Python 2-.
355 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
356 '''
357 return self.floor
359 def __floordiv__(self, other):
360 '''Return C{B{self} // B{other}} as an L{Fsum}.
362 @arg other: An L{Fsum} or C{scalar} divisor.
364 @return: The C{floor} quotient (L{Fsum}).
366 @see: Methods L{Fsum.__ifloordiv__}.
367 '''
368 f = self._copy_2(self.__floordiv__)
369 return f._floordiv(other, _floordiv_op_)
371 def __format__(self, *other): # PYCHOK no cover
372 '''Not implemented.'''
373 return _NotImplemented(self, *other)
375 def __ge__(self, other):
376 '''Compare this with an other instance or C{scalar}.
377 '''
378 return self._cmp_0(other, _ge_op_) >= 0
380 def __gt__(self, other):
381 '''Compare this with an other instance or C{scalar}.
382 '''
383 return self._cmp_0(other, _gt_op_) > 0
385 def __hash__(self): # PYCHOK no cover
386 '''Return this instance' C{hash}.
387 '''
388 return hash(self._ps) # XXX id(self)?
390 def __iadd__(self, other):
391 '''Apply C{B{self} += B{other}} to this instance.
393 @arg other: An L{Fsum} or C{scalar} instance.
395 @return: This instance, updated (L{Fsum}).
397 @raise TypeError: Invalid B{C{other}}, not
398 C{scalar} nor L{Fsum}.
400 @see: Methods L{Fsum.fadd} and L{Fsum.fadd_}.
401 '''
402 return self._fadd(other, _iadd_)
404 def __ifloordiv__(self, other):
405 '''Apply C{B{self} //= B{other}} to this instance.
407 @arg other: An L{Fsum} or C{scalar} divisor.
409 @return: This instance, updated (L{Fsum}).
411 @raise ResidualError: Non-zero residual in B{C{other}}.
413 @raise TypeError: Invalid B{C{other}} type.
415 @raise ValueError: Invalid or non-finite B{C{other}}.
417 @raise ZeroDivisionError: Zero B{C{other}}.
419 @see: Methods L{Fsum.__itruediv__}.
420 '''
421 return self._floordiv(other, _floordiv_op_ + _fset_op_)
423 def __imatmul__(self, other): # PYCHOK no cover
424 '''Not implemented.'''
425 return _NotImplemented(self, other)
427 def __imod__(self, other):
428 '''Apply C{B{self} %= B{other}} to this instance.
430 @arg other: An L{Fsum} or C{scalar} modulus.
432 @return: This instance, updated (L{Fsum}).
434 @see: Method L{Fsum.__divmod__}.
435 '''
436 self._fdivmod2(other, _mod_op_ + _fset_op_)
437 return self
439 def __imul__(self, other):
440 '''Apply C{B{self} *= B{other}} to this instance.
442 @arg other: An L{Fsum} or C{scalar} factor.
444 @return: This instance, updated (L{Fsum}).
446 @raise OverflowError: Partial C{2sum} overflow.
448 @raise TypeError: Invalid B{C{other}} type.
450 @raise ValueError: Invalid or non-finite B{C{other}}.
451 '''
452 return self._fmul(other, _mul_op_ + _fset_op_)
454 def __int__(self):
455 '''Return this instance as an C{int}.
457 @see: Methods L{Fsum.int_float}, L{Fsum.__ceil__}
458 and L{Fsum.__floor__} and properties
459 L{Fsum.ceil} and L{Fsum.floor}.
460 '''
461 i, _ = self._fint2
462 return i
464 def __invert__(self): # PYCHOK no cover
465 '''Not implemented.'''
466 # Luciano Ramalho, "Fluent Python", 2nd Ed, page 567, O'Reilly, 2022
467 return _NotImplemented(self)
469 def __ipow__(self, other, *mod): # PYCHOK 2 vs 3 args
470 '''Apply C{B{self} **= B{other}} to this instance.
472 @arg other: The exponent (L{Fsum} or C{scalar}).
473 @arg mod: Optional modulus (C{int} or C{None}) for the
474 3-argument C{pow(B{self}, B{other}, B{mod})}
475 version.
477 @return: This instance, updated (L{Fsum}).
479 @note: If B{C{mod}} is given, the result will be an C{integer}
480 L{Fsum} in Python 3+ if this instance C{is_integer} or
481 set to C{as_integer} if B{C{mod}} given as C{None}.
483 @raise OverflowError: Partial C{2sum} overflow.
485 @raise ResidualError: Non-zero residual in B{C{other}} and
486 env var C{PYGEODESY_FSUM_RESIDUAL}
487 set or this instance has a non-zero
488 residual and either B{C{mod}} is
489 given and non-C{None} or B{C{other}}
490 is a negative or fractional C{scalar}.
492 @raise TypeError: Invalid B{C{other}} type or 3-argument
493 C{pow} invocation failed.
495 @raise ValueError: If B{C{other}} is a negative C{scalar}
496 and this instance is C{0} or B{C{other}}
497 is a fractional C{scalar} and this
498 instance is negative or has a non-zero
499 residual or B{C{mod}} is given and C{0}.
501 @see: CPython function U{float_pow<https://GitHub.com/
502 python/cpython/blob/main/Objects/floatobject.c>}.
503 '''
504 return self._fpow(other, _pow_op_ + _fset_op_, *mod)
506 def __isub__(self, other):
507 '''Apply C{B{self} -= B{other}} to this instance.
509 @arg other: An L{Fsum} or C{scalar}.
511 @return: This instance, updated (L{Fsum}).
513 @raise TypeError: Invalid B{C{other}} type.
515 @see: Method L{Fsum.fadd}.
516 '''
517 return self._fsub(other, _sub_op_ + _fset_op_)
519 def __iter__(self):
520 '''Return an C{iter}ator over a C{partials} duplicate.
521 '''
522 return iter(self.partials)
524 def __itruediv__(self, other):
525 '''Apply C{B{self} /= B{other}} to this instance.
527 @arg other: An L{Fsum} or C{scalar} divisor.
529 @return: This instance, updated (L{Fsum}).
531 @raise OverflowError: Partial C{2sum} overflow.
533 @raise ResidualError: Non-zero residual in B{C{other}} and
534 env var C{PYGEODESY_FSUM_RESIDUAL} set.
536 @raise TypeError: Invalid B{C{other}} type.
538 @raise ValueError: Invalid or non-finite B{C{other}}.
540 @raise ZeroDivisionError: Zero B{C{other}}.
542 @see: Method L{Fsum.__ifloordiv__}.
543 '''
544 return self._ftruediv(other, _truediv_op_ + _fset_op_)
546 def __le__(self, other):
547 '''Compare this with an other instance or C{scalar}.
548 '''
549 return self._cmp_0(other, _le_op_) <= 0
551 def __len__(self):
552 '''Return the number of values accumulated (C{int}).
553 '''
554 return self._n
556 def __lt__(self, other):
557 '''Compare this with an other instance or C{scalar}.
558 '''
559 return self._cmp_0(other, _lt_op_) < 0
561 def __matmul__(self, other): # PYCHOK no cover
562 '''Not implemented.'''
563 return _NotImplemented(self, other)
565 def __mod__(self, other):
566 '''Return C{B{self} % B{other}} as an L{Fsum}.
568 @see: Method L{Fsum.__imod__}.
569 '''
570 f = self._copy_2(self.__mod__)
571 return f._fdivmod2(other, _mod_op_)[1]
573 def __mul__(self, other):
574 '''Return C{B{self} * B{other}} as an L{Fsum}.
576 @see: Method L{Fsum.__imul__}.
577 '''
578 f = self._copy_2(self.__mul__)
579 return f._fmul(other, _mul_op_)
581 def __ne__(self, other):
582 '''Compare this with an other instance or C{scalar}.
583 '''
584 return self._cmp_0(other, _ne_op_) != 0
586 def __neg__(self):
587 '''Return I{a copy of} this instance, negated.
588 '''
589 return self._copy_n(self.__neg__)
591 def __pos__(self):
592 '''Return this instance I{as-is}, like C{float.__pos__()}.
593 '''
594 return self if _pos_self else self._copy_2(self.__pos__)
596 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
597 '''Return C{B{self}**B{other}} as an L{Fsum}.
599 @see: Method L{Fsum.__ipow__}.
600 '''
601 f = self._copy_2(self.__pow__)
602 return f._fpow(other, _pow_op_, *mod)
604 def __radd__(self, other):
605 '''Return C{B{other} + B{self}} as an L{Fsum}.
607 @see: Method L{Fsum.__iadd__}.
608 '''
609 f = self._copy_r2(other, self.__radd__)
610 return f._fadd(self, _add_op_)
612 def __rdivmod__(self, other):
613 '''Return C{divmod(B{other}, B{self})} as 2-tuple C{(quotient,
614 remainder)}.
616 @see: Method L{Fsum.__divmod__}.
617 '''
618 f = self._copy_r2(other, self.__rdivmod__)
619 return f._fdivmod2(self, _divmod_op_)
621# def __repr__(self):
622# '''Return the default C{repr(this)}.
623# '''
624# return self.toRepr(lenc=True)
626 def __rfloordiv__(self, other):
627 '''Return C{B{other} // B{self}} as an L{Fsum}.
629 @see: Method L{Fsum.__ifloordiv__}.
630 '''
631 f = self._copy_r2(other, self.__rfloordiv__)
632 return f._floordiv(self, _floordiv_op_)
634 def __rmatmul__(self, other): # PYCHOK no cover
635 '''Not implemented.'''
636 return _NotImplemented(self, other)
638 def __rmod__(self, other):
639 '''Return C{B{other} % B{self}} as an L{Fsum}.
641 @see: Method L{Fsum.__imod__}.
642 '''
643 f = self._copy_r2(other, self.__rmod__)
644 return f._fdivmod2(self, _mod_op_)[1]
646 def __rmul__(self, other):
647 '''Return C{B{other} * B{self}} as an L{Fsum}.
649 @see: Method L{Fsum.__imul__}.
650 '''
651 f = self._copy_r2(other, self.__rmul__)
652 return f._fmul(self, _mul_op_)
654 def __round__(self, ndigits=None): # PYCHOK no cover
655 '''Not implemented.'''
656 return _NotImplemented(self, ndigits=ndigits)
658 def __rpow__(self, other, *mod):
659 '''Return C{B{other}**B{self}} as an L{Fsum}.
661 @see: Method L{Fsum.__ipow__}.
662 '''
663 f = self._copy_r2(other, self.__rpow__)
664 return f._fpow(self, _pow_op_, *mod)
666 def __rsub__(self, other):
667 '''Return C{B{other} - B{self}} as L{Fsum}.
669 @see: Method L{Fsum.__isub__}.
670 '''
671 f = self._copy_r2(other, self.__rsub__)
672 return f._fsub(self, _sub_op_)
674 def __rtruediv__(self, other):
675 '''Return C{B{other} / B{self}} as an L{Fsum}.
677 @see: Method L{Fsum.__itruediv__}.
678 '''
679 f = self._copy_r2(other, self.__rtruediv__)
680 return f._ftruediv(self, _truediv_op_)
682 def __str__(self):
683 '''Return the default C{str(self)}.
684 '''
685 return self.toStr(lenc=True)
687 def __sub__(self, other):
688 '''Return C{B{self} - B{other}} as an L{Fsum}.
690 @arg other: An L{Fsum} or C{scalar}.
692 @return: The difference (L{Fsum}).
694 @see: Method L{Fsum.__isub__}.
695 '''
696 f = self._copy_2(self.__sub__)
697 return f._fsub(other, _sub_op_)
699 def __truediv__(self, other):
700 '''Return C{B{self} / B{other}} as an L{Fsum}.
702 @arg other: An L{Fsum} or C{scalar} divisor.
704 @return: The quotient (L{Fsum}).
706 @see: Method L{Fsum.__itruediv__}.
707 '''
708 f = self._copy_2(self.__truediv__)
709 return f._ftruediv(other, _truediv_op_)
711 __trunc__ = __int__
713 if _sys_version_info2 < (3, 0): # PYCHOK no cover
714 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
715 __div__ = __truediv__
716 __idiv__ = __itruediv__
717 __long__ = __int__
718 __nonzero__ = __bool__
719 __rdiv__ = __rtruediv__
721 def as_integer_ratio(self):
722 '''Return this instance as the ratio of 2 integers.
724 @return: 2-Tuple C{(numerator, denominator)} both
725 C{int} and with positive C{denominator}.
727 @see: Standard C{float.as_integer_ratio} in Python 3+.
728 '''
729 n, r = self._fint2
730 if r:
731 i, d = r.as_integer_ratio()
732 n *= d
733 n += i
734 else: # PYCHOK no cover
735 d = 1
736 return n, d
738 @property_RO
739 def ceil(self):
740 '''Get this instance' C{ceil} value (C{int} in Python 3+,
741 but C{float} in Python 2-).
743 @note: The C{ceil} takes the C{residual} into account.
745 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
746 L{Fsum.imag} and L{Fsum.real}.
747 '''
748 s, r = self._fprs2
749 c = _ceil(s) + int(r) - 1
750 while r > (c - s): # (s + r) > c
751 c += 1
752 return c
754 def _cmp_0(self, other, op):
755 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
756 '''
757 if isscalar(other):
758 if other:
759 s = _fsum(self._ps_1(other))
760 else:
761 s, r = self._fprs2
762 s = _signOf(s, -r)
763 elif isinstance(other, Fsum):
764 s = _fsum(self._ps_1(*other._ps))
765 else:
766 raise self._TypeError(op, other) # txt=_invalid_
767 return s
769 def copy(self, deep=False, name=NN):
770 '''Copy this instance, C{shallow} or B{C{deep}}.
772 @return: The copy (L{Fsum}).
773 '''
774 f = _Named.copy(self, deep=deep, name=name)
775 f._n = self._n if deep else 1
776 f._ps = list(self._ps) # separate list
777 return f
779 def _copy_0(self, *xs):
780 '''(INTERNAL) Copy with/-out overriding C{partials}.
781 '''
782 # for x in xs:
783 # assert isscalar(x)
784 f = self._Fsum(self._n + len(xs), *xs)
785 if self.name:
786 f._name = self.name # .rename calls _update_attrs
787 return f
789 def _copy_2(self, which):
790 '''(INTERNAL) Copy for I{dyadic} operators.
791 '''
792 # NOT .classof due to .Fdot(a, *b) args, etc.
793 f = _Named.copy(self, deep=False, name=which.__name__)
794 # assert f._n == self._n
795 f._ps = list(self._ps) # separate list
796 return f
798 def _copy_n(self, which):
799 '''(INTERNAL) Negated copy for I{monadic} C{__abs__} and C{__neg__}.
800 '''
801 if self._ps:
802 f = self._Fsum(self._n)
803 f._ps[:] = self._ps_n()
804# f._facc_up(up=False)
805 else:
806 f = self._Fsum(self._n, _0_0)
807 f._name = which.__name__ # .rename calls _update_attrs
808 return f
810 def _copy_r2(self, other, which):
811 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
812 '''
813 return other._copy_2(which) if isinstance(other, Fsum) else \
814 Fsum(other, name=which.__name__) # see ._copy_2
816 def _copy_RESIDUAL(self, other):
817 '''(INTERNAL) Copy C{other._RESIDUAL}.
818 '''
819 R = other._RESIDUAL
820 if R is not Fsum._RESIDUAL:
821 self._RESIDUAL = R
823 def _copy_up(self, _fprs2=False):
824 '''(INTERNAL) Minimal, anonymous copy.
825 '''
826 f = self._Fsum(self._n, *self._ps)
827 if _fprs2: # only the ._fprs2 2-tuple
828 Fsum._fprs2._update_from(f, self)
829 return f
831 def divmod(self, other):
832 '''Return C{divmod(B{self}, B{other})} as 2-tuple C{(quotient,
833 remainder)}.
835 @arg other: An L{Fsum} or C{scalar} divisor.
837 @return: 2-Tuple C{(quotient, remainder)}, with the C{quotient}
838 an C{int} in Python 3+ or a C{float} in Python 2- and
839 the C{remainder} an L{Fsum} instance.
841 @see: Method L{Fsum.__itruediv__}.
842 '''
843 f = self._copy_2(self.divmod)
844 return f._fdivmod2(other, _divmod_op_)
846 def _Error(self, op, other, Error, **txt):
847 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
848 '''
849 return Error(_SPACE_(self.toRepr(), op, repr(other)), **txt)
851 def _ErrorX(self, X, xs, **kwds): # in .fmath
852 '''(INTERNAL) Format a caught exception.
853 '''
854 E, t = _xError2(X)
855 n = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
856 return E(n, txt=t, cause=X)
858 def _facc(self, xs, up=True): # from .elliptic._Defer.Fsum
859 '''(INTERNAL) Accumulate more known C{scalar}s.
860 '''
861 n, ps, _2s = 0, self._ps, _2sum
862 for x in xs: # _iter()
863 # assert isscalar(x) and isfinite(x)
864 i = 0
865 for p in ps:
866 x, p = _2s(x, p)
867 if p:
868 ps[i] = p
869 i += 1
870 ps[i:] = [x]
871 n += 1
872 # assert self._ps is ps
873 if n:
874 self._n += n
875 # Fsum._px = max(Fsum._px, len(ps))
876 if up:
877 self._update()
878 return self
880 def _facc_(self, *xs, **up):
881 '''(INTERNAL) Accumulate all positional C{scalar}s.
882 '''
883 return self._facc(xs, **up) if xs else self
885# def _facc_up(self, up=True):
886# '''(INTERNAL) Update the C{partials}, by removing
887# and re-accumulating the final C{partial}.
888# '''
889# while len(self._ps) > 1:
890# p = self._ps.pop()
891# if p:
892# n = self._n
893# self._facc_(p, up=False)
894# self._n = n
895# break
896# return self._update() if up else self # ._fpsqz()
898 def fadd(self, xs=()):
899 '''Add an iterable of C{scalar} or L{Fsum} instances
900 to this instance.
902 @arg xs: Iterable, list, tuple, etc. (C{scalar} or
903 L{Fsum} instances).
905 @return: This instance (L{Fsum}).
907 @raise OverflowError: Partial C{2sum} overflow.
909 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}
910 nor L{Fsum}.
912 @raise ValueError: Invalid or non-finite B{C{xs}} value.
913 '''
914 if isinstance(xs, Fsum):
915 self._facc(xs._ps)
916 elif isscalar(xs): # for backward compatibility
917 self._facc_(_2float(x=xs)) # PYCHOK no cover
918 elif xs:
919 self._facc(_2floats(xs)) # PYCHOK yield
920 return self
922 def fadd_(self, *xs):
923 '''Add all positional C{scalar} or L{Fsum} instances
924 to this instance.
926 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
927 all positional.
929 @return: This instance (L{Fsum}).
931 @raise OverflowError: Partial C{2sum} overflow.
933 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}
934 nor L{Fsum}.
936 @raise ValueError: Invalid or non-finite B{C{xs}} value.
937 '''
938 return self._facc(_2floats(xs, origin=1)) # PYCHOK yield
940 def _fadd(self, other, op): # in .fmath.Fhorner
941 '''(INTERNAL) Apply C{B{self} += B{other}}.
942 '''
943 if isinstance(other, Fsum):
944 if other is self:
945 self._facc_(*other._ps) # == ._facc(tuple(other._ps))
946 elif other._ps:
947 self._facc(other._ps)
948 elif not isscalar(other):
949 raise self._TypeError(op, other) # txt=_invalid_
950 elif other:
951 self._facc_(other)
952 return self
954 fcopy = copy # for backward compatibility
955 fdiv = __itruediv__ # for backward compatibility
956 fdivmod = __divmod__ # for backward compatibility
958 def _fdivmod2(self, other, op):
959 '''(INTERNAL) C{divmod(B{self}, B{other})} as 2-tuple
960 (C{int} or C{float}, remainder C{self}).
961 '''
962 # result mostly follows CPython function U{float_divmod
963 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
964 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
965 q = self._copy_up(_fprs2=True)._ftruediv(other, op).floor
966 if q: # == float // other == floor(float / other)
967 self -= other * q
969 s = signOf(other) # make signOf(self) == signOf(other)
970 if s and self.signOf() == -s: # PYCHOK no cover
971 self += other
972 q -= 1
974# t = self.signOf()
975# if t and t != s:
976# from pygeodesy.errors import _AssertionError
977# raise self._Error(op, other, _AssertionError, txt=signOf.__name__)
978 return q, self # q is C{int} in Python 3+, but C{float} in Python 2-
980 def _finite(self, other, op=None):
981 '''(INTERNAL) Return B{C{other}} if C{finite}.
982 '''
983 if _isfinite(other):
984 return other
985 raise ValueError(_not_finite_) if not op else \
986 self._ValueError(op, other, txt=_not_finite_)
988 def fint(self, raiser=True, name=NN):
989 '''Return this instance' current running sum as C{integer}.
991 @kwarg raiser: If C{True} throw a L{ResidualError} if the
992 I{integer} residual is non-zero.
993 @kwarg name: Optional name (C{str}), overriding C{"fint"}.
995 @return: The C{integer} (L{Fsum}).
997 @raise ResidualError: Non-zero I{integer} residual.
999 @see: Methods L{Fsum.int_float} and L{Fsum.is_integer}.
1000 '''
1001 i, r = self._fint2
1002 if r and raiser:
1003 t = _stresidual(_integer_, r)
1004 raise ResidualError(_integer_, i, txt=t)
1005 n = name or self.fint.__name__
1006 return Fsum(name=n)._fset(i, asis=True)
1008 def fint2(self, **name):
1009 '''Return this instance' current running sum as C{int} and
1010 the I{integer} residual.
1012 @kwarg name: Optional name (C{str}).
1014 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1015 an C{int} and I{integer} C{residual} a C{float} or
1016 C{INT0} if the C{fsum} is considered to be I{exact}.
1017 '''
1018 return Fsum2Tuple(*self._fint2, **name)
1020 @Property_RO
1021 def _fint2(self): # see ._fset
1022 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1023 '''
1024 i = int(self._fprs) # int(self)
1025 r = _fsum(self._ps_1(i)) if len(self._ps) > 1 else (
1026 (self._ps[0] - i) if self._ps else -i)
1027 return i, (r or INT0)
1029 @deprecated_property_RO
1030 def float_int(self): # PYCHOK no cover
1031 '''DEPRECATED, use method C{Fsum.int_float}.'''
1032 return self.int_float() # raiser=False
1034 @property_RO
1035 def floor(self):
1036 '''Get this instance' C{floor} (C{int} in Python 3+, but
1037 C{float} in Python 2-).
1039 @note: The C{floor} takes the C{residual} into account.
1041 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1042 L{Fsum.imag} and L{Fsum.real}.
1043 '''
1044 s, r = self._fprs2
1045 f = _floor(s) + _floor(r) + 1
1046 while r < (f - s): # (s + r) < f
1047 f -= 1
1048 return f
1050# floordiv = __floordiv__ # for naming consistency
1052 def _floordiv(self, other, op): # rather _ffloordiv?
1053 '''Apply C{B{self} //= B{other}}.
1054 '''
1055 q = self._ftruediv(other, op) # == self
1056 return self._fset(q.floor, asis=True) # floor(q)
1058 fmul = __imul__ # for backward compatibility
1060 def _fmul(self, other, op):
1061 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1062 '''
1063 if isscalar(other):
1064 f = self._mul_scalar(other, op)
1065 elif not isinstance(other, Fsum):
1066 raise self._TypeError(op, other) # txt=_invalid_
1067 elif len(self._ps) != 1:
1068 f = self._mul_Fsum(other, op)
1069 elif len(other._ps) != 1: # len(self._ps) == 1
1070 f = other._copy_up()._mul_scalar(self._ps[0], op)
1071 else: # len(other._ps) == len(self._ps) == 1
1072 s = self._finite(self._ps[0] * other._ps[0])
1073 return self._fset(s, asis=True, n=len(self) + 1)
1074 return self._fset(f)
1076 def fover(self, over):
1077 '''Apply C{B{self} /= B{over}} and summate.
1079 @arg over: An L{Fsum} or C{scalar} denominator.
1081 @return: Precision running sum (C{float}).
1083 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1084 '''
1085 return float(self.fdiv(over)._fprs)
1087 fpow = __ipow__ # for backward compatibility
1089 def _fpow(self, other, op, *mod):
1090 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1091 '''
1092 if mod and mod[0] is not None: # == 3-arg C{pow}
1093 s = self._pow_3(other, mod[0], op)
1094 elif mod and mod[0] is None and self.is_integer():
1095 # return an exact C{int} for C{int}**C{int}
1096 i = self._copy_0(self._fint2[0]) # assert _fint2[1] == 0
1097 x = _2scalar(other) # C{int}, C{float} or other
1098 s = i._pow_2(x, other, op) if isscalar(x) else i._fpow(x, op)
1099 else: # pow(self, other) == pow(self, other, None)
1100 p = None
1101 if isinstance(other, Fsum):
1102 x, r = other._fprs2
1103 if r:
1104 if self._raiser(r, x):
1105 raise self._ResidualError(op, other, r)
1106 p = self._pow_scalar(r, other, op)
1107# p = _2scalar(p) # _raiser = None
1108 elif not isscalar(other):
1109 raise self._TypeError(op, other) # txt=_invalid_
1110 else:
1111 x = self._finite(other, op)
1112 s = self._pow_scalar(x, other, op)
1113 if p is not None:
1114 s *= p
1115 return self._fset(s, asis=isint(s), n=max(len(self), 1))
1117 @Property_RO
1118 def _fprs(self):
1119 '''(INTERNAL) Get and cache this instance' precision
1120 running sum (C{float} or C{int}), ignoring C{residual}.
1122 @note: The precision running C{fsum} after a C{//=} or
1123 C{//} C{floor} division is C{int} in Python 3+.
1124 '''
1125 ps = self._ps
1126 n = len(ps) - 1
1127 if n > 1:
1128 s = _psum(ps)
1129 elif n > 0: # len(ps) == 2
1130 s, p = _2sum(*ps) if ps[1] else ps
1131 ps[:] = ([p, s] if s else [p]) if p else [s]
1132 elif n < 0: # see L{Fsum.__init__}
1133 s = _0_0
1134 ps[:] = [s]
1135 else: # len(ps) == 1
1136 s = ps[0]
1137 # assert self._ps is ps
1138 # assert Fsum._fprs2.name not in self.__dict__
1139 return s
1141 @Property_RO
1142 def _fprs2(self):
1143 '''(INTERNAL) Get and cache this instance' precision
1144 running sum and residual (L{Fsum2Tuple}).
1145 '''
1146 s = self._fprs
1147 r = _fsum(self._ps_1(s)) if len(self._ps) > 1 else INT0
1148 return Fsum2Tuple(s, r) # name=Fsum.fsum2.__name__
1150# def _fpsqz(self):
1151# '''(INTERNAL) Compress, squeeze the C{partials}.
1152# '''
1153# if len(self._ps) > 2:
1154# _ = self._fprs
1155# return self
1157 def _fset(self, other, asis=False, n=1):
1158 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1159 '''
1160 if other is self:
1161 pass # from ._fmul, ._ftruediv and ._pow_scalar
1162 elif isinstance(other, Fsum):
1163 self._n = other._n
1164 self._ps[:] = other._ps
1165 self._copy_RESIDUAL(other)
1166 # use or zap the C{Property_RO} values
1167 Fsum._fint2._update_from(self, other)
1168 Fsum._fprs ._update_from(self, other)
1169 Fsum._fprs2._update_from(self, other)
1170 elif isscalar(other):
1171 s = other if asis else float(other)
1172 i = int(s) # see ._fint2
1173 t = i, ((s - i) or INT0)
1174 self._n = n
1175 self._ps[:] = [s]
1176 # Property_RO _fint2, _fprs and _fprs2 can't be a Property:
1177 # Property's _fset zaps the value just set by the @setter
1178 self.__dict__.update(_fint2=t, _fprs=s, _fprs2=Fsum2Tuple(s, INT0))
1179 else: # PYCHOK no cover
1180 raise self._TypeError(_fset_op_, other) # txt=_invalid_
1181 return self
1183 def fsub(self, xs=()):
1184 '''Subtract an iterable of C{scalar} or L{Fsum} instances
1185 from this instance.
1187 @arg xs: Iterable, list, tuple. etc. (C{scalar}
1188 or L{Fsum} instances).
1190 @return: This instance, updated (L{Fsum}).
1192 @see: Method L{Fsum.fadd}.
1193 '''
1194 return self._facc(_2floats(xs, sub=True)) if xs else self # PYCHOK yield
1196 def fsub_(self, *xs):
1197 '''Subtract all positional C{scalar} or L{Fsum} instances
1198 from this instance.
1200 @arg xs: Values to subtract (C{scalar} or
1201 L{Fsum} instances), all positional.
1203 @return: This instance, updated (L{Fsum}).
1205 @see: Method L{Fsum.fadd}.
1206 '''
1207 return self._facc(_2floats(xs, origin=1, sub=True)) if xs else self # PYCHOK yield
1209 def _fsub(self, other, op):
1210 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1211 '''
1212 if isinstance(other, Fsum):
1213 if other is self: # or other._fprs2 == self._fprs2:
1214 self._fset(_0_0, asis=True, n=len(self) * 2) # self -= self
1215 elif other._ps:
1216 self._facc(other._ps_n())
1217 elif not isscalar(other):
1218 raise self._TypeError(op, other) # txt=_invalid_
1219 elif self._finite(other, op):
1220 self._facc_(-other)
1221 return self
1223 def _Fsum(self, n, *ps):
1224 '''(INTERNAL) New L{Fsum} instance.
1225 '''
1226 f = Fsum()
1227 f._n = n
1228 if ps:
1229 f._ps[:] = ps
1230 f._copy_RESIDUAL(self)
1231 return f
1233 def fsum(self, xs=()):
1234 '''Add more C{scalar} or L{Fsum} instances and summate.
1236 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or
1237 L{Fsum} instances).
1239 @return: Precision running sum (C{float} or C{int}).
1241 @see: Method L{Fsum.fadd}.
1243 @note: Accumulation can continue after summation.
1244 '''
1245 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield
1246 return f._fprs
1248 def fsum_(self, *xs):
1249 '''Add all positional C{scalar} or L{Fsum} instances and summate.
1251 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
1252 all positional.
1254 @return: Precision running sum (C{float} or C{int}).
1256 @see: Method L{Fsum.fsum}.
1257 '''
1258 f = self._facc(_2floats(xs, origin=1)) if xs else self # PYCHOK yield
1259 return f._fprs
1261 def fsum2(self, xs=(), **name):
1262 '''Add more C{scalar} or L{Fsum} instances and return the
1263 current precision running sum and the C{residual}.
1265 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or
1266 L{Fsum} instances).
1267 @kwarg name: Optional name (C{str}).
1269 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1270 current precision running sum and C{residual}, the
1271 (precision) sum of the remaining C{partials}. The
1272 C{residual is INT0} if the C{fsum} is considered
1273 to be I{exact}.
1275 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1276 '''
1277 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield
1278 t = f._fprs2
1279 if name:
1280 t = t.dup(name=_xkwds_get(name, name=NN))
1281 return t
1283 def fsum2_(self, *xs):
1284 '''Add any positional C{scalar} or L{Fsum} instances and return
1285 the precision running sum and the C{differential}.
1287 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
1288 all positional.
1290 @return: 2-Tuple C{(fsum, delta)} with the current precision
1291 running C{fsum} and C{delta}, the difference with
1292 the previous running C{fsum} (C{float}s).
1294 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1295 '''
1296 p, r = self._fprs2
1297 if xs:
1298 s, t = self._facc(_2floats(xs, origin=1))._fprs2 # PYCHOK yield
1299 return s, _fsum((s, -p, r, -t)) # ((s - p) + (r - t))
1300 else: # PYCHOK no cover
1301 return p, _0_0
1303# ftruediv = __itruediv__ # for naming consistency
1305 def _ftruediv(self, other, op):
1306 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1307 '''
1308 n = _1_0
1309 if isinstance(other, Fsum):
1310 if other is self or other._fprs2 == self._fprs2:
1311 return self._fset(_1_0, asis=True, n=len(self))
1312 d, r = other._fprs2
1313 if r:
1314 if not d: # PYCHOK no cover
1315 d = r
1316 elif self._raiser(r, d):
1317 raise self._ResidualError(op, other, r)
1318 else:
1319 d, n = other.as_integer_ratio()
1320 elif isscalar(other):
1321 d = other
1322 else: # PYCHOK no cover
1323 raise self._TypeError(op, other) # txt=_invalid_
1324 try:
1325 s = 0 if isinf(d) else (
1326 d if isnan(d) else self._finite(n / d))
1327 except Exception as x:
1328 E, t = _xError2(x)
1329 raise self._Error(op, other, E, txt=t)
1330 f = self._mul_scalar(s, _mul_op_) # handles 0, NAN, etc.
1331 return self._fset(f)
1333 @property_RO
1334 def imag(self):
1335 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1337 @see: Properties L{Fsum.ceil}, L{Fsum.floor} and L{Fsum.real}.
1338 '''
1339 return _0_0
1341 def int_float(self, raiser=False):
1342 '''Return this instance' current running sum as C{int} or C{float}.
1344 @kwarg raiser: If C{True} throw a L{ResidualError} if the
1345 residual is non-zero.
1347 @return: This C{integer} sum if this instance C{is_integer},
1348 otherwise return the C{float} sum if the residual
1349 is zero or if C{B{raiser}=False}.
1351 @raise ResidualError: Non-zero residual and C{B{raiser}=True}.
1353 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.
1354 '''
1355 s, r = self._fint2
1356 if r:
1357 s, r = self._fprs2
1358 if r and raiser: # PYCHOK no cover
1359 t = _stresidual(_non_zero_, r)
1360 raise ResidualError(int_float=s, txt=t)
1361 s = float(s) # redundant
1362 return s
1364 def is_exact(self):
1365 '''Is this instance' current running C{fsum} considered to
1366 be exact? (C{bool}).
1367 '''
1368 return self.residual is INT0
1370 def is_integer(self):
1371 '''Is this instance' current running sum C{integer}? (C{bool}).
1373 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.
1374 '''
1375 _, r = self._fint2
1376 return False if r else True
1378 def is_math_fsum(self):
1379 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1}
1380 and L{fsum1_} plus partials summation are based on
1381 Python's C{math.fsum} or not.
1383 @return: C{2} if all functions and partials summation
1384 are based on C{math.fsum}, C{True} if only
1385 the functions are based on C{math.fsum} (and
1386 partials summation is not) or C{False} if
1387 none are.
1388 '''
1389 f = Fsum._math_fsum
1390 return 2 if _psum is f else bool(f)
1392 def _mul_Fsum(self, other, op=_mul_op_):
1393 '''(INTERNAL) Return C{B{self} * Fsum B{other}} as L{Fsum}.
1394 '''
1395 # assert isinstance(other, Fsum)
1396 return self._copy_0()._facc(self._ps_x(op, *other._ps), up=False)
1398 def _mul_scalar(self, factor, op):
1399 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum} or C{0}.
1400 '''
1401 # assert isscalar(factor)
1402 if self._finite(factor, op) and self._ps:
1403 if factor == _1_0:
1404 return self
1405 f = self._copy_0()._facc(self._ps_x(op, factor), up=False)
1406 else:
1407 f = self._copy_0(_0_0)
1408 return f
1410 @property_RO
1411 def partials(self):
1412 '''Get this instance' current partial sums (C{tuple} of C{float}s and/or C{int}s).
1413 '''
1414 return tuple(self._ps)
1416 def pow(self, x, *mod):
1417 '''Return C{B{self}**B{x}} as L{Fsum}.
1419 @arg x: The exponent (L{Fsum} or C{scalar}).
1420 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
1421 C{pow(B{self}, B{other}, B{mod})} version.
1423 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
1424 result (L{Fsum}).
1426 @note: If B{C{mod}} is given as C{None}, the result will be an
1427 C{integer} L{Fsum} provided this instance C{is_integer}
1428 or set C{integer} with L{Fsum.fint}.
1430 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint} and L{Fsum.is_integer}.
1431 '''
1432 f = self._copy_2(self.pow)
1433 if f and isint(x) and x >= 0 and not mod:
1434 f._pow_int(x, x, _pow_op_) # f **= x
1435 else:
1436 f._fpow(x, _pow_op_, *mod) # f = pow(f, x, *mod)
1437 return f
1439 def _pow_0_1(self, x, other):
1440 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
1441 '''
1442 return self if x else (1 if self.is_integer() and isint(other) else _1_0)
1444 def _pow_2(self, x, other, op):
1445 '''(INTERNAL) 2-arg C{pow(B{self}, scalar B{x})} embellishing errors.
1446 '''
1447 # assert len(self._ps) == 1 and isscalar(x)
1448 b = self._ps[0] # assert isscalar(b)
1449 try: # type(s) == type(x) if x in (_1_0, 1)
1450 s = pow(b, x) # -1**2.3 == -(1**2.3)
1451 if not iscomplex(s):
1452 return self._finite(s) # 0**INF == 0.0, 1**INF==1.0
1453 # neg**frac == complex in Python 3+, but ValueError in 2-
1454 E, t = _ValueError, _strcomplex(s, b, x) # PYCHOK no cover
1455 except Exception as x:
1456 E, t = _xError2(x)
1457 raise self._Error(op, other, E, txt=t)
1459 def _pow_3(self, other, mod, op):
1460 '''(INTERNAL) 3-arg C{pow(B{self}, B{other}, int B{mod} or C{None})}.
1461 '''
1462 b, r = self._fprs2 if mod is None else self._fint2
1463 if r and self._raiser(r, b):
1464 t = _non_zero_ if mod is None else _integer_
1465 E, t = ResidualError, _stresidual(t, r, mod=mod)
1466 else:
1467 try: # b, other, mod all C{int}, unless C{mod} is C{None}
1468 x = _2scalar(other, _raiser=self._raiser)
1469 s = pow(b, x, mod)
1470 if not iscomplex(s):
1471 return self._finite(s)
1472 # neg**frac == complex in Python 3+, but ValueError in 2-
1473 E, t = _ValueError, _strcomplex(s, b, x, mod) # PYCHOK no cover
1474 except Exception as x:
1475 E, t = _xError2(x)
1476 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod), t)
1477 raise self._Error(op, other, E, txt=t)
1479 def _pow_int(self, x, other, op):
1480 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
1481 '''
1482 # assert isint(x) and x >= 0
1483 if len(self._ps) > 1:
1484 if x > 2:
1485 p = self._copy_up()
1486 m = 1 # single-bit mask
1487 if x & m:
1488 x -= m # x ^= m
1489 f = p._copy_up()
1490 else:
1491 f = self._copy_0(_1_0)
1492 while x:
1493 p = p._mul_Fsum(p, op) # p **= 2
1494 m += m # m <<= 1
1495 if x & m:
1496 x -= m # x ^= m
1497 f = f._mul_Fsum(p, op) # f *= p
1498 elif x > 1: # self**2
1499 f = self._mul_Fsum(self, op)
1500 else: # self**1 or self**0
1501 f = self._pow_0_1(x, other)
1502 elif self._ps: # self._ps[0]**x
1503 f = self._pow_2(x, other, op)
1504 else: # PYCHOK no cover
1505 # 0**pos_int == 0, but 0**0 == 1
1506 f = 0 if x else 1 # like ._fprs
1507 return self._fset(f, asis=isint(f), n=len(self))
1509 def _pow_scalar(self, x, other, op):
1510 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
1511 '''
1512 s, r = self._fprs2
1513 if isint(x, both=True):
1514 x = int(x) # Fsum**int
1515 y = abs(x)
1516 if y > 1:
1517 if r:
1518 f = self._copy_up()._pow_int(y, other, op)
1519 if x > 0: # > 1
1520 return f
1521 # assert x < 0 # < -1
1522 s, r = f._fprs2
1523 if r:
1524 return self._copy_0(_1_0)._ftruediv(f, op)
1525 # use **= -1 for the CPython float_pow
1526 # error if s is zero, and not s = 1 / s
1527 x = -1
1528# elif y > 1: # self**2 or self**-2
1529# f = self._mul_Fsum(self, op)
1530# if x < 0:
1531# f = f._copy_0(_1_0)._ftruediv(f, op)
1532# return f
1533 elif x < 0: # self**-1 == 1 / self
1534 if r:
1535 return self._copy_0(_1_0)._ftruediv(self, op)
1536 else: # self**1 or self**0
1537 return self._pow_0_1(x, other) # self or 0.0
1538 elif not isscalar(x): # assert ...
1539 raise self._TypeError(op, other, txt=_not_scalar_)
1540 elif r and self._raiser(r, s): # non-zero residual**fractional
1541 # raise self._ResidualError(op, other, r, fractional_power=x)
1542 t = _stresidual(_non_zero_, r, fractional_power=x)
1543 raise self._Error(op, other, ResidualError, txt=t)
1544 # assert isscalar(s) and isscalar(x)
1545 return self._copy_0(s)._pow_2(x, other, op)
1547 def _ps_1(self, *less):
1548 '''(INTERNAL) Yield partials, 1-primed and subtract any C{less}.
1549 '''
1550 yield _1_0
1551 for p in self._ps:
1552 if p:
1553 yield p
1554 for p in less:
1555 if p:
1556 yield -p
1557 yield _N_1_0
1559 def _ps_n(self):
1560 '''(INTERNAL) Yield partials, negated.
1561 '''
1562 for p in self._ps:
1563 if p:
1564 yield -p
1566 def _ps_x(self, op, *factors): # see .fmath.Fhorner
1567 '''(INTERNAL) Yield all C{partials} times each B{C{factor}},
1568 in total, up to C{len(partials) * len(factors)} items.
1569 '''
1570 ps = self._ps
1571 if len(ps) < len(factors):
1572 ps, factors = factors, ps
1573 _f = _isfinite
1574 for f in factors:
1575 for p in ps:
1576 p *= f
1577 if _f(p):
1578 yield p
1579 else: # PYCHOK no cover
1580 self._finite(p, op) # throw ValueError
1582 @property_RO
1583 def real(self):
1584 '''Get the C{real} part of this instance (C{float}).
1586 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
1587 and properties L{Fsum.ceil}, L{Fsum.floor},
1588 L{Fsum.imag} and L{Fsum.residual}.
1589 '''
1590 return float(self._fprs)
1592 @property_RO
1593 def residual(self):
1594 '''Get this instance' residual (C{float} or C{int}), the
1595 C{sum(partials)} less the precision running sum C{fsum}.
1597 @note: If the C{residual is INT0}, the precision running
1598 C{fsum} is considered to be I{exact}.
1600 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
1601 '''
1602 return self._fprs2.residual
1604 def _raiser(self, r, s):
1605 '''(INTERNAL) Does the ratio C{r / s} exceed threshold?
1606 '''
1607 self._ratio = t = fabs((r / s) if s else r)
1608 return t > self._RESIDUAL
1610 def RESIDUAL(self, *threshold):
1611 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
1612 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
1614 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
1615 L{ResidualError}s in division and exponention, if
1616 C{None} restore the default set with env variable
1617 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
1618 current setting.
1620 @return: The previous C{RESIDUAL} setting (C{float}).
1622 @raise ValueError: Negative B{C{threshold}}.
1624 @note: A L{ResidualError} is thrown if the non-zero I{ratio}
1625 C{residual} / C{fsum} exceeds the B{C{threshold}}.
1626 '''
1627 r = self._RESIDUAL
1628 if threshold:
1629 t = threshold[0]
1630 t = Fsum._RESIDUAL if t is None else (
1631 float(t) if isscalar(t) else ( # for backward ...
1632 _0_0 if bool(t) else _1_0)) # ... compatibility
1633 if t < 0:
1634 u = self._unstr(self.RESIDUAL, *threshold)
1635 raise _ValueError(u, RESIDUAL=t, txt=_negative_)
1636 self._RESIDUAL = t
1637 return r
1639 def _ResidualError(self, op, other, residual):
1640 '''(INTERNAL) Non-zero B{C{residual}} etc.
1641 '''
1642 t = _stresidual(_non_zero_, residual, ratio=self._ratio,
1643 RESIDUAL=self._RESIDUAL)
1644 t = t.replace(_COMMASPACE_R_, _exceeds_R_)
1645 return self._Error(op, other, ResidualError, txt=t)
1647 def signOf(self, res=True):
1648 '''Determine the sign of this instance.
1650 @kwarg res: If C{True} consider, otherwise
1651 ignore the residual (C{bool}).
1653 @return: The sign (C{int}, -1, 0 or +1).
1654 '''
1655 s, r = self._fprs2 if res else (self._fprs, 0)
1656 return _signOf(s, -r)
1658 def toRepr(self, **prec_sep_fmt_lenc): # PYCHOK signature
1659 '''Return this C{Fsum} instance as representation.
1661 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for
1662 method L{Fsum2Tuple.toRepr} plus C{B{lenc}=True}
1663 (C{bool}) to in-/exclude the current C{[len]}
1664 of this L{Fsum} enclosed in I{[brackets]}.
1666 @return: This instance (C{repr}).
1667 '''
1668 return self._toT(self._fprs2.toRepr, **prec_sep_fmt_lenc)
1670 def toStr(self, **prec_sep_fmt_lenc): # PYCHOK signature
1671 '''Return this C{Fsum} instance as string.
1673 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for
1674 method L{Fsum2Tuple.toStr} plus C{B{lenc}=True}
1675 (C{bool}) to in-/exclude the current C{[len]}
1676 of this L{Fsum} enclosed in I{[brackets]}.
1678 @return: This instance (C{str}).
1679 '''
1680 return self._toT(self._fprs2.toStr, **prec_sep_fmt_lenc)
1682 def _toT(self, toT, fmt=Fmt.g, lenc=True, **kwds):
1683 '''(INTERNAL) Helper for C{toRepr} and C{toStr}.
1684 '''
1685 n = self.named3
1686 if lenc:
1687 n = Fmt.SQUARE(n, len(self))
1688 return _SPACE_(n, toT(fmt=fmt, **kwds))
1690 def _TypeError(self, op, other, **txt): # PYCHOK no cover
1691 '''(INTERNAL) Return a C{TypeError}.
1692 '''
1693 return self._Error(op, other, _TypeError, **txt)
1695 def _update(self): # see ._fset
1696 '''(INTERNAL) Zap all cached C{Property_RO} values.
1697 '''
1698 Fsum._fint2._update(self)
1699 Fsum._fprs ._update(self)
1700 Fsum._fprs2._update(self)
1701 return self
1703 def _ValueError(self, op, other, **txt): # PYCHOK no cover
1704 '''(INTERNAL) Return a C{ValueError}.
1705 '''
1706 return self._Error(op, other, _ValueError, **txt)
1708 def _ZeroDivisionError(self, op, other, **txt): # PYCHOK no cover
1709 '''(INTERNAL) Return a C{ZeroDivisionError}.
1710 '''
1711 return self._Error(op, other, _ZeroDivisionError, **txt)
1713_allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK assert, see Fsum._fset, -._update
1716def _Float_Int(arg, **name_Error):
1717 '''(INTERNAL) Unit of L{Fsum2Tuple} items.
1718 '''
1719 U = Int if isint(arg) else Float
1720 return U(arg, **name_Error)
1723class Fsum2Tuple(_NamedTuple):
1724 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
1725 and the C{residual}, the sum of the remaining partials. Each
1726 item is either C{float} or C{int}.
1728 @note: If the C{residual is INT0}, the C{fsum} is considered
1729 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
1730 '''
1731 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
1732 _Units_ = (_Float_Int, _Float_Int)
1734 @Property_RO
1735 def Fsum(self):
1736 '''Get this L{Fsum2Tuple} as an L{Fsum}.
1737 '''
1738 f = Fsum(name=self.name)
1739 return f._copy_0(*(s for s in reversed(self) if s))
1741 def is_exact(self):
1742 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
1743 '''
1744 return self.Fsum.is_exact()
1746 def is_integer(self):
1747 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
1748 '''
1749 return self.Fsum.is_integer()
1752class ResidualError(_ValueError):
1753 '''Error raised for an operation involving a L{pygeodesy.sums.Fsum}
1754 instance with a non-zero C{residual}, I{integer} or otherwise.
1756 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
1757 '''
1758 pass
1761try:
1762 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
1764 # make sure _fsum works as expected (XXX check
1765 # float.__getformat__('float')[:4] == 'IEEE'?)
1766 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
1767 del _fsum # nope, remove _fsum ...
1768 raise ImportError # ... use _fsum below
1770 Fsum._math_fsum = _fsum
1772 if _getenv('PYGEODESY_FSUM_PARTIALS', _fsum.__name__) == _fsum.__name__:
1773 _psum = _fsum # PYCHOK redef
1775except ImportError:
1777 def _fsum(xs):
1778 '''(INTERNAL) Precision summation, Python 2.5-.
1779 '''
1780 return Fsum(name=_fsum.__name__)._facc(xs, up=False)._fprs
1783def fsum(xs, floats=False):
1784 '''Precision floating point summation based on or like Python's C{math.fsum}.
1786 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or
1787 L{Fsum} instances).
1788 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}
1789 B{C{xs}} are known to be C{float}.
1791 @return: Precision C{fsum} (C{float}).
1793 @raise OverflowError: Partial C{2sum} overflow.
1795 @raise TypeError: Non-scalar B{C{xs}} value.
1797 @raise ValueError: Invalid or non-finite B{C{xs}} value.
1799 @note: Exceptions and I{non-finite} handling may differ if not
1800 based on Python's C{math.fsum}.
1802 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.
1803 '''
1804 return _fsum(xs if floats else _2floats(xs)) if xs else _0_0 # PYCHOK yield
1807def fsum_(*xs, **floats):
1808 '''Precision floating point summation of all positional arguments.
1810 @arg xs: Values to be added (C{scalar} or L{Fsum} instances),
1811 all positional.
1812 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}
1813 B{C{xs}} are known to be C{float}.
1815 @return: Precision C{fsum} (C{float}).
1817 @see: Function C{fsum}.
1818 '''
1819 return _fsum(xs if _xkwds_get(floats, floats=False) else
1820 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield
1823def fsumf_(*xs):
1824 '''Precision floating point summation L{fsum_}C{(*xs, floats=True)}.
1825 '''
1826 return _fsum(xs) if xs else _0_0
1829def fsum1(xs, floats=False):
1830 '''Precision floating point summation of a few arguments, 1-primed.
1832 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or
1833 L{Fsum} instances).
1834 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}
1835 B{C{xs}} are known to be C{float}.
1837 @return: Precision C{fsum} (C{float}).
1839 @see: Function C{fsum}.
1840 '''
1841 return _fsum(_1primed(xs if floats else _2floats(xs))) if xs else _0_0 # PYCHOK yield
1844def fsum1_(*xs, **floats):
1845 '''Precision floating point summation of a few arguments, 1-primed.
1847 @arg xs: Values to be added (C{scalar} or L{Fsum} instances),
1848 all positional.
1849 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}
1850 B{C{xs}} are known to be C{float}.
1852 @return: Precision C{fsum} (C{float}).
1854 @see: Function C{fsum}
1855 '''
1856 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) else
1857 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield
1860def fsum1f_(*xs):
1861 '''Precision floating point summation L{fsum1_}C{(*xs, floats=True)}.
1862 '''
1863 return _fsum(_1primed(xs)) if xs else _0_0
1866# **) MIT License
1867#
1868# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.
1869#
1870# Permission is hereby granted, free of charge, to any person obtaining a
1871# copy of this software and associated documentation files (the "Software"),
1872# to deal in the Software without restriction, including without limitation
1873# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1874# and/or sell copies of the Software, and to permit persons to whom the
1875# Software is furnished to do so, subject to the following conditions:
1876#
1877# The above copyright notice and this permission notice shall be included
1878# in all copies or substantial portions of the Software.
1879#
1880# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1881# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1882# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1883# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1884# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1885# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1886# OTHER DEALINGS IN THE SOFTWARE.