Coverage for pygeodesy/fsums.py: 96%

822 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-05-02 14:35 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Class L{Fsum} for precision floating point summation and I{running} 

5summation based on, respectively similar to Python's C{math.fsum}. 

6 

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}. 

11 

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}. 

16 

17Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater than 

18C{"0.0"} as the threshold to throw a L{ResidualError} for a division, power or 

19root operation of an L{Fsum} instance with a C{residual} I{ratio} exceeding 

20the threshold. See methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__} 

21and L{Fsum.__itruediv__}. 

22''' 

23# make sure int/int division yields float quotient, see .basics 

24from __future__ import division as _; del _ # PYCHOK semicolon 

25 

26from pygeodesy.basics import isbool, iscomplex, isint, isscalar, itemsorted, \ 

27 signOf, _signOf 

28from pygeodesy.constants import INT0, _isfinite, NEG0, _pos_self, \ 

29 _0_0, _1_0, _N_1_0, Float, Int 

30from pygeodesy.errors import _AssertionError, _OverflowError, _TypeError, \ 

31 _ValueError, _xError, _xError2, _xkwds_get, \ 

32 _ZeroDivisionError 

33from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _DOT_, \ 

34 _EQUAL_, _from_, _LANGLE_, _NOTEQUAL_, \ 

35 _not_finite_, _PERCENT_, _PLUS_, _RANGLE_, \ 

36 _SLASH_, _SPACE_, _STAR_, _UNDER_ 

37from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2 

38from pygeodesy.named import _Named, _NamedTuple, _NotImplemented, Fmt, unstr 

39from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \ 

40 Property_RO, property_RO 

41# from pygeodesy.streprs import Fmt, unstr # from .named 

42# from pygeodesy.units import Float, Int # from .constants 

43 

44from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp 

45 

46__all__ = _ALL_LAZY.fsums 

47__version__ = '24.05.02' 

48 

49_add_op_ = _PLUS_ # in .auxilats.auxAngle 

50_eq_op_ = _EQUAL_ * 2 # _DEQUAL_ 

51_div_ = 'div' 

52_floordiv_op_ = _SLASH_ * 2 # _DSLASH_ 

53_fset_op_ = _EQUAL_ 

54_ge_op_ = _RANGLE_ + _EQUAL_ 

55_gt_op_ = _RANGLE_ 

56_iadd_op_ = _add_op_ + _EQUAL_ # in .auxilats.auxAngle, .fstats 

57_integer_ = 'integer' 

58_isinstance = isinstance 

59_le_op_ = _LANGLE_ + _EQUAL_ 

60_lt_op_ = _LANGLE_ 

61_mod_ = 'mod' 

62_mod_op_ = _PERCENT_ 

63_mul_op_ = _STAR_ 

64_ne_op_ = _NOTEQUAL_ 

65_non_zero_ = 'non-zero' 

66_pow_op_ = _STAR_ * 2 # _DSTAR_ 

67_significant_ = 'significant' 

68_sub_op_ = _DASH_ # in .auxilats.auxAngle 

69_threshold_ = 'threshold' 

70_truediv_op_ = _SLASH_ 

71_divmod_op_ = _floordiv_op_ + _mod_op_ 

72_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle 

73 

74 

75def _2delta(*ab): 

76 '''(INTERNAL) Helper for C{Fsum._fsum2}. 

77 ''' 

78 try: 

79 a, b = _2sum(*ab) 

80 except _OverflowError: 

81 a, b = ab 

82 return float(a if fabs(a) > fabs(b) else b) 

83 

84 

85def _2error(unused): 

86 '''(INTERNAL) Throw a C{not-finite} exception. 

87 ''' 

88 raise ValueError(_not_finite_) 

89 

90 

91def _2float(index=None, **name_value): # in .fmath, .fstats 

92 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite. 

93 ''' 

94 n, v = name_value.popitem() # _xkwds_item2(name_value) 

95 try: 

96 v = float(v) 

97 return v if _isfinite(v) else _2error(v) 

98 except Exception as X: 

99 raise _xError(X, Fmt.INDEX(n, index), v) 

100 

101 

102def _X_ps(X): # for _2floats only 

103 return X._ps 

104 

105 

106def _2floats(xs, origin=0, _X=_X_ps, _x=float): 

107 '''(INTERNAL) Yield each B{C{xs}} as a C{float}. 

108 ''' 

109 try: 

110 i, x = origin, None 

111 _fin = _isfinite 

112 _FsT = _Fsum_Fsum2Tuple_types 

113 _is = _isinstance 

114 for x in xs: 

115 if _is(x, _FsT): 

116 for p in _X(x._Fsum): 

117 yield p 

118 else: 

119 f = _x(x) 

120 yield f if _fin(f) else _2error(f) 

121 i += 1 

122 except Exception as X: 

123 raise _xError(X, Fmt.INDEX(xs=i), x) 

124 

125 

126def _Fsumf_(*xs): # floats=True, in .auxLat, ... 

127 '''(INTERNAL) An C{Fsum} of I{known scalars}. 

128 ''' 

129 return Fsum()._facc_scalar(xs, up=False) 

130 

131 

132def _Fsum1f_(*xs): # floats=True, in .albers, ... 

133 '''(INTERNAL) An C{Fsum} of I{known scalars}, 1-primed. 

134 ''' 

135 return Fsum()._facc_scalar(_1primed(xs), up=False) 

136 

137 

138def _2halfeven(s, r, p): 

139 '''(INTERNAL) Round half-even. 

140 ''' 

141 if (p > 0 and r > 0) or \ 

142 (p < 0 and r < 0): # signs match 

143 r *= 2 

144 t = s + r 

145 if r == (t - s): 

146 s = t 

147 return s 

148 

149 

150def _isFsum(x): 

151 '''(INTERNAL) Is C{x} an C{Fsum} instance? 

152 ''' 

153 return _isinstance(x, Fsum) 

154 

155 

156def _isFsumTuple(x): 

157 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance? 

158 ''' 

159 return _isinstance(x, _Fsum_Fsum2Tuple_types) 

160 

161 

162def _1_Over(x, op, **raiser_RESIDUAL): # vs _1_over 

163 '''(INTERNAL) Return C{Fsum(1) / B{x}}. 

164 ''' 

165 return _Psum_(_1_0)._ftruediv(x, op, **raiser_RESIDUAL) 

166 

167 

168def _1primed(xs): # in .fmath 

169 '''(INTERNAL) 1-Primed summation of iterable C{xs} 

170 items, all I{known} to be C{finite float}. 

171 ''' 

172 yield _1_0 

173 for x in xs: 

174 yield x 

175 yield _N_1_0 

176 

177 

178def _psum(ps): # PYCHOK used! 

179 '''(INTERNAL) Partials summation, updating C{ps}. 

180 ''' 

181 # assert _isinstance(ps, list) 

182 i = len(ps) - 1 

183 s = _0_0 if i < 0 else ps[i] 

184 _2s = _2sum 

185 while i > 0: 

186 i -= 1 

187 s, r = _2s(s, ps[i]) 

188 if r: # sum(ps) became inexact 

189 if s: 

190 ps[i:] = r, s 

191 if i > 0: 

192 s = _2halfeven(s, r, ps[i-1]) 

193 break # return s 

194 s = r # PYCHOK no cover 

195 ps[i:] = s, 

196 return s 

197 

198 

199def _Psum(ps, **name): 

200 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}. 

201 ''' 

202 F = Fsum(**name) if name else Fsum() 

203 if ps: 

204 F._ps[:] = ps 

205 F._n = len(F._ps) 

206 return F 

207 

208 

209def _Psum_(*ps, **name): 

210 '''(INTERNAL) Return an C{Fsum} from 1 or 2 known scalar(s) C{ps}. 

211 ''' 

212 return _Psum(ps, **name) 

213 

214 

215def _2scalar2(other): 

216 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int}, 

217 C{float} or C{as-is} and C{r} the residual of C{as-is}. 

218 ''' 

219 if _isFsumTuple(other): 

220 s, r = other._fint2 

221 if r: 

222 s, r = other._fprs2 

223 if r: # PYCHOK no cover 

224 s = other # L{Fsum} as-is 

225 else: 

226 r = 0 

227 s = other # C{type} as-is 

228 if isint(s, both=True): 

229 s = int(s) 

230 return s, r 

231 

232 

233def _s_r(s, r): 

234 '''(INTERNAL) Return C{(s, r)}, I{ordered}. 

235 ''' 

236 if r: 

237 if fabs(s) < fabs(r): 

238 s, r = r, (s or INT0) 

239 else: 

240 r = INT0 

241 return s, r 

242 

243 

244def _strcomplex(s, *args): 

245 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}. 

246 ''' 

247 c = _strcomplex.__name__[4:] 

248 n = _DASH_(len(args), _arg_) 

249 t = unstr(pow, *args) 

250 return _SPACE_(c, s, _from_, n, t) 

251 

252 

253def _stresidual(prefix, residual, R=0, **mod_ratio): 

254 '''(INTERNAL) Residual error txt C{str}. 

255 ''' 

256 p = _stresidual.__name__[3:] 

257 t = Fmt.PARENSPACED(p, Fmt(residual)) 

258 for n, v in itemsorted(mod_ratio): 

259 p = Fmt.PARENSPACED(n, Fmt(v)) 

260 t = _COMMASPACE_(t, p) 

261 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_) 

262 

263 

264def _2sum(a, b): # by .testFmath 

265 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual). 

266 ''' 

267 s = a + b 

268 if _isfinite(s): 

269 if fabs(a) < fabs(b): 

270 b, a = a, b 

271 return s, (b - (s - a)) 

272 u = unstr(_2sum, a, b) 

273 t = Fmt.PARENSPACED(_not_finite_, s) 

274 raise _OverflowError(u, txt=t) 

275 

276 

277def _threshold(threshold): 

278 '''(INTERNAL) Get the L{ResidualError}s threshold. 

279 ''' 

280 try: 

281 t = float(threshold) or _0_0 

282 return t if _isfinite(t) else _2error(t) # PYCHOK None 

283 except Exception as x: 

284 raise ResidualError(threshold=threshold, cause=x) 

285 

286 

287class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase 

288 '''Precision floating point summation and I{running} summation. 

289 

290 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate, 

291 I{running}, precision floating point summations. Accumulation may continue after any 

292 intermediate, I{running} summuation. 

293 

294 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances, 

295 any C{type} having method C{__float__} to convert the C{scalar} to a single 

296 C{float}, except C{complex}. 

297 

298 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from 

299 Python's C{math.fsum}. 

300 

301 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/Python/ 

302 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}, 

303 U{Kahan<https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein 

304 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+ 

305 file I{Modules/mathmodule.c} and the issue log U{Full precision summation 

306 <https://Bugs.Python.org/issue2819>}. 

307 ''' 

308 _math_fsum = None 

309 _n = 0 

310# _ps = [] # partial sums 

311# _ps_max = 0 # max(Fsum._ps_max, len(Fsum._ps)) 

312 _RESIDUAL = _threshold(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)) 

313 

314 def __init__(self, *xs, **name_RESIDUAL): 

315 '''New L{Fsum} for I{running} precision floating point summation. 

316 

317 @arg xs: No, one or more items to add (each C{scalar} or an L{Fsum} 

318 or L{Fsum2Tuple} instance), all positional. 

319 @kwarg name_RESIDUAL: Optional C{B{name}=NN} for this L{Fsum} and 

320 the C{B{RESIDUAL}=0.0} threshold for L{ResidualError}s. 

321 

322 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}. 

323 ''' 

324 if name_RESIDUAL: 

325 

326 def _n_r(name=NN, RESIDUAL=None): 

327 return name, RESIDUAL 

328 

329 n, r = _n_r(**name_RESIDUAL) 

330 if r is not None: 

331 self.RESIDUAL(r) 

332 if n: 

333 self.name = n 

334 

335 self._ps = [] # [_0_0], see L{Fsum._fprs} 

336 if xs: 

337 self._facc_1(xs, up=False) 

338 

339 def __abs__(self): 

340 '''Return this instance' absolute value as an L{Fsum}. 

341 ''' 

342 s = self.signOf() # == self._cmp_0(0) 

343 return (-self) if s < 0 else self._copy_2(self.__abs__) 

344 

345 def __add__(self, other): 

346 '''Return C{B{self} + B{other}} as an L{Fsum}. 

347 

348 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}. 

349 

350 @return: The sum (L{Fsum}). 

351 

352 @see: Method L{Fsum.__iadd__}. 

353 ''' 

354 f = self._copy_2(self.__add__) 

355 return f._fadd(other, _add_op_) 

356 

357 def __bool__(self): # PYCHOK not special in Python 2- 

358 '''Return C{True} if this instance is I{exactly} non-zero. 

359 ''' 

360 s, r = self._fprs2 

361 return bool(s or r) and s != -r # == self != 0 

362 

363 def __ceil__(self): # PYCHOK not special in Python 2- 

364 '''Return this instance' C{math.ceil} as C{int} or C{float}. 

365 

366 @return: An C{int} in Python 3+, but C{float} in Python 2-. 

367 

368 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}. 

369 ''' 

370 return self.ceil 

371 

372 def __cmp__(self, other): # PYCHOK no cover 

373 '''Compare this with an other instance or C{scalar}, Python 2-. 

374 

375 @return: -1, 0 or +1 (C{int}). 

376 

377 @raise TypeError: Incompatible B{C{other}} C{type}. 

378 ''' 

379 s = self._cmp_0(other, self.cmp.__name__) 

380 return _signOf(s, 0) 

381 

382 def __divmod__(self, other, **raiser_RESIDUAL): 

383 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple} 

384 with quotient C{div} an C{int} in Python 3+ or C{float} 

385 in Python 2- and remainder C{mod} an L{Fsum} instance. 

386 

387 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus. 

388 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

389 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

390 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

391 

392 @raise ResidualError: Non-zero, significant residual or invalid 

393 B{C{RESIDUAL}}. 

394 

395 @see: Method L{Fsum.__itruediv__}. 

396 ''' 

397 f = self._copy_2(self.__divmod__) 

398 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL) 

399 

400 def __eq__(self, other): 

401 '''Compare this with an other instance or C{scalar}. 

402 ''' 

403 return self._cmp_0(other, _eq_op_) == 0 

404 

405 def __float__(self): 

406 '''Return this instance' current, precision running sum as C{float}. 

407 

408 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}. 

409 ''' 

410 return float(self._fprs) 

411 

412 def __floor__(self): # PYCHOK not special in Python 2- 

413 '''Return this instance' C{math.floor} as C{int} or C{float}. 

414 

415 @return: An C{int} in Python 3+, but C{float} in Python 2-. 

416 

417 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}. 

418 ''' 

419 return self.floor 

420 

421 def __floordiv__(self, other): 

422 '''Return C{B{self} // B{other}} as an L{Fsum}. 

423 

424 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

425 

426 @return: The C{floor} quotient (L{Fsum}). 

427 

428 @see: Methods L{Fsum.__ifloordiv__}. 

429 ''' 

430 f = self._copy_2(self.__floordiv__) 

431 return f._floordiv(other, _floordiv_op_) 

432 

433 def __format__(self, *other): # PYCHOK no cover 

434 '''Not implemented.''' 

435 return _NotImplemented(self, *other) 

436 

437 def __ge__(self, other): 

438 '''Compare this with an other instance or C{scalar}. 

439 ''' 

440 return self._cmp_0(other, _ge_op_) >= 0 

441 

442 def __gt__(self, other): 

443 '''Compare this with an other instance or C{scalar}. 

444 ''' 

445 return self._cmp_0(other, _gt_op_) > 0 

446 

447 def __hash__(self): # PYCHOK no cover 

448 '''Return this instance' C{hash}. 

449 ''' 

450 return hash(self._ps) # XXX id(self)? 

451 

452 def __iadd__(self, other): 

453 '''Apply C{B{self} += B{other}} to this instance. 

454 

455 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} instance. 

456 

457 @return: This instance, updated (L{Fsum}). 

458 

459 @raise TypeError: Invalid B{C{other}}, not 

460 C{scalar} nor L{Fsum}. 

461 

462 @see: Methods L{Fsum.fadd} and L{Fsum.fadd_}. 

463 ''' 

464 return self._fadd(other, _iadd_op_) 

465 

466 def __ifloordiv__(self, other): 

467 '''Apply C{B{self} //= B{other}} to this instance. 

468 

469 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

470 

471 @return: This instance, updated (L{Fsum}). 

472 

473 @raise ResidualError: Non-zero, significant residual 

474 in B{C{other}}. 

475 

476 @raise TypeError: Invalid B{C{other}} type. 

477 

478 @raise ValueError: Invalid or non-finite B{C{other}}. 

479 

480 @raise ZeroDivisionError: Zero B{C{other}}. 

481 

482 @see: Methods L{Fsum.__itruediv__}. 

483 ''' 

484 return self._floordiv(other, _floordiv_op_ + _fset_op_) 

485 

486 def __imatmul__(self, other): # PYCHOK no cover 

487 '''Not implemented.''' 

488 return _NotImplemented(self, other) 

489 

490 def __imod__(self, other): 

491 '''Apply C{B{self} %= B{other}} to this instance. 

492 

493 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus. 

494 

495 @return: This instance, updated (L{Fsum}). 

496 

497 @see: Method L{Fsum.__divmod__}. 

498 ''' 

499 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod 

500 

501 def __imul__(self, other): 

502 '''Apply C{B{self} *= B{other}} to this instance. 

503 

504 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor. 

505 

506 @return: This instance, updated (L{Fsum}). 

507 

508 @raise OverflowError: Partial C{2sum} overflow. 

509 

510 @raise TypeError: Invalid B{C{other}} type. 

511 

512 @raise ValueError: Invalid or non-finite B{C{other}}. 

513 ''' 

514 return self._fmul(other, _mul_op_ + _fset_op_) 

515 

516 def __int__(self): 

517 '''Return this instance as an C{int}. 

518 

519 @see: Methods L{Fsum.int_float}, L{Fsum.__ceil__} 

520 and L{Fsum.__floor__} and properties 

521 L{Fsum.ceil} and L{Fsum.floor}. 

522 ''' 

523 i, _ = self._fint2 

524 return i 

525 

526 def __invert__(self): # PYCHOK no cover 

527 '''Not implemented.''' 

528 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567 

529 return _NotImplemented(self) 

530 

531 def __ipow__(self, other, *mod, **raiser_RESIDUAL): # PYCHOK 2 vs 3 args 

532 '''Apply C{B{self} **= B{other}} to this instance. 

533 

534 @arg other: The exponent (C{scalar}, L{Fsum} or L{Fsum2Tuple}). 

535 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument 

536 C{pow(B{self}, B{other}, B{mod})} version. 

537 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

538 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

539 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

540 

541 @return: This instance, updated (L{Fsum}). 

542 

543 @note: If B{C{mod}} is given, the result will be an C{integer} 

544 L{Fsum} in Python 3+ if this instance C{is_integer} or 

545 set to C{as_integer} and B{C{mod}} is given as C{None}. 

546 

547 @raise OverflowError: Partial C{2sum} overflow. 

548 

549 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual 

550 is non-zero and significant and either 

551 B{C{other}} is a fractional or negative 

552 C{scalar} or B{C{mod}} is given and not 

553 C{None}. 

554 

555 @raise TypeError: Invalid B{C{other}} type or 3-argument C{pow} 

556 invocation failed. 

557 

558 @raise ValueError: If B{C{other}} is a negative C{scalar} and this 

559 instance is C{0} or B{C{other}} is a fractional 

560 C{scalar} and this instance is negative or has a 

561 non-zero and significant residual or B{C{mod}} 

562 is given as C{0}. 

563 

564 @see: CPython function U{float_pow<https://GitHub.com/ 

565 python/cpython/blob/main/Objects/floatobject.c>}. 

566 ''' 

567 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser_RESIDUAL) 

568 

569 def __isub__(self, other): 

570 '''Apply C{B{self} -= B{other}} to this instance. 

571 

572 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}. 

573 

574 @return: This instance, updated (L{Fsum}). 

575 

576 @raise TypeError: Invalid B{C{other}} type. 

577 

578 @see: Method L{Fsum.fadd}. 

579 ''' 

580 return self._fsub(other, _isub_op_) 

581 

582 def __iter__(self): 

583 '''Return an C{iter}ator over a C{partials} duplicate. 

584 ''' 

585 return iter(self.partials) 

586 

587 def __itruediv__(self, other, **raiser_RESIDUAL): 

588 '''Apply C{B{self} /= B{other}} to this instance. 

589 

590 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

591 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

592 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

593 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

594 

595 @return: This instance, updated (L{Fsum}). 

596 

597 @raise OverflowError: Partial C{2sum} overflow. 

598 

599 @raise ResidualError: Non-zero, significant residual or invalid 

600 B{C{RESIDUAL}}. 

601 

602 @raise TypeError: Invalid B{C{other}} type. 

603 

604 @raise ValueError: Invalid or non-finite B{C{other}}. 

605 

606 @raise ZeroDivisionError: Zero B{C{other}}. 

607 

608 @see: Method L{Fsum.__ifloordiv__}. 

609 ''' 

610 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL) 

611 

612 def __le__(self, other): 

613 '''Compare this with an other instance or C{scalar}. 

614 ''' 

615 return self._cmp_0(other, _le_op_) <= 0 

616 

617 def __len__(self): 

618 '''Return the number of values accumulated (C{int}). 

619 ''' 

620 return self._n 

621 

622 def __lt__(self, other): 

623 '''Compare this with an other instance or C{scalar}. 

624 ''' 

625 return self._cmp_0(other, _lt_op_) < 0 

626 

627 def __matmul__(self, other): # PYCHOK no cover 

628 '''Not implemented.''' 

629 return _NotImplemented(self, other) 

630 

631 def __mod__(self, other): 

632 '''Return C{B{self} % B{other}} as an L{Fsum}. 

633 

634 @see: Method L{Fsum.__imod__}. 

635 ''' 

636 f = self._copy_2(self.__mod__) 

637 return f._fdivmod2(other, _mod_op_).mod 

638 

639 def __mul__(self, other): 

640 '''Return C{B{self} * B{other}} as an L{Fsum}. 

641 

642 @see: Method L{Fsum.__imul__}. 

643 ''' 

644 f = self._copy_2(self.__mul__) 

645 return f._fmul(other, _mul_op_) 

646 

647 def __ne__(self, other): 

648 '''Compare this with an other instance or C{scalar}. 

649 ''' 

650 return self._cmp_0(other, _ne_op_) != 0 

651 

652 def __neg__(self): 

653 '''Return I{a copy of} this instance, I{negated}. 

654 ''' 

655 f = self._copy_2(self.__neg__) 

656 return f._fset(self._neg) 

657 

658 def __pos__(self): 

659 '''Return this instance I{as-is}, like C{float.__pos__()}. 

660 ''' 

661 return self if _pos_self else self._copy_2(self.__pos__) 

662 

663 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args 

664 '''Return C{B{self}**B{other}} as an L{Fsum}. 

665 

666 @see: Method L{Fsum.__ipow__}. 

667 ''' 

668 f = self._copy_2(self.__pow__) 

669 return f._fpow(other, _pow_op_, *mod) 

670 

671 def __radd__(self, other): 

672 '''Return C{B{other} + B{self}} as an L{Fsum}. 

673 

674 @see: Method L{Fsum.__iadd__}. 

675 ''' 

676 f = self._copy_2r(other, self.__radd__) 

677 return f._fadd(self, _add_op_) 

678 

679 def __rdivmod__(self, other): 

680 '''Return C{divmod(B{other}, B{self})} as 2-tuple 

681 C{(quotient, remainder)}. 

682 

683 @see: Method L{Fsum.__divmod__}. 

684 ''' 

685 f = self._copy_2r(other, self.__rdivmod__) 

686 return f._fdivmod2(self, _divmod_op_) 

687 

688# def __repr__(self): 

689# '''Return the default C{repr(this)}. 

690# ''' 

691# return self.toRepr(lenc=True) 

692 

693 def __rfloordiv__(self, other): 

694 '''Return C{B{other} // B{self}} as an L{Fsum}. 

695 

696 @see: Method L{Fsum.__ifloordiv__}. 

697 ''' 

698 f = self._copy_2r(other, self.__rfloordiv__) 

699 return f._floordiv(self, _floordiv_op_) 

700 

701 def __rmatmul__(self, other): # PYCHOK no cover 

702 '''Not implemented.''' 

703 return _NotImplemented(self, other) 

704 

705 def __rmod__(self, other): 

706 '''Return C{B{other} % B{self}} as an L{Fsum}. 

707 

708 @see: Method L{Fsum.__imod__}. 

709 ''' 

710 f = self._copy_2r(other, self.__rmod__) 

711 return f._fdivmod2(self, _mod_op_).mod 

712 

713 def __rmul__(self, other): 

714 '''Return C{B{other} * B{self}} as an L{Fsum}. 

715 

716 @see: Method L{Fsum.__imul__}. 

717 ''' 

718 f = self._copy_2r(other, self.__rmul__) 

719 return f._fmul(self, _mul_op_) 

720 

721 def __round__(self, *ndigits): # PYCHOK Python 3+ 

722 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}. 

723 

724 @arg ndigits: Optional number of digits (C{int}). 

725 ''' 

726 f = self._copy_2(self.__round__) 

727 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__> 

728 return f._fset(round(float(self), *ndigits)) # can be C{int} 

729 

730 def __rpow__(self, other, *mod): 

731 '''Return C{B{other}**B{self}} as an L{Fsum}. 

732 

733 @see: Method L{Fsum.__ipow__}. 

734 ''' 

735 f = self._copy_2r(other, self.__rpow__) 

736 return f._fpow(self, _pow_op_, *mod) 

737 

738 def __rsub__(self, other): 

739 '''Return C{B{other} - B{self}} as L{Fsum}. 

740 

741 @see: Method L{Fsum.__isub__}. 

742 ''' 

743 f = self._copy_2r(other, self.__rsub__) 

744 return f._fsub(self, _sub_op_) 

745 

746 def __rtruediv__(self, other, **raiser_RESIDUAL): 

747 '''Return C{B{other} / B{self}} as an L{Fsum}. 

748 

749 @see: Method L{Fsum.__itruediv__}. 

750 ''' 

751 f = self._copy_2r(other, self.__rtruediv__) 

752 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL) 

753 

754 def __str__(self): 

755 '''Return the default C{str(self)}. 

756 ''' 

757 return self.toStr(lenc=True) 

758 

759 def __sub__(self, other): 

760 '''Return C{B{self} - B{other}} as an L{Fsum}. 

761 

762 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}. 

763 

764 @return: The difference (L{Fsum}). 

765 

766 @see: Method L{Fsum.__isub__}. 

767 ''' 

768 f = self._copy_2(self.__sub__) 

769 return f._fsub(other, _sub_op_) 

770 

771 def __truediv__(self, other, **raiser_RESIDUAL): 

772 '''Return C{B{self} / B{other}} as an L{Fsum}. 

773 

774 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

775 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

776 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

777 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

778 

779 @return: The quotient (L{Fsum}). 

780 

781 @raise ResidualError: Non-zero, significant residual or invalid 

782 B{C{RESIDUAL}}. 

783 

784 @see: Method L{Fsum.__itruediv__}. 

785 ''' 

786 f = self._copy_2(self.__truediv__) 

787 return f._ftruediv(other, _truediv_op_, **raiser_RESIDUAL) 

788 

789 __trunc__ = __int__ 

790 

791 if _sys_version_info2 < (3, 0): # PYCHOK no cover 

792 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions> 

793 __div__ = __truediv__ 

794 __idiv__ = __itruediv__ 

795 __long__ = __int__ 

796 __nonzero__ = __bool__ 

797 __rdiv__ = __rtruediv__ 

798 

799 def as_integer_ratio(self): 

800 '''Return this instance as the ratio of 2 integers. 

801 

802 @return: 2-Tuple C{(numerator, denominator)} both 

803 C{int} and with positive C{denominator}. 

804 

805 @see: Standard C{float.as_integer_ratio} in Python 3+. 

806 ''' 

807 n, r = self._fint2 

808 if r: 

809 i, d = float(r).as_integer_ratio() 

810 n *= d 

811 n += i 

812 else: # PYCHOK no cover 

813 d = 1 

814 return n, d 

815 

816 @property_RO 

817 def as_iscalar(self): 

818 '''Get this instance I{as-is} (L{Fsum}) or as C{scalar} iff scalar. 

819 ''' 

820 s, r = self._fprs2 

821 return self if r else s 

822 

823 @property_RO 

824 def ceil(self): 

825 '''Get this instance' C{ceil} value (C{int} in Python 3+, 

826 but C{float} in Python 2-). 

827 

828 @note: The C{ceil} takes the C{residual} into account. 

829 

830 @see: Method L{Fsum.int_float} and properties L{Fsum.floor}, 

831 L{Fsum.imag} and L{Fsum.real}. 

832 ''' 

833 s, r = self._fprs2 

834 c = _ceil(s) + int(r) - 1 

835 while r > (c - s): # (s + r) > c 

836 c += 1 

837 return c 

838 

839 cmp = __cmp__ 

840 

841 def _cmp_0(self, other, op): 

842 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison. 

843 ''' 

844 if _isFsumTuple(other): 

845 s = _fsum(self._ps_1primed(*other._ps)) 

846 elif self._scalar(other, op): 

847 s = _fsum(self._ps_1primed(other)) 

848 else: 

849 s = self.signOf() # res=True 

850 return s 

851 

852 def copy(self, deep=False, name=NN): 

853 '''Copy this instance, C{shallow} or B{C{deep}}. 

854 

855 @return: The copy (L{Fsum}). 

856 ''' 

857 f = _Named.copy(self, deep=deep, name=name) 

858 if f._ps is self._ps: 

859 f._ps = list(self._ps) # separate list 

860 if not deep: 

861 f._n = 1 

862 return f 

863 

864 def _copy_2(self, which, name=NN): 

865 '''(INTERNAL) Copy for I{dyadic} operators. 

866 ''' 

867 n = name or which.__name__ 

868 # NOT .classof due to .Fdot(a, *b) args, etc. 

869 f = _Named.copy(self, deep=False, name=n) 

870 # assert f._n == self._n 

871 f._ps = list(self._ps) # separate list 

872 return f 

873 

874 def _copy_2r(self, other, which): 

875 '''(INTERNAL) Copy for I{reverse-dyadic} operators. 

876 ''' 

877 return other._copy_2(which) if _isFsum(other) else \ 

878 self._copy_2(which)._fset(other) 

879 

880# def _copy_RESIDUAL(self, other): 

881# '''(INTERNAL) Copy C{other._RESIDUAL}. 

882# ''' 

883# R = other._RESIDUAL 

884# if R is not Fsum._RESIDUAL: 

885# self._RESIDUAL = R 

886 

887 divmod = __divmod__ 

888 

889 def _Error(self, op, other, Error, **txt_cause): 

890 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}. 

891 ''' 

892 return Error(_SPACE_(self.as_iscalar, op, other), **txt_cause) 

893 

894 def _ErrorX(self, X, op, other, *mod): 

895 '''(INTERNAL) Format the caught exception C{X}. 

896 ''' 

897 E, t = _xError2(X) 

898 if mod: 

899 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t) 

900 return self._Error(op, other, E, txt=t, cause=X) 

901 

902 def _ErrorXs(self, X, xs, **kwds): # in .fmath 

903 '''(INTERNAL) Format the caught exception C{X}. 

904 ''' 

905 E, t = _xError2(X) 

906 u = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds) 

907 return E(u, txt=t, cause=X) 

908 

909 def _facc(self, xs, up=True, **origin_X_x): 

910 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s. 

911 ''' 

912 if xs: 

913 _xs = _2floats(xs, **origin_X_x) # PYCHOK yield 

914 ps = self._ps 

915 ps[:] = self._ps_acc(list(ps), _xs, up=up) 

916 return self 

917 

918 def _facc_1(self, xs, **up): 

919 '''(INTERNAL) Accumulate 0, 1 or more C{scalars} or L{Fsum}s, 

920 all positional C{xs} in the caller of this method. 

921 ''' 

922 return self._fadd(xs[0], _add_op_, **up) if len(xs) == 1 else \ 

923 self._facc(xs, origin=1, **up) 

924 

925 def _facc_neg(self, xs, **up_origin): 

926 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s, negated. 

927 ''' 

928 def _N(X): 

929 return X._ps_neg 

930 

931 def _n(x): 

932 return -float(x) 

933 

934 return self._facc(xs, _X=_N, _x=_n, **up_origin) 

935 

936 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath 

937 '''(INTERNAL) Add each C{xs} as C{float(x**power)}. 

938 ''' 

939 def _Pow4(p): 

940 r = 0 

941 if _isFsumTuple(p): 

942 s, r = p._fprs2 

943 if r: 

944 m = Fsum._pow 

945 else: # scalar 

946 return _Pow4(s) 

947 elif isint(p, both=True) and int(p) >= 0: 

948 p = s = int(p) 

949 m = Fsum._pow_int 

950 else: 

951 p = s = _2float(power=p) 

952 m = Fsum._pow_scalar 

953 return m, p, s, r 

954 

955 _Pow, p, s, r = _Pow4(power) 

956 if p: # and xs: 

957 op = which.__name__ 

958 _isF = _isFsum 

959 _pow = self._pow_2_3 

960 

961 def _P(X): 

962 f = _Pow(X, p, power, op, **raiser_RESIDUAL) 

963 return f._ps if _isF(f) else (f,) 

964 

965 def _p(x): 

966 x = float(x) 

967 f = _pow(x, s, power, op, **raiser_RESIDUAL) 

968 if f and r: 

969 f *= _pow(x, r, power, op, **raiser_RESIDUAL) 

970 return f 

971 

972 f = self._facc(xs, origin=1, _X=_P, _x=_p) 

973 else: 

974 f = self._facc_scalar_(float(len(xs))) # x**0 == 1 

975 return f 

976 

977 def _facc_scalar(self, xs, **up): 

978 '''(INTERNAL) Accumulate all C{xs}, known to be scalar. 

979 ''' 

980 if xs: 

981 _ = self._ps_acc(self._ps, xs, **up) 

982 return self 

983 

984 def _facc_scalar_(self, *xs, **up): 

985 '''(INTERNAL) Accumulate all positional C{xs}, known to be scalar. 

986 ''' 

987 if xs: 

988 _ = self._ps_acc(self._ps, xs, **up) 

989 return self 

990 

991# def _facc_up(self, up=True): 

992# '''(INTERNAL) Update the C{partials}, by removing 

993# and re-accumulating the final C{partial}. 

994# ''' 

995# ps = self._ps 

996# while len(ps) > 1: 

997# p = ps.pop() 

998# if p: 

999# n = self._n 

1000# _ = self._ps_acc(ps, (p,), up=False) 

1001# self._n = n 

1002# break 

1003# return self._update() if up else self 

1004 

1005 def fadd(self, xs=()): 

1006 '''Add all items from an iterable to this instance. 

1007 

1008 @arg xs: Iterable of items to add (each C{scalar} 

1009 or an L{Fsum} or L{Fsum2Tuple} instance). 

1010 

1011 @return: This instance (L{Fsum}). 

1012 

1013 @raise OverflowError: Partial C{2sum} overflow. 

1014 

1015 @raise TypeError: An invalid B{C{xs}} item. 

1016 

1017 @raise ValueError: Invalid or non-finite B{C{xs}} value. 

1018 ''' 

1019 if _isFsumTuple(xs): 

1020 self._facc_scalar(xs._ps) # tuple(xs._ps) 

1021 elif isscalar(xs): # for backward compatibility 

1022 self._facc_scalar_(_2float(x=xs)) # PYCHOK no cover 

1023 elif xs: # assert isiterable(xs) 

1024 self._facc(xs) 

1025 return self 

1026 

1027 def fadd_(self, *xs): 

1028 '''Add all positional arguments to this instance. 

1029 

1030 @arg xs: Values to add (each C{scalar} or an L{Fsum} 

1031 or L{Fsum2Tuple} instance), all positional. 

1032 

1033 @see: Method L{Fsum.fadd} for further details. 

1034 ''' 

1035 return self._facc_1(xs) 

1036 

1037 def _fadd(self, other, op, **up): # in .fmath.Fhorner 

1038 '''(INTERNAL) Apply C{B{self} += B{other}}. 

1039 ''' 

1040 if _isFsumTuple(other): 

1041 self._facc_scalar(other._ps, **up) # tuple 

1042 elif self._scalar(other, op): 

1043 self._facc_scalar_(other, **up) 

1044 return self 

1045 

1046 fcopy = copy # for backward compatibility 

1047 fdiv = __itruediv__ # for backward compatibility 

1048 fdivmod = __divmod__ # for backward compatibility 

1049 

1050 def _fdivmod2(self, other, op, **raiser_RESIDUAL): 

1051 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}. 

1052 ''' 

1053 # result mostly follows CPython function U{float_divmod 

1054 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>}, 

1055 # but at least divmod(-3, 2) equals Cpython's result (-2, 1). 

1056 q = self._copy_2(self._fdivmod2) 

1057 q = q._ftruediv(other, op, **raiser_RESIDUAL).floor 

1058 if q: # == float // other == floor(float / other) 

1059 self -= Fsum(other) * q # NO Fsum2Tuple.__mul__! 

1060 

1061 s = signOf(other) # make signOf(self) == signOf(other) 

1062 if s and self.signOf() == -s: # PYCHOK no cover 

1063 self += other 

1064 q -= 1 

1065# t = self.signOf() 

1066# if t and t != s: 

1067# raise self._Error(op, other, _AssertionError, txt=signOf.__name__) 

1068 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2- 

1069 

1070 def _finite(self, other, op=None): 

1071 '''(INTERNAL) Return B{C{other}} if C{finite}. 

1072 ''' 

1073 if _isfinite(other): 

1074 return other 

1075 raise ValueError(_not_finite_) if op is None else \ 

1076 self._ValueError(op, other, txt=_not_finite_) 

1077 

1078 def fint(self, name=NN, **raiser_RESIDUAL): 

1079 '''Return this instance' current running sum as C{integer}. 

1080 

1081 @kwarg name: Optional name (C{str}), overriding C{"fint"}. 

1082 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

1083 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

1084 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

1085 

1086 @return: The C{integer} sum (L{Fsum}) if this instance C{is_integer} 

1087 with a zero or insignificant I{integer} residual. 

1088 

1089 @raise ResidualError: Non-zero, significant residual or invalid 

1090 B{C{RESIDUAL}}. 

1091 

1092 @see: Methods L{Fsum.int_float} and L{Fsum.is_integer}. 

1093 ''' 

1094 i, r = self._fint2 

1095 if r: 

1096 R = self._raiser(r, i, **raiser_RESIDUAL) 

1097 if R: 

1098 t = _stresidual(_integer_, r, **R) 

1099 raise ResidualError(_integer_, i, txt=t) 

1100 f = self._copy_2(self.fint, name=name) 

1101 return f._fset(i) 

1102 

1103 def fint2(self, **name): 

1104 '''Return this instance' current running sum as C{int} and the 

1105 I{integer} residual. 

1106 

1107 @kwarg name: Optional name (C{str}). 

1108 

1109 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} 

1110 an C{int} and I{integer} C{residual} a C{float} or 

1111 C{INT0} if the C{fsum} is considered to be I{exact}. 

1112 ''' 

1113 return Fsum2Tuple(*self._fint2, **name) 

1114 

1115 @Property_RO 

1116 def _fint2(self): # see ._fset 

1117 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual). 

1118 ''' 

1119 s, r = self._fprs2 

1120 i = int(s) 

1121 r = _fsum(self._ps_1primed(i)) if r else float(s - i) 

1122 return i, (r or INT0) # Fsum2Tuple? 

1123 

1124 @deprecated_property_RO 

1125 def float_int(self): # PYCHOK no cover 

1126 '''DEPRECATED, use method C{Fsum.int_float}.''' 

1127 return self.int_float() # raiser=False 

1128 

1129 @property_RO 

1130 def floor(self): 

1131 '''Get this instance' C{floor} (C{int} in Python 3+, but 

1132 C{float} in Python 2-). 

1133 

1134 @note: The C{floor} takes the C{residual} into account. 

1135 

1136 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil}, 

1137 L{Fsum.imag} and L{Fsum.real}. 

1138 ''' 

1139 s, r = self._fprs2 

1140 f = _floor(s) + _floor(r) + 1 

1141 while (f - s) > r: # f > (s + r) 

1142 f -= 1 

1143 return f 

1144 

1145# floordiv = __floordiv__ # for naming consistency 

1146 

1147 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv? 

1148 '''Apply C{B{self} //= B{other}}. 

1149 ''' 

1150 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self 

1151 return self._fset(q.floor) # floor(q) 

1152 

1153 fmul = __imul__ # for backward compatibility 

1154 

1155 def _fmul(self, other, op): 

1156 '''(INTERNAL) Apply C{B{self} *= B{other}}. 

1157 ''' 

1158 if _isFsumTuple(other): 

1159 if len(self._ps) != 1: 

1160 f = self._mul_Fsum(other, op) 

1161 elif len(other._ps) != 1: # and len(self._ps) == 1 

1162 f = other._mul_scalar(self._ps[0], op) 

1163 else: # len(other._ps) == len(self._ps) == 1 

1164 f = self._finite(self._ps[0] * other._ps[0]) 

1165 else: 

1166 s = self._scalar(other, op) 

1167 f = self._mul_scalar(s, op) 

1168 return self._fset(f) # n=len(self) + 1 

1169 

1170 def fover(self, over, **raiser_RESIDUAL): 

1171 '''Apply C{B{self} /= B{over}} and summate. 

1172 

1173 @arg over: An L{Fsum} or C{scalar} denominator. 

1174 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

1175 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

1176 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

1177 

1178 @return: Precision running sum (C{float}). 

1179 

1180 @raise ResidualError: Non-zero, significant residual or invalid 

1181 B{C{RESIDUAL}}. 

1182 

1183 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}. 

1184 ''' 

1185 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs) 

1186 

1187 fpow = __ipow__ # for backward compatibility 

1188 

1189 def _fpow(self, other, op, *mod, **raiser_RESIDUAL): 

1190 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}. 

1191 ''' 

1192 if mod: 

1193 if mod[0] is not None: # == 3-arg C{pow} 

1194 f = self._pow_2_3(self, other, other, op, *mod, **raiser_RESIDUAL) 

1195 elif self.is_integer(): 

1196 # return an exact C{int} for C{int}**C{int} 

1197 i, _ = self._fint2 # assert _ == 0 

1198 x, r = _2scalar2(other) # C{int}, C{float} or other 

1199 f = _Psum_(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \ 

1200 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL) 

1201 else: # mod[0] is None, power(self, other) 

1202 f = self._pow(other, other, op, **raiser_RESIDUAL) 

1203 else: # pow(self, other) 

1204 f = self._pow(other, other, op, **raiser_RESIDUAL) 

1205 return self._fset(f, asis=isint(f)) # n=max(len(self), 1) 

1206 

1207 @Property_RO 

1208 def _fprs(self): 

1209 '''(INTERNAL) Get and cache this instance' precision 

1210 running sum (C{float} or C{int}), ignoring C{residual}. 

1211 

1212 @note: The precision running C{fsum} after a C{//=} or 

1213 C{//} C{floor} division is C{int} in Python 3+. 

1214 ''' 

1215 return self._fprs2.fsum 

1216 

1217 @Property_RO 

1218 def _fprs2(self): 

1219 '''(INTERNAL) Get and cache this instance' precision 

1220 running sum and residual (L{Fsum2Tuple}). 

1221 ''' 

1222 ps = self._ps 

1223 n = len(ps) - 2 

1224 if n > 0: # len(ps) > 2 

1225 s = _psum(ps) 

1226 n = len(ps) - 2 

1227 if n > 0: 

1228 r = _fsum(self._ps_1primed(s)) 

1229 return Fsum2Tuple(*_s_r(s, r)) 

1230 if n == 0: # len(ps) == 2 

1231 s, r = _s_r(*_2sum(*ps)) 

1232 ps[:] = (r, s) if r else (s,) 

1233 elif ps: # len(ps) == 1 

1234 s, r = ps[0], INT0 

1235 else: # len(ps) == 0 

1236 s, r = _0_0, INT0 

1237 ps[:] = s, 

1238 # assert self._ps is ps 

1239 return Fsum2Tuple(s, r) 

1240 

1241 def fset_(self, *xs): 

1242 '''Replace this instance' value with C{xs}. 

1243 

1244 @arg xs: Optional, new values (each C{scalar} or 

1245 an L{Fsum} or L{Fsum2Tuple} instance), 

1246 all positional. 

1247 

1248 @return: This instance (C{Fsum}). 

1249 

1250 @see: Method L{Fsum.fadd} for further details. 

1251 ''' 

1252 f = Fsum(*xs) if xs else _0_0 

1253 return self._fset(f) 

1254 

1255 def _fset(self, other, asis=True, n=0): 

1256 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}. 

1257 ''' 

1258 if other is self: 

1259 pass # from ._fmul, ._ftruediv and ._pow_0_1 

1260 elif _isFsumTuple(other): 

1261 self._ps[:] = other._ps 

1262 self._n = n or other._n 

1263# self._copy_RESIDUAL(other) 

1264 # use or zap the C{Property_RO} values 

1265 Fsum._fint2._update_from(self, other) 

1266 Fsum._fprs ._update_from(self, other) 

1267 Fsum._fprs2._update_from(self, other) 

1268 elif isscalar(other): 

1269 s = other if asis else float(other) 

1270 i = int(s) # see ._fint2 

1271 t = i, ((s - i) or INT0) 

1272 self._ps[:] = s, 

1273 self._n = n or 1 

1274 # Property_ROs _fint2, _fprs and _fprs2 can't be a Property: 

1275 # Property's _fset zaps the value just set by the @setter 

1276 self.__dict__.update(_fint2=t, _fprs=s, _fprs2=Fsum2Tuple(s, INT0)) 

1277 else: # PYCHOK no cover 

1278 raise self._Error(_fset_op_, other, _AssertionError) 

1279 return self 

1280 

1281 def _fset_ps(self, other, n=0): # in .fmath 

1282 '''(INTERNAL) Set partials from a known C{scalar}, L{Fsum} or L{Fsum2Tuple}. 

1283 ''' 

1284 if _isFsumTuple(other): 

1285 self._ps[:] = other._ps 

1286 self._n = n or other._n 

1287 else: # assert isscalar(other) 

1288 self._ps[:] = other, 

1289 self._n = n or 1 

1290 return self 

1291 

1292 def fsub(self, xs=()): 

1293 '''Subtract all items of an iterable from this instance. 

1294 

1295 @see: Method L{Fsum.fadd} for further details. 

1296 ''' 

1297 return self._facc_neg(xs) 

1298 

1299 def fsub_(self, *xs): 

1300 '''Subtract all positional arguments from this instance. 

1301 

1302 @see: Method L{Fsum.fadd_} for further details. 

1303 ''' 

1304 return self._fsub(xs[0], _sub_op_) if len(xs) == 1 else \ 

1305 self._facc_neg(xs, origin=1) 

1306 

1307 def _fsub(self, other, op): 

1308 '''(INTERNAL) Apply C{B{self} -= B{other}}. 

1309 ''' 

1310 if _isFsumTuple(other): 

1311 if other is self: # or other._fprs2 == self._fprs2: 

1312 self._fset(_0_0, n=len(self) * 2) 

1313 elif other._ps: 

1314 self._facc_scalar(other._ps_neg) 

1315 elif self._scalar(other, op): 

1316 self._facc_scalar_(-other) 

1317 return self 

1318 

1319 def fsum(self, xs=()): 

1320 '''Add more items from an iterable, summate and return 

1321 the current precision running sum. 

1322 

1323 @arg xs: Iterable of items to add (each item C{scalar} 

1324 or an L{Fsum} or L{Fsum2Tuple} instance). 

1325 

1326 @return: Precision running sum (C{float} or C{int}). 

1327 

1328 @see: Method L{Fsum.fadd}. 

1329 

1330 @note: Accumulation can continue after summation. 

1331 ''' 

1332 return self._facc(xs)._fprs 

1333 

1334 def fsum_(self, *xs): 

1335 '''Add any positional arguments, summate and return the 

1336 current precision running sum. 

1337 

1338 @arg xs: Values to add (each C{scalar} or an L{Fsum} 

1339 or L{Fsum2Tuple} instance), all positional. 

1340 

1341 @return: Precision running sum (C{float} or C{int}). 

1342 

1343 @see: Methods L{Fsum.fsum}, L{Fsum.Fsum_} and L{Fsum.fsumf_}. 

1344 ''' 

1345 return self._facc_1(xs)._fprs 

1346 

1347 @property_RO 

1348 def _Fsum(self): 

1349 '''(INTERNAL) Like L{Fsum2Tuple._Fsum}, for C{_2floats}. 

1350 ''' 

1351 return self 

1352 

1353 def Fsum_(self, *xs, **name): 

1354 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}. 

1355 

1356 @kwarg name: Optional name (C{str}). 

1357 

1358 @return: Current, precision running sum (L{Fsum}). 

1359 ''' 

1360 return self._facc_1(xs)._copy_2(self.Fsum_, **name) 

1361 

1362 def Fsum2Tuple_(self, *xs, **name): 

1363 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}. 

1364 

1365 @kwarg name: Optional name (C{str}). 

1366 

1367 @return: Current, precision running sum (L{Fsum2Tuple}). 

1368 ''' 

1369 return Fsum2Tuple(self._facc_1(xs)._fprs2, **name) 

1370 

1371 def fsum2(self, xs=(), name=NN): 

1372 '''Add more items from an iterable, summate and return the 

1373 current precision running sum I{and} the C{residual}. 

1374 

1375 @arg xs: Iterable of items to add (each item C{scalar} 

1376 or an L{Fsum} or L{Fsum2Tuple} instance). 

1377 @kwarg name: Optional name (C{str}). 

1378 

1379 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the 

1380 current precision running sum and C{residual}, the 

1381 (precision) sum of the remaining C{partials}. The 

1382 C{residual is INT0} if the C{fsum} is considered 

1383 to be I{exact}. 

1384 

1385 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_} 

1386 ''' 

1387 t = self._facc(xs)._fprs2 

1388 return t.dup(name=name) if name else t 

1389 

1390 def fsum2_(self, *xs): 

1391 '''Add any positional arguments, summate and return the current 

1392 precision running sum I{and} the C{differential}. 

1393 

1394 @arg xs: Values to add (each C{scalar} or an L{Fsum} or 

1395 L{Fsum2Tuple} instance), all positional. 

1396 

1397 @return: 2Tuple C{(fsum, delta)} with the current, precision 

1398 running C{fsum} like method L{Fsum.fsum} and C{delta}, 

1399 the difference with previous running C{fsum}, C{float}. 

1400 

1401 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}. 

1402 ''' 

1403 return self._fsum2(xs, self._facc_1) 

1404 

1405 def _fsum2(self, xs, _f, **origin): 

1406 '''(INTERNAL) Helper for L{Fsum.fsum2_} and L{Fsum.fsum2f_}. 

1407 ''' 

1408 p, q = self._fprs2 

1409 if xs: 

1410 s, r = _f(xs, **origin)._fprs2 

1411 return s, _2delta(s - p, r - q) # _fsum(_1primed((s, -p, r, -q)) 

1412 else: 

1413 return p, _0_0 

1414 

1415 def fsumf_(self, *xs): 

1416 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}} are I{known to be scalar}. 

1417 ''' 

1418 return self._facc_scalar(xs)._fprs 

1419 

1420 def Fsumf_(self, *xs): 

1421 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}} are I{known to be scalar}. 

1422 ''' 

1423 return self._facc_scalar(xs)._copy_2(self.Fsumf_) 

1424 

1425 def fsum2f_(self, *xs): 

1426 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}} are I{known to be scalar}. 

1427 ''' 

1428 return self._fsum2(xs, self._facc_scalar, origin=1) 

1429 

1430# ftruediv = __itruediv__ # for naming consistency? 

1431 

1432 def _ftruediv(self, other, op, **raiser_RESIDUAL): 

1433 '''(INTERNAL) Apply C{B{self} /= B{other}}. 

1434 ''' 

1435 n = _1_0 

1436 if _isFsumTuple(other): 

1437 if other is self or self == other: 

1438 return self._fset(n) # n=len(self) 

1439 d, r = other._fprs2 

1440 if r: 

1441 R = self._raiser(r, d, **raiser_RESIDUAL) 

1442 if R: 

1443 raise self._ResidualError(op, other, r, **R) 

1444 d, n = other.as_integer_ratio() 

1445 else: 

1446 d = self._scalar(other, op) 

1447 try: 

1448 s = n / d 

1449 except Exception as X: 

1450 raise self._ErrorX(X, op, other) 

1451 f = self._mul_scalar(s, _mul_op_) # handles 0, INF, NAN 

1452 return self._fset(f) # asis=False 

1453 

1454 @property_RO 

1455 def imag(self): 

1456 '''Get the C{imaginary} part of this instance (C{0.0}, always). 

1457 

1458 @see: Properties L{Fsum.ceil}, L{Fsum.floor} and L{Fsum.real}. 

1459 ''' 

1460 return _0_0 

1461 

1462 def int_float(self, **raiser_RESIDUAL): 

1463 '''Return this instance' current running sum as C{int} or C{float}. 

1464 

1465 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

1466 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

1467 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

1468 

1469 @return: This C{integer} sum if this instance C{is_integer}, 

1470 otherwise return the C{float} sum if the residual is 

1471 zero or not significant. 

1472 

1473 @raise ResidualError: Non-zero, significant residual or invalid 

1474 B{C{RESIDUAL}}. 

1475 

1476 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.RESIDUAL} and 

1477 property L{Fsum.as_iscalar}. 

1478 ''' 

1479 s, r = self._fint2 

1480 if r: 

1481 s, r = self._fprs2 

1482 if r: # PYCHOK no cover 

1483 R = self._raiser(r, s, **raiser_RESIDUAL) 

1484 if R: 

1485 t = _stresidual(_non_zero_, r, **R) 

1486 raise ResidualError(int_float=s, txt=t) 

1487 s = float(s) # redundant 

1488 return s 

1489 

1490 def is_exact(self): 

1491 '''Is this instance' running C{fsum} considered to be exact? (C{bool}). 

1492 ''' 

1493 return self.residual is INT0 

1494 

1495 def is_integer(self): 

1496 '''Is this instance' running sum C{integer}? (C{bool}). 

1497 

1498 @see: Methods L{Fsum.fint}, L{Fsum.fint2} and L{Fsum.is_scalar}. 

1499 ''' 

1500 _, r = self._fint2 

1501 return False if r else True 

1502 

1503 def is_math_fsum(self): 

1504 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and 

1505 L{fsum1_} plus partials summation are based on Python's 

1506 C{math.fsum} or not. 

1507 

1508 @return: C{2} if all functions and partials summation 

1509 are based on C{math.fsum}, C{True} if only 

1510 the functions are based on C{math.fsum} (and 

1511 partials summation is not) or C{False} if 

1512 none are. 

1513 ''' 

1514 f = Fsum._math_fsum 

1515 return 2 if _psum is f else bool(f) 

1516 

1517 def is_scalar(self, **raiser_RESIDUAL): 

1518 '''Is this instance' running sum C{scalar} with an insignificant 

1519 residual and the residual I{ratio} not exceeding the RESIDUAL 

1520 threshold? (C{bool}). 

1521 

1522 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

1523 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

1524 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

1525 

1526 @raise ResidualError: Non-zero, significant residual or invalid 

1527 B{C{RESIDUAL}}. 

1528 

1529 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property 

1530 L{Fsum.as_iscalar}. 

1531 ''' 

1532 s, r = self._fprs2 

1533 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True 

1534 

1535 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner 

1536 '''(INTERNAL) Return C{B{self} * B{other}} as L{Fsum} or C{0}. 

1537 ''' 

1538 # assert _isFsumTuple(other) 

1539 if self._ps and other._ps: 

1540 f = self._ps_mul(op, *other._ps) # NO .as_iscalar 

1541 else: 

1542 f = _0_0 

1543 return f 

1544 

1545 def _mul_scalar(self, factor, op): # in .fmath.Fhorner 

1546 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0} or C{self}. 

1547 ''' 

1548 # assert isscalar(factor) 

1549 if self._ps and self._finite(factor, op): 

1550 f = self if factor == _1_0 else ( 

1551 self._neg if factor == _N_1_0 else 

1552 self._ps_mul(op, factor).as_iscalar) 

1553 else: 

1554 f = _0_0 

1555 return f 

1556 

1557 @property_RO 

1558 def _neg(self): 

1559 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}. 

1560 ''' 

1561 return _Psum(self._ps_neg) if self._ps else NEG0 

1562 

1563 @property_RO 

1564 def partials(self): 

1565 '''Get this instance' current, partial sums (C{tuple} of C{float}s). 

1566 ''' 

1567 return tuple(self._ps) 

1568 

1569 def pow(self, x, *mod, **raiser_RESIDUAL): 

1570 '''Return C{B{self}**B{x}} as L{Fsum}. 

1571 

1572 @arg x: The exponent (C{scalar} or L{Fsum}). 

1573 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument 

1574 C{pow(B{self}, B{other}, B{mod})} version. 

1575 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

1576 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

1577 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

1578 

1579 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})} 

1580 result (L{Fsum}). 

1581 

1582 @raise ResidualError: Non-zero, significant residual or invalid 

1583 B{C{RESIDUAL}}. 

1584 

1585 @note: If B{C{mod}} is given as C{None}, the result will be an 

1586 C{integer} L{Fsum} provided this instance C{is_integer} 

1587 or set to C{integer} by an L{Fsum.fint} call. 

1588 

1589 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer} 

1590 and L{Fsum.root}. 

1591 ''' 

1592 f = self._copy_2(self.pow) 

1593 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod) 

1594 

1595 def _pow(self, other, unused, op, **raiser_RESIDUAL): 

1596 '''Return C{B{self} ** B{other}}. 

1597 ''' 

1598 if _isFsumTuple(other): 

1599 f = self._pow_Fsum(other, op, **raiser_RESIDUAL) 

1600 elif self._scalar(other, op): 

1601 x = self._finite(other, op) 

1602 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

1603 else: 

1604 f = self._pow_0_1(0, other) 

1605 return f 

1606 

1607 def _pow_0_1(self, x, other): 

1608 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}. 

1609 ''' 

1610 return self if x else (1 if isint(other) and self.is_integer() else _1_0) 

1611 

1612 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL): 

1613 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b}, 

1614 B{x}, int B{mod} or C{None})}, embellishing errors. 

1615 ''' 

1616 

1617 if mod: # b, x, mod all C{int}, unless C{mod} is C{None} 

1618 m = mod[0] 

1619 # assert _isFsumTuple(b) 

1620 

1621 def _s(s, r): 

1622 R = self._raiser(r, s, **raiser_RESIDUAL) 

1623 if R: 

1624 raise self._ResidualError(op, other, r, mod=m, **R) 

1625 return s 

1626 

1627 b = _s(*(b._fprs2 if m is None else b._fint2)) 

1628 x = _s(*_2scalar2(x)) 

1629 

1630 try: 

1631 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3) 

1632 s = pow(b, x, *mod) 

1633 if iscomplex(s): 

1634 # neg**frac == complex in Python 3+, but ValueError in 2- 

1635 raise ValueError(_strcomplex(s, b, x, *mod)) 

1636 return self._finite(s) 

1637 except Exception as X: 

1638 raise self._ErrorX(X, op, other, *mod) 

1639 

1640 def _pow_Fsum(self, other, op, **raiser_RESIDUAL): 

1641 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsumTuple(other)}. 

1642 ''' 

1643 # assert _isFsumTuple(other) 

1644 x, r = other._fprs2 

1645 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

1646 if f and r: 

1647 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL) 

1648 return f 

1649 

1650 def _pow_int(self, x, other, op, **raiser_RESIDUAL): 

1651 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}. 

1652 ''' 

1653 # assert isint(x) and x >= 0 

1654 ps = self._ps 

1655 if len(ps) > 1: 

1656 _mul_Fsum = Fsum._mul_Fsum 

1657 if x > 4: 

1658 p = self 

1659 f = self if (x & 1) else _Psum_(_1_0) 

1660 m = x >> 1 # // 2 

1661 while m: 

1662 p = _mul_Fsum(p, p, op) # p **= 2 

1663 if (m & 1): 

1664 f = _mul_Fsum(f, p, op) # f *= p 

1665 m >>= 1 # //= 2 

1666 elif x > 1: # self**2, 3 or 4 

1667 f = _mul_Fsum(self, self, op) 

1668 if x > 2: # self**3 or 4 

1669 p = self if x < 4 else f 

1670 f = _mul_Fsum(f, p, op).as_iscalar 

1671 else: # self**1 or self**0 == 1 or _1_0 

1672 f = self._pow_0_1(x, other) 

1673 elif ps: # self._ps[0]**x 

1674 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL) 

1675 else: # PYCHOK no cover 

1676 # 0**pos_int == 0, but 0**0 == 1 

1677 f = 0 if x else 1 

1678 return f 

1679 

1680 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL): 

1681 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}. 

1682 ''' 

1683 s, r = self._fprs2 

1684 if r: 

1685 # assert s != 0 

1686 if isint(x, both=True): # self**int 

1687 x = int(x) 

1688 y = abs(x) 

1689 if y > 1: 

1690 f = self._pow_int(y, other, op, **raiser_RESIDUAL) 

1691 if x > 0: # i.e. > 1 

1692 return f # Fsum or scalar 

1693 # assert x < 0 # i.e. < -1 

1694 if _isFsum(f): 

1695 s, r = f._fprs2 

1696 if r: 

1697 return _1_Over(f, op, **raiser_RESIDUAL) 

1698 else: # scalar 

1699 s = f 

1700 # use s**(-1) to get the CPython 

1701 # float_pow error iff s is zero 

1702 x = -1 

1703 elif x < 0: # self**(-1) 

1704 return _1_Over(self, op, **raiser_RESIDUAL) # 1 / self 

1705 else: # self**1 or self**0 

1706 return self._pow_0_1(x, other) # self, 1 or 1.0 

1707 else: # self**fractional 

1708 R = self._raiser(r, s, **raiser_RESIDUAL) 

1709 if R: 

1710 raise self._ResidualError(op, other, r, **R) 

1711 n, d = self.as_integer_ratio() 

1712 if abs(n) > abs(d): 

1713 n, d, x = d, n, (-x) 

1714 s = n / d 

1715 # assert isscalar(s) and isscalar(x) 

1716 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL) 

1717 

1718 def _ps_acc(self, ps, xs, up=True, **unused): 

1719 '''(INTERNAL) Accumulate all C{xs} scalars into list C{ps}. 

1720 ''' 

1721 n = 0 

1722 _2s = _2sum 

1723 for x in (tuple(xs) if xs is ps else xs): 

1724 # assert isscalar(x) and _isfinite(x) 

1725 if x: 

1726 i = 0 

1727 for p in ps: 

1728 x, p = _2s(x, p) 

1729 if p: 

1730 ps[i] = p 

1731 i += 1 

1732 ps[i:] = (x,) if x else () 

1733 n += 1 

1734 if n: 

1735 self._n += n 

1736 # Fsum._ps_max = max(Fsum._ps_max, len(ps)) 

1737 if up: 

1738 self._update() 

1739 return ps 

1740 

1741 def _ps_mul(self, op, *factors): 

1742 '''(INTERNAL) Multiply this instance' C{partials} with each 

1743 of the scalar B{C{factors}} and accumulate. 

1744 ''' 

1745 def _pfs(ps, fs): 

1746 if len(ps) < len(fs): 

1747 ps, fs = fs, ps 

1748 _fin = _isfinite 

1749 for f in fs: 

1750 for p in ps: 

1751 p *= f 

1752 yield p if _fin(p) else self._finite(p, op) 

1753 

1754 return _Psum(self._ps_acc([], _pfs(self._ps, factors), up=False)) 

1755 

1756 @property_RO 

1757 def _ps_neg(self): 

1758 '''(INTERNAL) Yield the partials, I{negated}. 

1759 ''' 

1760 for p in self._ps: 

1761 yield -p 

1762 

1763 def _ps_1primed(self, *less): 

1764 '''(INTERNAL) Yield partials, 1-primed C{less} any scalars. 

1765 ''' 

1766 yield _1_0 

1767 for p in self._ps: 

1768 yield p 

1769 for p in less: 

1770 yield -p 

1771 yield _N_1_0 

1772 

1773 def _raiser(self, r, s, raiser=True, **RESIDUAL): 

1774 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold 

1775 I{and} is residual C{r} I{non-zero} or I{significant} (for a 

1776 negative respectively positive C{RESIDUAL} threshold)? 

1777 ''' 

1778 if r and raiser: 

1779 t = self._RESIDUAL 

1780 if RESIDUAL: 

1781 t = _threshold(_xkwds_get(RESIDUAL, RESIDUAL=t)) 

1782 if t < 0 or (s + r) != s: 

1783 q = (r / s) if s else s # == 0. 

1784 if fabs(q) > fabs(t): 

1785 return dict(ratio=q, R=t) 

1786 return {} 

1787 

1788 @property_RO 

1789 def real(self): 

1790 '''Get the C{real} part of this instance (C{float}). 

1791 

1792 @see: Methods L{Fsum.__float__} and L{Fsum.fsum} 

1793 and properties L{Fsum.ceil}, L{Fsum.floor}, 

1794 L{Fsum.imag} and L{Fsum.residual}. 

1795 ''' 

1796 return float(self._fprs) 

1797 

1798 @property_RO 

1799 def residual(self): 

1800 '''Get this instance' residual (C{float} or C{int}): the 

1801 C{sum(partials)} less the precision running sum C{fsum}. 

1802 

1803 @note: The C{residual is INT0} iff the precision running 

1804 C{fsum} is considered to be I{exact}. 

1805 

1806 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}. 

1807 ''' 

1808 return self._fprs2.residual 

1809 

1810 def RESIDUAL(self, *threshold): 

1811 '''Get and set this instance' I{ratio} for raising L{ResidualError}s, 

1812 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}. 

1813 

1814 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising 

1815 L{ResidualError}s in division and exponention, if 

1816 C{None} restore the default set with env variable 

1817 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

1818 current setting. 

1819 

1820 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}. 

1821 

1822 @raise ResidualError: Invalid B{C{threshold}}. 

1823 

1824 @note: L{ResidualError}s may be thrown if the non-zero I{ratio} 

1825 C{residual / fsum} exceeds the given B{C{threshold}} and 

1826 if the C{residual} is non-zero and I{significant} vs the 

1827 C{fsum}, i.e. C{(fsum + residual) != fsum} and if optional 

1828 keyword argument C{raiser=False} is missing. Specify a 

1829 negative B{C{threshold}} for only non-zero C{residual} 

1830 testing without I{significant}. 

1831 ''' 

1832 r = self._RESIDUAL 

1833 if threshold: 

1834 t = threshold[0] 

1835 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ... 

1836 (_0_0 if t else _1_0) if isbool(t) else 

1837 _threshold(t)) # ... backward compatibility 

1838 return r 

1839 

1840 def _ResidualError(self, op, other, residual, **mod_R): 

1841 '''(INTERNAL) Non-zero B{C{residual}} etc. 

1842 ''' 

1843 def _p(mod=None, R=0, **unused): # ratio=0 

1844 return (_non_zero_ if R < 0 else _significant_) \ 

1845 if mod is None else _integer_ 

1846 

1847 t = _stresidual(_p(**mod_R), residual, **mod_R) 

1848 return self._Error(op, other, ResidualError, txt=t) 

1849 

1850 def root(self, root, **raiser_RESIDUAL): 

1851 '''Return C{B{self}**(1 / B{root})} as L{Fsum}. 

1852 

1853 @arg root: The order (C{scalar} or L{Fsum}), non-zero. 

1854 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to 

1855 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar} 

1856 to override the L{RESIDUAL<Fsum.RESIDUAL>}. 

1857 

1858 @return: The C{self ** (1 / B{root})} result (L{Fsum}). 

1859 

1860 @raise ResidualError: Non-zero, significant residual or invalid 

1861 B{C{RESIDUAL}}. 

1862 

1863 @see: Method L{Fsum.pow}. 

1864 ''' 

1865 x = _1_Over(root, _truediv_op_, **raiser_RESIDUAL) 

1866 f = self._copy_2(self.root) 

1867 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x) 

1868 

1869 def _scalar(self, other, op, **txt): 

1870 '''(INTERNAL) Return scalar C{other}. 

1871 ''' 

1872 if isscalar(other): 

1873 return other 

1874 raise self._TypeError(op, other, **txt) # _invalid_ 

1875 

1876 def signOf(self, res=True): 

1877 '''Determine the sign of this instance. 

1878 

1879 @kwarg res: If C{True} consider, otherwise 

1880 ignore the residual (C{bool}). 

1881 

1882 @return: The sign (C{int}, -1, 0 or +1). 

1883 ''' 

1884 s, r = self._fprs2 

1885 r = (-r) if res else 0 

1886 return _signOf(s, r) 

1887 

1888 def toRepr(self, **prec_sep_fmt_lenc): # PYCHOK signature 

1889 '''Return this C{Fsum} instance as representation. 

1890 

1891 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

1892 method L{Fsum2Tuple.toRepr} plus C{B{lenc}=True} 

1893 (C{bool}) to in-/exclude the current C{[len]} 

1894 of this L{Fsum} enclosed in I{[brackets]}. 

1895 

1896 @return: This instance (C{repr}). 

1897 ''' 

1898 return self._toT(self._fprs2.toRepr, **prec_sep_fmt_lenc) 

1899 

1900 def toStr(self, **prec_sep_fmt_lenc): # PYCHOK signature 

1901 '''Return this C{Fsum} instance as string. 

1902 

1903 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

1904 method L{Fsum2Tuple.toStr} plus C{B{lenc}=True} 

1905 (C{bool}) to in-/exclude the current C{[len]} 

1906 of this L{Fsum} enclosed in I{[brackets]}. 

1907 

1908 @return: This instance (C{str}). 

1909 ''' 

1910 return self._toT(self._fprs2.toStr, **prec_sep_fmt_lenc) 

1911 

1912 def _toT(self, toT, fmt=Fmt.g, lenc=True, **kwds): 

1913 '''(INTERNAL) Helper for C{toRepr} and C{toStr}. 

1914 ''' 

1915 p = self.classname 

1916 if lenc: 

1917 p = Fmt.SQUARE(p, len(self)) 

1918 n = self.name 

1919 if n: 

1920 n = _UNDER_(*n.split()) 

1921 return NN(p, _SPACE_, n, toT(fmt=fmt, **kwds)) 

1922 

1923 def _TypeError(self, op, other, **txt): # PYCHOK no cover 

1924 '''(INTERNAL) Return a C{TypeError}. 

1925 ''' 

1926 return self._Error(op, other, _TypeError, **txt) 

1927 

1928 def _update(self, updated=True): # see ._fset 

1929 '''(INTERNAL) Zap all cached C{Property_RO} values. 

1930 ''' 

1931 if updated: 

1932 _pop = self.__dict__.pop 

1933 for p in _ROs: 

1934 _ = _pop(p, None) 

1935# Fsum._fint2._update(self) 

1936# Fsum._fprs ._update(self) 

1937# Fsum._fprs2._update(self) 

1938 return self # for .fset_ 

1939 

1940 def _ValueError(self, op, other, **txt): # PYCHOK no cover 

1941 '''(INTERNAL) Return a C{ValueError}. 

1942 ''' 

1943 return self._Error(op, other, _ValueError, **txt) 

1944 

1945 def _ZeroDivisionError(self, op, other, **txt): # PYCHOK no cover 

1946 '''(INTERNAL) Return a C{ZeroDivisionError}. 

1947 ''' 

1948 return self._Error(op, other, _ZeroDivisionError, **txt) 

1949 

1950_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update 

1951 

1952 

1953def _Float_Int(arg, **name_Error): 

1954 '''(INTERNAL) Unit of L{Fsum2Tuple} items. 

1955 ''' 

1956 U = Int if isint(arg) else Float 

1957 return U(arg, **name_Error) 

1958 

1959 

1960class DivMod2Tuple(_NamedTuple): 

1961 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder 

1962 C{mod} results of a C{divmod} operation. 

1963 

1964 @note: Quotient C{div} an C{int} in Python 3+ but a C{float} 

1965 in Python 2-. Remainder C{mod} an L{Fsum} instance. 

1966 ''' 

1967 _Names_ = (_div_, _mod_) 

1968 _Units_ = (_Float_Int, Fsum) 

1969 

1970 

1971class Fsum2Tuple(_NamedTuple): 

1972 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum} 

1973 and the C{residual}, the sum of the remaining partials. Each 

1974 item is C{float} or C{int}. 

1975 

1976 @note: If the C{residual is INT0}, the C{fsum} is considered 

1977 to be I{exact}, see method L{Fsum2Tuple.is_exact}. 

1978 ''' 

1979 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name) 

1980 _Units_ = (_Float_Int, _Float_Int) 

1981 

1982 def as_integer_ratio(self): 

1983 '''Return this instance as the ratio of 2 integers. 

1984 

1985 @see: Method L{Fsum.as_integer_ratio} for further details. 

1986 ''' 

1987 return self._Fsum.as_integer_ratio() 

1988 

1989 @property_RO 

1990 def _fint2(self): 

1991 return self._Fsum.fint2 

1992 

1993 @property_RO 

1994 def _fprs2(self): 

1995 return self._Fsum._fprs2 

1996 

1997 @Property_RO 

1998 def _Fsum(self): 

1999 return Fsum(*self) 

2000 

2001 def is_exact(self): 

2002 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}). 

2003 ''' 

2004 _, r = _s_r(*self) 

2005 return False if r else True 

2006 

2007 def is_integer(self): 

2008 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}). 

2009 ''' 

2010 s, r = _s_r(*self) 

2011 return False if r else isint(s, both=True) 

2012 

2013 @property_RO 

2014 def _n(self): 

2015 return self._Fsum._n 

2016 

2017 @property_RO 

2018 def _ps(self): 

2019 return self._Fsum._ps 

2020 

2021 @property_RO 

2022 def _ps_neg(self): 

2023 return self._Fsum._ps_neg 

2024 

2025 def signOf(self, **res): 

2026 '''Like L{Fsum.signOf}. 

2027 ''' 

2028 return self._Fsum.signOf(**res) 

2029 

2030_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK line 

2031 

2032 

2033class ResidualError(_ValueError): 

2034 '''Error raised for a division, power or root operation of 

2035 an L{Fsum} instance with a C{residual} I{ratio} exceeding 

2036 the L{RESIDUAL<Fsum.RESIDUAL>} threshold. 

2037 

2038 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}. 

2039 ''' 

2040 pass 

2041 

2042 

2043try: 

2044 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+ 

2045 

2046 # make sure _fsum works as expected (XXX check 

2047 # float.__getformat__('float')[:4] == 'IEEE'?) 

2048 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover 

2049 del _fsum # nope, remove _fsum ... 

2050 raise ImportError # ... use _fsum below 

2051 

2052 Fsum._math_fsum = _sum = _fsum # PYCHOK exported 

2053except ImportError: 

2054 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic 

2055 

2056 def _fsum(xs): 

2057 '''(INTERNAL) Precision summation, Python 2.5-. 

2058 ''' 

2059 F = Fsum() 

2060 F.name = _fsum.__name__ 

2061 return F._facc(xs, up=False)._fprs2.fsum 

2062 

2063 

2064def fsum(xs, floats=False): 

2065 '''Precision floating point summation based on/like Python's C{math.fsum}. 

2066 

2067 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or 

2068 L{Fsum2Tuple} instance). 

2069 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are 

2070 I{known to be scalar} (C{bool}). 

2071 

2072 @return: Precision C{fsum} (C{float}). 

2073 

2074 @raise OverflowError: Partial C{2sum} overflow. 

2075 

2076 @raise TypeError: Non-scalar B{C{xs}} item. 

2077 

2078 @raise ValueError: Invalid or non-finite B{C{xs}} item. 

2079 

2080 @note: Exception and I{non-finite} handling may differ if not based 

2081 on Python's C{math.fsum}. 

2082 

2083 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}. 

2084 ''' 

2085 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield 

2086 

2087 

2088def fsum_(*xs, **floats): 

2089 '''Precision floating point summation of all positional arguments. 

2090 

2091 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} 

2092 instance), all positional. 

2093 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are 

2094 I{known to be scalar} (C{bool}). 

2095 

2096 @see: Function L{fsum<fsums.fsum>} for further details. 

2097 ''' 

2098 return _fsum(xs if _xkwds_get(floats, floats=False) is True else 

2099 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield 

2100 

2101 

2102def fsumf_(*xs): 

2103 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}. 

2104 

2105 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2106 ''' 

2107 return _fsum(xs) if xs else _0_0 

2108 

2109 

2110def fsum1(xs, floats=False): 

2111 '''Precision floating point summation, 1-primed. 

2112 

2113 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or 

2114 L{Fsum2Tuple} instance). 

2115 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are 

2116 I{known to be scalar} (C{bool}). 

2117 

2118 @see: Function L{fsum<fsums.fsum>} for further details. 

2119 ''' 

2120 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield 

2121 

2122 

2123def fsum1_(*xs, **floats): 

2124 '''Precision floating point summation, 1-primed of all positional arguments. 

2125 

2126 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} 

2127 instance), all positional. 

2128 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are 

2129 I{known to be scalar} (C{bool}). 

2130 

2131 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2132 ''' 

2133 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) is True else 

2134 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield 

2135 

2136 

2137def fsum1f_(*xs): 

2138 '''Precision floating point summation iff I{all} C{B{xs}} are I{known to be scalar}. 

2139 

2140 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2141 ''' 

2142 return _fsum(_1primed(xs)) if xs else _0_0 

2143 

2144 

2145if __name__ == '__main__': 

2146 

2147 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums 

2148 

2149 if _getenv(_psum.__name__, NN) == _fsum.__name__: 

2150 _psum = _fsum 

2151 

2152 def _test(n): 

2153 # copied from Hettinger, see L{Fsum} reference 

2154 from pygeodesy import frandoms, printf 

2155 

2156 printf(_fsum.__name__, end=_COMMASPACE_) 

2157 printf(_psum.__name__, end=_COMMASPACE_) 

2158 

2159 F = Fsum() 

2160 if F.is_math_fsum(): 

2161 for t in frandoms(n, seeded=True): 

2162 assert float(F.fset_(*t)) == _fsum(t) 

2163 printf(_DOT_, end=NN) 

2164 printf(NN) 

2165 

2166 _test(128) 

2167 

2168# **) MIT License 

2169# 

2170# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved. 

2171# 

2172# Permission is hereby granted, free of charge, to any person obtaining a 

2173# copy of this software and associated documentation files (the "Software"), 

2174# to deal in the Software without restriction, including without limitation 

2175# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

2176# and/or sell copies of the Software, and to permit persons to whom the 

2177# Software is furnished to do so, subject to the following conditions: 

2178# 

2179# The above copyright notice and this permission notice shall be included 

2180# in all copies or substantial portions of the Software. 

2181# 

2182# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

2183# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

2184# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

2185# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

2186# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

2187# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

2188# OTHER DEALINGS IN THE SOFTWARE.