Coverage for pygeodesy/fsums.py: 96%

783 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-04-24 16:06 -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_PARTIALS} to string C{"fsum"}) for summation 

18of L{Fsum} partials by Python function C{math.fsum}. 

19 

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

21C{"0.0"} as the threshold to throw a L{ResidualError} in division or exponention 

22of an L{Fsum} instance with a I{relative} C{residual} exceeding the threshold, 

23see methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__} and L{Fsum.__itruediv__}. 

24''' 

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

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

27 

28from pygeodesy.basics import iscomplex, isint, isscalar, itemsorted, \ 

29 signOf, _signOf 

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

31 _0_0, _1_0, _N_1_0, Float, Int 

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

33 _ValueError, _xError, _xError2, _xkwds_get, \ 

34 _ZeroDivisionError 

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

36 _exceeds_, _from_, _iadd_op_, _LANGLE_, _negative_, \ 

37 _NOTEQUAL_, _not_finite_, _PERCENT_, _PLUS_, _R_, \ 

38 _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_ 

39from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2 

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

41from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \ 

42 Property_RO, property_RO 

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

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

45 

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

47 

48__all__ = _ALL_LAZY.fsums 

49__version__ = '24.04.24' 

50 

51_add_op_ = _PLUS_ # in .auxilats.auxAngle 

52_eq_op_ = _EQUAL_ * 2 # _DEQUAL_ 

53_COMMASPACE_R_ = _COMMASPACE_ + _R_ 

54_div_ = 'div' 

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_ = 'mod' 

64_mod_op_ = _PERCENT_ 

65_mul_op_ = _STAR_ 

66_ne_op_ = _NOTEQUAL_ 

67_non_zero_ = 'non-zero' 

68_pow_op_ = _STAR_ * 2 # _DSTAR_, in .fmath 

69_sub_op_ = _DASH_ # in .auxilats.auxAngle, .fsums 

70_truediv_op_ = _SLASH_ 

71_divmod_op_ = _floordiv_op_ + _mod_op_ 

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

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 _Fs = Fsum 

113 for x in xs: 

114 if isinstance(x, _Fs): 

115 for p in _X(x): 

116 yield p 

117 else: 

118 f = _x(x) 

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

120 i += 1 

121 except Exception as X: 

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

123 

124 

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

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

127 ''' 

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

129 

130 

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

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

133 ''' 

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

135 

136 

137def _2halfeven(s, r, p): 

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

139 ''' 

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

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

142 r *= 2 

143 t = s + r 

144 if r == (t - s): 

145 s = t 

146 return s 

147 

148 

149def _1_over(x, op=_truediv_op_, **raiser): 

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

151 ''' 

152 return _Psum_(_1_0)._ftruediv(x, op, **raiser) 

153 

154 

155def _1primed(xs): # in .fmath 

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

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

158 ''' 

159 yield _1_0 

160 for x in xs: 

161 yield x 

162 yield _N_1_0 

163 

164 

165def _2ps(s, r): 

166 '''(INTERNAL) Return an C{s} and C{r} pair, I{ps-ordered}. 

167 ''' 

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

169 s, r = r, s 

170 return (r, s) if r else (s,) # PYCHOK types 

171 

172 

173def _psum(ps): # PYCHOK used! 

174 '''(INTERNAL) Partials sum, updating C{ps}, I{overridden below}. 

175 ''' 

176 # assert isinstance(ps, list) 

177 i = len(ps) - 1 

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

179 _2s = _2sum 

180 while i > 0: 

181 i -= 1 

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

183 if r: # sum(ps) became inexact 

184 if s: 

185 ps[i:] = r, s 

186 if i > 0: 

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

188 break # return s 

189 s = r # PYCHOK no cover 

190 ps[i:] = s, 

191 return s 

192 

193 

194def _Psum(ps, **name): 

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

196 ''' 

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

198 if ps: 

199 F._ps[:] = ps 

200 F._n = len(F._ps) 

201 return F 

202 

203 

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

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

206 ''' 

207 return _Psum(ps, **name) 

208 

209 

210def _2scalar(other, _raiser=None, **mod): 

211 '''(INTERNAL) Return B{C{other}} as C{int}, C{float} or C{as-is}. 

212 ''' 

213 if isinstance(other, Fsum): 

214 s, r = other._fint2 

215 if r: 

216 s, r = other._fprs2 

217 if r: # PYCHOK no cover 

218 if _raiser and _raiser(r, s): 

219 t = _stresidual(_non_zero_, r, **mod) 

220 raise ResidualError(t, txt=None) 

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

222 else: 

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

224 if isint(s, both=True): 

225 s = int(s) 

226 return s 

227 

228 

229def _strcomplex(s, *args): 

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

231 ''' 

232 c = _strcomplex.__name__[4:] 

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

234 t = unstr(pow, *args) 

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

236 

237 

238def _stresidual(prefix, residual, **name_values): 

239 '''(INTERNAL) Residual error as C{str}. 

240 ''' 

241 p = _stresidual.__name__[3:] 

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

243 for n, v in itemsorted(name_values): 

244 n = n.replace(_UNDER_, _SPACE_) 

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

246 t = _COMMASPACE_(t, p) 

247 return _SPACE_(prefix, t) 

248 

249 

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

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

252 ''' 

253 s = a + b 

254 if _isfinite(s): 

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

256 b, a = a, b 

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

258 u = unstr(_2sum, a, b) 

259 t = Fmt.PARENSPACED(_not_finite_, s) 

260 raise _OverflowError(u, txt=t) 

261 

262 

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

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

265 

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

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

268 intermediate, I{running} summuation. 

269 

270 @note: Accumulated values may be L{Fsum} or C{scalar} instances, any C{type} having 

271 method C{__float__} to convert the C{scalar} to a single C{float}. 

272 

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

274 Python's C{math.fsum}. 

275 

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

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

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

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

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

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

282 ''' 

283 _math_fsum = None 

284 _n = 0 

285# _ps = [] # partial sums 

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

287 _ratio = None # see method _raiser 

288 _recursive = bool(_getenv('PYGEODESY_FSUM_RECURSIVE', NN)) 

289 _RESIDUAL = max(float(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)), _0_0) 

290 

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

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

293 

294 @arg xs: No, one or more initial values, all positional (each C{scalar} 

295 or an L{Fsum} instance). 

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

297 C{B{RESIDUAL}=None} for the L{ResidualError} threshold. 

298 

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

300 ''' 

301 if name_RESIDUAL: 

302 n = _xkwds_get(name_RESIDUAL, name=NN) 

303 if n: # set name before ... 

304 self.name = n 

305 r = _xkwds_get(name_RESIDUAL, RESIDUAL=None) 

306 if r is not None: 

307 self.RESIDUAL(r) # ... ResidualError 

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

309 if xs: 

310 self._facc(xs, origin=1, up=False) 

311 

312 def __abs__(self): 

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

314 ''' 

315 s = _fsum(self._ps_1primed()) # == self._cmp_0(0, ...) 

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

317 

318 def __add__(self, other): 

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

320 

321 @arg other: An L{Fsum} or C{scalar}. 

322 

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

324 

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

326 ''' 

327 f = self._copy_2(self.__add__) 

328 return f._fadd(other, _add_op_) 

329 

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

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

332 ''' 

333 s, r = self._fprs2 

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

335 

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

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

338 

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

340 

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

342 ''' 

343 return self.ceil 

344 

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

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

347 

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

349 

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

351 ''' 

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

353 return _signOf(s, 0) 

354 

355 cmp = __cmp__ 

356 

357 def __divmod__(self, other): 

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

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

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

361 

362 @arg other: An L{Fsum} or C{scalar} modulus. 

363 

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

365 ''' 

366 f = self._copy_2(self.__divmod__) 

367 return f._fdivmod2(other, _divmod_op_) 

368 

369 def __eq__(self, other): 

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

371 ''' 

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

373 

374 def __float__(self): 

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

376 

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

378 ''' 

379 return float(self._fprs) 

380 

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

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

383 

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

385 

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

387 ''' 

388 return self.floor 

389 

390 def __floordiv__(self, other): 

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

392 

393 @arg other: An L{Fsum} or C{scalar} divisor. 

394 

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

396 

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

398 ''' 

399 f = self._copy_2(self.__floordiv__) 

400 return f._floordiv(other, _floordiv_op_) 

401 

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

403 '''Not implemented.''' 

404 return _NotImplemented(self, *other) 

405 

406 def __ge__(self, other): 

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

408 ''' 

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

410 

411 def __gt__(self, other): 

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

413 ''' 

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

415 

416 def __hash__(self): # PYCHOK no cover 

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

418 ''' 

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

420 

421 def __iadd__(self, other): 

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

423 

424 @arg other: An L{Fsum} or C{scalar} instance. 

425 

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

427 

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

429 C{scalar} nor L{Fsum}. 

430 

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

432 ''' 

433 return self._fadd(other, _iadd_op_) 

434 

435 def __ifloordiv__(self, other): 

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

437 

438 @arg other: An L{Fsum} or C{scalar} divisor. 

439 

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

441 

442 @raise ResidualError: Non-zero residual in B{C{other}}. 

443 

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

445 

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

447 

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

449 

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

451 ''' 

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

453 

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

455 '''Not implemented.''' 

456 return _NotImplemented(self, other) 

457 

458 def __imod__(self, other): 

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

460 

461 @arg other: An L{Fsum} or C{scalar} modulus. 

462 

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

464 

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

466 ''' 

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

468 

469 def __imul__(self, other): 

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

471 

472 @arg other: An L{Fsum} or C{scalar} factor. 

473 

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

475 

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

477 

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

479 

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

481 ''' 

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

483 

484 def __int__(self): 

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

486 

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

488 and L{Fsum.__floor__} and properties 

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

490 ''' 

491 i, _ = self._fint2 

492 return i 

493 

494 def __invert__(self): # PYCHOK no cover 

495 '''Not implemented.''' 

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

497 return _NotImplemented(self) 

498 

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

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

501 

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

503 @arg mod: Optional modulus (C{int} or C{None}) for the 

504 3-argument C{pow(B{self}, B{other}, B{mod})} 

505 version. 

506 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

507 (C{bool}), see also method L{RESIDUAL}. 

508 

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

510 

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

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

513 set to C{as_integer} if B{C{mod}} given as C{None}. 

514 

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

516 

517 @raise ResidualError: Non-zero residual in B{C{other}} and 

518 env var C{PYGEODESY_FSUM_RESIDUAL} 

519 set or this instance has a non-zero 

520 residual and either B{C{mod}} is 

521 given and non-C{None} or B{C{other}} 

522 is a negative or fractional C{scalar}. 

523 

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

525 C{pow} invocation failed. 

526 

527 @raise ValueError: If B{C{other}} is a negative C{scalar} 

528 and this instance is C{0} or B{C{other}} 

529 is a fractional C{scalar} and this 

530 instance is negative or has a non-zero 

531 residual or B{C{mod}} is given and C{0}. 

532 

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

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

535 ''' 

536 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser) 

537 

538 def __isub__(self, other): 

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

540 

541 @arg other: An L{Fsum} or C{scalar}. 

542 

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

544 

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

546 

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

548 ''' 

549 return self._fsub(other, _isub_op_) 

550 

551 def __iter__(self): 

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

553 ''' 

554 return iter(self.partials) 

555 

556 def __itruediv__(self, other, **raiser): 

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

558 

559 @arg other: An L{Fsum} or C{scalar} divisor. 

560 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

561 (C{bool}), see also method L{RESIDUAL}. 

562 

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

564 

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

566 

567 @raise ResidualError: Non-zero residual in B{C{other}} and 

568 env var C{PYGEODESY_FSUM_RESIDUAL} set. 

569 

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

571 

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

573 

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

575 

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

577 ''' 

578 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser) 

579 

580 def __le__(self, other): 

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

582 ''' 

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

584 

585 def __len__(self): 

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

587 ''' 

588 return self._n 

589 

590 def __lt__(self, other): 

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

592 ''' 

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

594 

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

596 '''Not implemented.''' 

597 return _NotImplemented(self, other) 

598 

599 def __mod__(self, other): 

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

601 

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

603 ''' 

604 f = self._copy_2(self.__mod__) 

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

606 

607 def __mul__(self, other): 

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

609 

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

611 ''' 

612 f = self._copy_2(self.__mul__) 

613 return f._fmul(other, _mul_op_) 

614 

615 def __ne__(self, other): 

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

617 ''' 

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

619 

620 def __neg__(self): 

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

622 ''' 

623 f = self._copy_2(self.__neg__) 

624 return f._fset(self._neg) 

625 

626 def __pos__(self): 

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

628 ''' 

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

630 

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

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

633 

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

635 ''' 

636 f = self._copy_2(self.__pow__) 

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

638 

639 def __radd__(self, other): 

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

641 

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

643 ''' 

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

645 return f._fadd(self, _add_op_) 

646 

647 def __rdivmod__(self, other): 

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

649 remainder)}. 

650 

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

652 ''' 

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

654 return f._fdivmod2(self, _divmod_op_) 

655 

656# def __repr__(self): 

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

658# ''' 

659# return self.toRepr(lenc=True) 

660 

661 def __rfloordiv__(self, other): 

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

663 

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

665 ''' 

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

667 return f._floordiv(self, _floordiv_op_) 

668 

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

670 '''Not implemented.''' 

671 return _NotImplemented(self, other) 

672 

673 def __rmod__(self, other): 

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

675 

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

677 ''' 

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

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

680 

681 def __rmul__(self, other): 

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

683 

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

685 ''' 

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

687 return f._fmul(self, _mul_op_) 

688 

689 def __round__(self, *ndigits): # PYCHOK no cover 

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

691 

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

693 ''' 

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

695 return _Psum_(round(float(self), *ndigits), # can be C{int} 

696 name=self.__round__.__name__) 

697 

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

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

700 

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

702 ''' 

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

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

705 

706 def __rsub__(self, other): 

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

708 

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

710 ''' 

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

712 return f._fsub(self, _sub_op_) 

713 

714 def __rtruediv__(self, other, **raiser): 

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

716 

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

718 ''' 

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

720 return f._ftruediv(self, _truediv_op_, **raiser) 

721 

722 def __str__(self): 

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

724 ''' 

725 return self.toStr(lenc=True) 

726 

727 def __sub__(self, other): 

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

729 

730 @arg other: An L{Fsum} or C{scalar}. 

731 

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

733 

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

735 ''' 

736 f = self._copy_2(self.__sub__) 

737 return f._fsub(other, _sub_op_) 

738 

739 def __truediv__(self, other, **raiser): 

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

741 

742 @arg other: An L{Fsum} or C{scalar} divisor. 

743 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

744 (C{bool}), see also method L{RESIDUAL}. 

745 

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

747 

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

749 ''' 

750 f = self._copy_2(self.__truediv__) 

751 return f._ftruediv(other, _truediv_op_, **raiser) 

752 

753 __trunc__ = __int__ 

754 

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

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

757 __div__ = __truediv__ 

758 __idiv__ = __itruediv__ 

759 __long__ = __int__ 

760 __nonzero__ = __bool__ 

761 __rdiv__ = __rtruediv__ 

762 

763 def as_integer_ratio(self): 

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

765 

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

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

768 

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

770 ''' 

771 n, r = self._fint2 

772 if r: 

773 i, d = r.as_integer_ratio() 

774 n *= d 

775 n += i 

776 else: # PYCHOK no cover 

777 d = 1 

778 return n, d 

779 

780 @property_RO 

781 def as_iscalar(self): 

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

783 ''' 

784 s, r = self._fprs2 

785 return self if r else s 

786 

787 @property_RO 

788 def ceil(self): 

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

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

791 

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

793 

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

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

796 ''' 

797 s, r = self._fprs2 

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

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

800 c += 1 

801 return c 

802 

803 def _cmp_0(self, other, op): 

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

805 ''' 

806 if isinstance(other, Fsum): 

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

808 elif self._scalar(other, op): 

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

810 else: 

811 s, r = self._fprs2 

812 s = _signOf(s, -r) 

813 return s 

814 

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

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

817 

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

819 ''' 

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

821 if f._ps is self._ps: 

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

823 if not deep: 

824 f._n = 1 

825 return f 

826 

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

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

829 ''' 

830 n = name or which.__name__ 

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

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

833 # assert f._n == self._n 

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

835 return f 

836 

837 def _copy_2r(self, other, which): 

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

839 ''' 

840 return other._copy_2(which) if isinstance(other, Fsum) else \ 

841 Fsum(other, name=which.__name__) 

842 

843# def _copy_RESIDUAL(self, other): 

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

845# ''' 

846# R = other._RESIDUAL 

847# if R is not Fsum._RESIDUAL: 

848# self._RESIDUAL = R 

849 

850 def divmod(self, other, **raiser): 

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

852 remainder)}. 

853 

854 @arg other: An L{Fsum} or C{scalar} divisor. 

855 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

856 (C{bool}), see also method L{RESIDUAL}. 

857 

858 @return: A L{DivMod2Tuple}C{(div, mod)}, with quotient C{div} 

859 an C{int} in Python 3+ or C{float} in Python 2- and 

860 remainder C{mod} an L{Fsum} instance. 

861 

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

863 ''' 

864 f = self._copy_2(self.divmod) 

865 return f._fdivmod2(other, _divmod_op_, **raiser) 

866 

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

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

869 ''' 

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

871 

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

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

874 ''' 

875 E, t = _xError2(X) 

876 if mod: 

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

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

879 

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

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

882 ''' 

883 E, t = _xError2(X) 

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

885 return E(n, txt=t, cause=X) 

886 

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

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

889 ''' 

890 if xs: 

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

892 ps = self._ps 

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

894 return self 

895 

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

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

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

899 ''' 

900 # assert islistuple(xs) 

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

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

903 

904 def _facc_neg(self, xs, up=True, **origin): 

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

906 ''' 

907 if xs: 

908 def _neg(x): 

909 return -x 

910 

911 _x = _2floats(xs, **origin) # PYCHOK yield 

912 ps = self._ps 

913 ps[:] = self._ps_acc(list(ps), map(_neg, _x), up=up) 

914 return self 

915 

916 def _facc_power(self, power, xs, which, **raiser): # in .fmath 

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

918 ''' 

919 def _Pow4(p): 

920 r = 0 

921 if isinstance(p, Fsum): 

922 s, r = p._fprs2 

923 if r == 0: 

924 return _Pow4(s) 

925 m = Fsum._pow 

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

927 p = s = int(p) 

928 m = Fsum._pow_int 

929 else: 

930 p = s = _2float(power=p) 

931 m = Fsum._pow_scalar 

932 return m, p, s, r 

933 

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

935 if p: # and xs: 

936 _pow = Fsum._pow_2_3 

937 _Fs = Fsum 

938 _Ps = _Psum_ # ()._fset_ps_ 

939 op = which.__name__ 

940 

941 def _X(X): 

942 f = _Pow(X, p, power, op, **raiser) 

943 return f._ps if isinstance(f, _Fs) else (f,) 

944 

945 def _x(x): 

946 x = float(x) 

947 X = _Ps(x) 

948 f = _pow(X, x, s, power, op, **raiser) 

949 if r: 

950 f *= _pow(X, x, r, power, op, **raiser) 

951 return f 

952 

953 f = self._facc(xs, origin=1, _X=_X, _x=_x) 

954 else: 

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

956 return f 

957 

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

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

960 ''' 

961 if xs: 

962 self._ps_acc(self._ps, xs, **up) 

963 return self 

964 

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

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

967 ''' 

968 if xs: 

969 self._ps_acc(self._ps, xs, **up) 

970 return self 

971 

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

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

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

975# ''' 

976# while len(self._ps) > 1: 

977# p = self._ps.pop() 

978# if p: 

979# n = self._n 

980# self._facc_scalar_(p, up=False) 

981# self._n = n 

982# break 

983# return self._update() if up else self # ._fpsqz() 

984 

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

986 '''Add an iterable of C{scalar} or L{Fsum} instances 

987 to this instance. 

988 

989 @arg xs: Iterable, list, tuple, etc. (C{scalar} or 

990 L{Fsum} instances). 

991 

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

993 

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

995 

996 @raise TypeError: An invalid B{C{xs}} type, not C{scalar} 

997 nor L{Fsum}. 

998 

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

1000 ''' 

1001 if isinstance(xs, Fsum): 

1002 self._facc_scalar(xs._ps) # tuple 

1003 elif isscalar(xs): # for backward compatibility 

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

1005 elif xs: # assert isiterable(xs) 

1006 self._facc(xs) 

1007 return self 

1008 

1009 def fadd_(self, *xs): 

1010 '''Add all positional C{scalar} or L{Fsum} instances 

1011 to this instance. 

1012 

1013 @arg xs: Values to add (C{scalar} or L{Fsum} instances), 

1014 all positional. 

1015 

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

1017 

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

1019 

1020 @raise TypeError: An invalid B{C{xs}} type, not C{scalar} 

1021 nor L{Fsum}. 

1022 

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

1024 ''' 

1025 return self._facc_1(xs) 

1026 

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

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

1029 ''' 

1030 if isinstance(other, Fsum): 

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

1032 elif self._scalar(other, op): 

1033 self._facc_scalar_(other, **up) 

1034 return self 

1035 

1036 fcopy = copy # for backward compatibility 

1037 fdiv = __itruediv__ # for backward compatibility 

1038 fdivmod = __divmod__ # for backward compatibility 

1039 

1040 def _fdivmod2(self, other, op, **raiser): 

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

1042 ''' 

1043 # result mostly follows CPython function U{float_divmod 

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

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

1046 f = self._copy_2(self._fdivmod2) 

1047 q = f._ftruediv(other, op, **raiser).floor 

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

1049 self -= other * q 

1050 

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

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

1053 self += other 

1054 q -= 1 

1055# t = self.signOf() 

1056# if t and t != s: 

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

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

1059 

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

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

1062 ''' 

1063 if _isfinite(other): 

1064 return other 

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

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

1067 

1068 def fint(self, raiser=True, name=NN, **RESIDUAL): 

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

1070 

1071 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

1072 (C{bool}), see also method L{RESIDUAL}. 

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

1074 @kwarg RESIDUAL: Optional threshold, overriding the current 

1075 L{RESIDUAL<Fsum.RESIDUAL>} (C{scalar}). 

1076 

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

1078 C{is_integer} and the residual is zero or 

1079 insignificant or if C{B{raiser}=False}. 

1080 

1081 @raise ResidualError: Non-zero I{integer} residual. 

1082 

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

1084 ''' 

1085 i, r = self._fint2 

1086 if r and raiser and self._raiser2sum(r, i, **RESIDUAL): 

1087 t = _stresidual(_integer_, r) 

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

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

1090 return f._fset(i) 

1091 

1092 def fint2(self, **name): 

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

1094 the I{integer} residual. 

1095 

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

1097 

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

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

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

1101 ''' 

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

1103 

1104 @Property_RO 

1105 def _fint2(self): # see ._fset 

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

1107 ''' 

1108 s, r = self._fprs2 

1109 i = int(s) 

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

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

1112 

1113 @deprecated_property_RO 

1114 def float_int(self): # PYCHOK no cover 

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

1116 return self.int_float() # raiser=False 

1117 

1118 @property_RO 

1119 def floor(self): 

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

1121 C{float} in Python 2-). 

1122 

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

1124 

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

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

1127 ''' 

1128 s, r = self._fprs2 

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

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

1131 f -= 1 

1132 return f 

1133 

1134# floordiv = __floordiv__ # for naming consistency 

1135 

1136 def _floordiv(self, other, op, **raiser): # rather _ffloordiv? 

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

1138 ''' 

1139 q = self._ftruediv(other, op, **raiser) # == self 

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

1141 

1142 fmul = __imul__ # for backward compatibility 

1143 

1144 def _fmul(self, other, op): 

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

1146 ''' 

1147 if isinstance(other, Fsum): 

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

1149 f = self._mul_Fsum(other, op) 

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

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

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

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

1154 else: 

1155 s = self._scalar(other, op) 

1156 f = self._mul_scalar(s, op) 

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

1158 

1159 def fover(self, over, **raiser): 

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

1161 

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

1163 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

1164 (C{bool}), see also method L{RESIDUAL}. 

1165 

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

1167 

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

1169 ''' 

1170 return float(self.fdiv(over, **raiser)._fprs) 

1171 

1172 fpow = __ipow__ # for backward compatibility 

1173 

1174 def _fpow(self, other, op, *mod, **raiser): 

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

1176 ''' 

1177 if mod: 

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

1179 f = self._pow_2_3(self, other, other, op, *mod, **raiser) 

1180 elif self.is_integer(): 

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

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

1183 x = _2scalar(other) # C{int}, C{float} or other 

1184 f = self._pow_2_3(i, x, other, op, **raiser) if isscalar(x) else \ 

1185 _Psum_(i)._pow( x, other, op, **raiser) # x is Fsum 

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

1187 f = self._pow(other, other, op, **raiser) 

1188 else: # pow(self, other) 

1189 f = self._pow(other, other, op, **raiser) 

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

1191 

1192 @Property_RO 

1193 def _fprs(self): 

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

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

1196 

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

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

1199 ''' 

1200 return self._fprs2.fsum 

1201 

1202 @Property_RO 

1203 def _fprs2(self): 

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

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

1206 ''' 

1207 ps = self._ps 

1208 n = len(ps) - 2 

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

1210 s = _psum(ps) 

1211 n = len(ps) - 2 

1212 if n > 0: 

1213 r = _fsum(self._ps_1primed(s)) or INT0 

1214 return Fsum2Tuple(s, r) 

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

1216 ps[:] = _2ps(*_2sum(*ps)) 

1217 r, s = (INT0, ps[0]) if len(ps) != 2 else ps 

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

1219 s, r = ps[0], INT0 

1220 else: # len(ps) == 0 

1221 s, r = _0_0, INT0 

1222 ps[:] = s, 

1223 # assert self._ps is ps 

1224 return Fsum2Tuple(s, r) 

1225 

1226# def _fpsqz(self): 

1227# '''(INTERNAL) Compress, squeeze the C{partials}. 

1228# ''' 

1229# if len(self._ps) > 2: 

1230# _ = self._fprs2 

1231# return self 

1232 

1233 def fset_(self, *xs): 

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

1235 

1236 @arg xs: Optional, new values (C{scalar} or L{Fsum} 

1237 instances), all positional. 

1238 

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

1240 

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

1242 ''' 

1243 self._ps[:] = 0, 

1244 self._n = 0 

1245 return self.fadd(xs) if xs else self._update() 

1246 

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

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

1249 ''' 

1250 if other is self: 

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

1252 elif isinstance(other, Fsum): 

1253 self._ps[:] = other._ps 

1254 self._n = n or other._n 

1255# self._copy_RESIDUAL(other) 

1256 # use or zap the C{Property_RO} values 

1257 Fsum._fint2._update_from(self, other) 

1258 Fsum._fprs ._update_from(self, other) 

1259 Fsum._fprs2._update_from(self, other) 

1260 elif isscalar(other): 

1261 s = other if asis else float(other) 

1262 i = int(s) # see ._fint2 

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

1264 self._ps[:] = s, 

1265 self._n = n or 1 

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

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

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

1269 else: # PYCHOK no cover 

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

1271 return self 

1272 

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

1274 '''(INTERNAL) Set partials from a known C{Fsum} or C{scalar}. 

1275 ''' 

1276 if isinstance(other, Fsum): 

1277 self._ps[:] = other._ps 

1278 self._n = n or other._n 

1279 else: # assert isscalar(other) 

1280 self._ps[:] = other, 

1281 self._n = n or 1 

1282 return self 

1283 

1284# def _fset_ps_(self, *xs): 

1285# '''(INTERNAL) Set partials to all known scalar C{xs}. 

1286# ''' 

1287# self._ps[:] = xs 

1288# self.n = len(xs) 

1289# return self 

1290 

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

1292 '''Subtract an iterable of C{scalar} or L{Fsum} instances from 

1293 this instance. 

1294 

1295 @arg xs: Iterable, list, tuple. etc. (C{scalar} or L{Fsum} 

1296 instances). 

1297 

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

1299 

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

1301 ''' 

1302 return self._facc_neg(xs) 

1303 

1304 def fsub_(self, *xs): 

1305 '''Subtract all positional C{scalar} or L{Fsum} instances from 

1306 this instance. 

1307 

1308 @arg xs: Values to subtract (C{scalar} or L{Fsum} instances), 

1309 all positional. 

1310 

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

1312 

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

1314 ''' 

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

1316 self._facc_neg(xs, origin=1) 

1317 

1318 def _fsub(self, other, op): 

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

1320 ''' 

1321 if isinstance(other, Fsum): 

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

1323 self._fset(_0_0) # n=len(self) * 2, self -= self 

1324 elif other._ps: 

1325 self._facc_scalar(other._ps_neg) 

1326 elif self._scalar(other, op): 

1327 self._facc_scalar_(-self._finite(other, op)) 

1328 return self 

1329 

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

1331 '''Add more C{scalar} or L{Fsum} instances and summate. 

1332 

1333 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or 

1334 L{Fsum} instances). 

1335 

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

1337 

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

1339 

1340 @note: Accumulation can continue after summation. 

1341 ''' 

1342 return self._facc(xs)._fprs 

1343 

1344 def fsum_(self, *xs): 

1345 '''Add all positional C{scalar} or L{Fsum} instances and summate. 

1346 

1347 @arg xs: Values to add (C{scalar} or L{Fsum} instances), all 

1348 positional. 

1349 

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

1351 

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

1353 ''' 

1354 return self._facc_1(xs)._fprs 

1355 

1356 def Fsum_(self, *xs): 

1357 '''Like method L{Fsum.fsum_} but returning an L{Fsum}. 

1358 

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

1360 ''' 

1361 return self._facc_1(xs)._copy_2(self.Fsum_) 

1362 

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

1364 '''Add more C{scalar} or L{Fsum} instances and return the 

1365 current precision running sum and the C{residual}. 

1366 

1367 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or L{Fsum} 

1368 instances). 

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

1370 

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

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

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

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

1375 to be I{exact}. 

1376 

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

1378 ''' 

1379 t = self._facc(xs)._fprs2 

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

1381 

1382 def fsum2_(self, *xs): 

1383 '''Add any positional C{scalar} or L{Fsum} instances and return 

1384 the precision running sum and the C{differential}. 

1385 

1386 @arg xs: Values to add (C{scalar} or L{Fsum} instances), all 

1387 positional. 

1388 

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

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

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

1392 

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

1394 ''' 

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

1396 

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

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

1399 ''' 

1400 p, q = self._fprs2 

1401 if xs: 

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

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

1404 else: 

1405 return p, _0_0 

1406 

1407 def fsumf_(self, *xs): 

1408 '''Like method L{Fsum.fsum_} but only for C{B{xs}}, I{known to be scalar}. 

1409 ''' 

1410 return self._facc_scalar(xs)._fprs 

1411 

1412 def Fsumf_(self, *xs): 

1413 '''Like method L{Fsum.Fsum_} but only for C{B{xs}}, I{known to be scalar}. 

1414 ''' 

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

1416 

1417 def fsum2f_(self, *xs): 

1418 '''Like method L{Fsum.fsum2_} but only for C{B{xs}}, I{known to be scalar}. 

1419 ''' 

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

1421 

1422# ftruediv = __itruediv__ # for naming consistency? 

1423 

1424 def _ftruediv(self, other, op, **raiser): 

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

1426 ''' 

1427 n = _1_0 

1428 if isinstance(other, Fsum): 

1429 if other is self or other == self: 

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

1431 d, r = other._fprs2 

1432 if r: 

1433 if d: 

1434 if self._raiser(r, d, **raiser): 

1435 raise self._ResidualError(op, other, r) 

1436 d, n = other.as_integer_ratio() 

1437 else: # PYCHOK no cover 

1438 d = r 

1439 else: 

1440 d = self._scalar(other, op) 

1441 try: 

1442 s = n / d 

1443 except Exception as X: 

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

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

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

1447 

1448 @property_RO 

1449 def imag(self): 

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

1451 

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

1453 ''' 

1454 return _0_0 

1455 

1456 def int_float(self, raiser=False, **RESIDUAL): 

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

1458 

1459 @kwarg raiser: If C{True} throw a L{ResidualError} if the 

1460 residual exceeds the C{RESIDUAL} (C{bool}). 

1461 @kwarg RESIDUAL: Optional threshold, overriding the current 

1462 L{RESIDUAL<Fsum.RESIDUAL>} (C{scalar}). 

1463 

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

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

1466 zero or insignificant or if C{B{raiser}=False}. 

1467 

1468 @raise ResidualError: Non-zero residual and C{B{raiser}=True}. 

1469 

1470 @see: Methods L{Fsum.fint} and L{Fsum.fint2} and property L{Fsum.as_iscalar}. 

1471 ''' 

1472 s, r = self._fint2 

1473 if r: 

1474 s, r = self._fprs2 

1475 if r and raiser and self._raiser2sum(r, s, **RESIDUAL): # PYCHOK no cover 

1476 t = _stresidual(_non_zero_, r) 

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

1478 s = float(s) # redundant 

1479 return s 

1480 

1481 def is_exact(self): 

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

1483 ''' 

1484 return self.residual is INT0 

1485 

1486 def is_integer(self): 

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

1488 

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

1490 ''' 

1491 _, r = self._fint2 

1492 return False if r else True 

1493 

1494 def is_math_fsum(self): 

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

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

1497 C{math.fsum} or not. 

1498 

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

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

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

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

1503 none are. 

1504 ''' 

1505 f = Fsum._math_fsum 

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

1507 

1508 def is_scalar(self): 

1509 '''Is this instance' running sum C{scalar}? (C{bool}). 

1510 

1511 @see: Method L{Fsum.is_integer} and property L{Fsum.as_iscalar}. 

1512 ''' 

1513 s, r = t = self._fprs2 

1514 return False if r and _2sum(s, r) != t else True 

1515 

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

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

1518 ''' 

1519 # assert isinstance(other, Fsum) 

1520 if self._ps and other._ps: 

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

1522 else: 

1523 f = _0_0 

1524 return f 

1525 

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

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

1528 ''' 

1529 # assert isscalar(factor) 

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

1531 f = self if factor == _1_0 else ( 

1532 self._neg if factor == _N_1_0 else 

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

1534 else: 

1535 f = _0_0 

1536 return f 

1537 

1538 @property_RO 

1539 def _neg(self): 

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

1541 ''' 

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

1543 

1544 @property_RO 

1545 def partials(self): 

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

1547 ''' 

1548 return tuple(self._ps) 

1549 

1550 def pow(self, x, *mod, **raiser): 

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

1552 

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

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

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

1556 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

1557 (C{bool}), see also method L{RESIDUAL}. 

1558 

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

1560 result (L{Fsum}). 

1561 

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

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

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

1565 

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

1567 and L{Fsum.root}. 

1568 ''' 

1569 f = self._copy_2(self.pow) 

1570 return f._fpow(x, _pow_op_, *mod, **raiser) # f = pow(f, x, *mod) 

1571 

1572 def _pow(self, other, unused, op, **raiser): 

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

1574 ''' 

1575 if isinstance(other, Fsum): 

1576 x, r = other._fprs2 

1577 if r and self._raiser(r, x, **raiser): 

1578 raise self._ResidualError(op, other, r) 

1579 f = self._pow_scalar(x, other, op, **raiser) 

1580 if r: 

1581 f *= self._pow_scalar(r, other, op, **raiser) 

1582 elif self._scalar(other, op): 

1583 x = self._finite(other, op) 

1584 f = self._pow_scalar(x, other, op, **raiser) 

1585 else: 

1586 f = self._pow_0_1(0, other) 

1587 return f 

1588 

1589 def _pow_0_1(self, x, other): 

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

1591 ''' 

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

1593 

1594 def _pow_2_3(self, b, x, other, op, *mod, **raiser): 

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

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

1597 ''' 

1598 try: 

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

1600 m = mod[0] 

1601 b, r = b._fprs2 if m is None else b._fint2 

1602 if r and self._raiser(r, b, **raiser): 

1603 t = _non_zero_ if m is None else _integer_ 

1604 raise ResidualError(_stresidual(t, r, mod=m), txt=None) 

1605 x = _2scalar(x, _raiser=self._raiser, mod=m) 

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

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

1608 if iscomplex(s): 

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

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

1611 return self._finite(s) 

1612 except Exception as X: 

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

1614 

1615 def _pow_int(self, x, other, op, **raiser): 

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

1617 ''' 

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

1619 ps = self._ps 

1620 if len(ps) > 1: 

1621 _mul_Fsum = Fsum._mul_Fsum 

1622 if x > 4: 

1623 p = self 

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

1625 m = x >> 1 # // 2 

1626 while m: 

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

1628 if (m & 1): 

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

1630 m >>= 1 # //= 2 

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

1632 f = _mul_Fsum(self, self, op) 

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

1634 p = self if x < 4 else f 

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

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

1637 f = self._pow_0_1(x, other) 

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

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

1640 else: # PYCHOK no cover 

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

1642 f = 0 if x else 1 

1643 return f 

1644 

1645 def _pow_scalar(self, x, other, op, **raiser): 

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

1647 ''' 

1648 s, r = self._fprs2 

1649 if isint(x, both=True): 

1650 x = int(x) # Fsum**int 

1651 y = abs(x) 

1652 if y > 1: 

1653 if r: 

1654 f = self._pow_int(y, other, op, **raiser) 

1655 if x > 0: # > 1 

1656 return f 

1657 # assert x < 0 # < -1 

1658 s, r = f._fprs2 if isinstance(f, Fsum) else (f, 0) 

1659 if r: 

1660 return _1_over(f, op, **raiser) # PYCHOK 2 args 

1661 # use **= -1 for the CPython float_pow 

1662 # error if s is zero, and not s = 1 / s 

1663 x = -1 

1664 elif x < 0: # == -1: self**(-1) == 1 / self 

1665 if r: 

1666 return _1_over(self, op, **raiser) # PYCHOK 2 args 

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

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

1669 elif r: # non-zero residual**fractional 

1670 if s: 

1671 n, d = self.as_integer_ratio() 

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

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

1674 s = n / d 

1675 else: 

1676 s = r 

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

1678 return self._pow_2_3(s, x, other, op, **raiser) 

1679 

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

1681 '''(INTERNAL) Accumulate all scalar C{xs} into C{ps}. 

1682 ''' 

1683 n = 0 

1684 _2s = _2sum 

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

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

1687 if x: 

1688 i = 0 

1689 for p in ps: 

1690 x, p = _2s(x, p) 

1691 if p: 

1692 ps[i] = p 

1693 i += 1 

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

1695 n += 1 

1696 if n: 

1697 self._n += n 

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

1699 if up: 

1700 self._update() 

1701 return ps 

1702 

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

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

1705 each of the scalar B{C{factors}} and accumulate. 

1706 ''' 

1707 def _pfs(ps, fs): 

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

1709 ps, fs = fs, ps 

1710 _fin = _isfinite 

1711 for f in fs: 

1712 for p in ps: 

1713 p *= f 

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

1715 

1716 return _Psum(self._ps_acc([], _pfs(self._ps, factors))) 

1717 

1718 @property_RO 

1719 def _ps_neg(self): 

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

1721 ''' 

1722 for p in self._ps: 

1723 yield -p 

1724 

1725 def _ps_1primed(self, *less): 

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

1727 ''' 

1728 yield _1_0 

1729 for p in self._ps: 

1730 yield p 

1731 for p in less: 

1732 yield -p 

1733 yield _N_1_0 

1734 

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

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

1737 ''' 

1738 self._ratio = r = (r / s) if s else s # == 0. 

1739 if r and raiser: 

1740 R = self._RESIDUAL 

1741 if RESIDUAL: 

1742 R = _xkwds_get(RESIDUAL, RESIDUAL=R) 

1743 return fabs(r) > R 

1744 return False 

1745 

1746 def _raiser2sum(self, r, s, **raiser_RESIDUAL): 

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

1748 I{and} is the residual B{C{r}} significant vs sum B{C{s}}? 

1749 ''' 

1750 return self._raiser(r, s, **raiser_RESIDUAL) and _2sum(s, r) != (s, r) 

1751 

1752 @property_RO 

1753 def real(self): 

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

1755 

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

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

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

1759 ''' 

1760 return float(self._fprs) 

1761 

1762 @property_RO 

1763 def residual(self): 

1764 '''Get this instance' residual (C{float} or C{int}), the 

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

1766 

1767 @note: If the C{residual is INT0}, the precision running 

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

1769 

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

1771 ''' 

1772 return self._fprs2.residual 

1773 

1774 def RESIDUAL(self, *threshold): 

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

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

1777 

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

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

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

1781 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

1782 current setting. 

1783 

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

1785 

1786 @raise ValueError: Negative B{C{threshold}}. 

1787 

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

1789 C{residual / fsum} exceeds the B{C{threshold}}. 

1790 ''' 

1791 r = self._RESIDUAL 

1792 if threshold: 

1793 t = threshold[0] 

1794 t = Fsum._RESIDUAL if t is None else ( 

1795 float(t) if isscalar(t) else ( # for backward ... 

1796 _0_0 if bool(t) else _1_0)) # ... compatibility 

1797 if t < 0: 

1798 u = _DOT_(self, unstr(self.RESIDUAL, *threshold)) 

1799 raise _ValueError(u, RESIDUAL=t, txt=_negative_) 

1800 self._RESIDUAL = t 

1801 return r 

1802 

1803 def _ResidualError(self, op, other, residual): 

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

1805 ''' 

1806 t = _stresidual(_non_zero_, residual, ratio=self._ratio, 

1807 RESIDUAL=self._RESIDUAL) 

1808 t = t.replace(_COMMASPACE_R_, _exceeds_R_) 

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

1810 

1811 def root(self, root, **raiser): 

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

1813 

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

1815 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s 

1816 (C{bool}), see also method L{RESIDUAL}. 

1817 

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

1819 

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

1821 ''' 

1822 x = _1_over(root, **raiser) 

1823 f = self._copy_2(self.root) 

1824 return f._fpow(x, f.name, **raiser) # == pow(f, x) 

1825 

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

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

1828 ''' 

1829 if isscalar(other): 

1830 return other 

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

1832 

1833 def signOf(self, res=True): 

1834 '''Determine the sign of this instance. 

1835 

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

1837 ignore the residual (C{bool}). 

1838 

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

1840 ''' 

1841 s, r = self._fprs2 

1842 return _signOf(s, (-r) if res else 0) 

1843 

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

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

1846 

1847 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1851 

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

1853 ''' 

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

1855 

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

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

1858 

1859 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1863 

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

1865 ''' 

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

1867 

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

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

1870 ''' 

1871 n = self.named3 

1872 if lenc: 

1873 n = Fmt.SQUARE(n, len(self)) 

1874 return _SPACE_(n, toT(fmt=fmt, **kwds)) 

1875 

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

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

1878 ''' 

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

1880 

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

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

1883 ''' 

1884 if updated: 

1885 _pop = self.__dict__.pop 

1886 for p in _ROs: 

1887 _ = _pop(p, None) 

1888# Fsum._fint2._update(self) 

1889# Fsum._fprs ._update(self) 

1890# Fsum._fprs2._update(self) 

1891 return self # for .fset_ 

1892 

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

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

1895 ''' 

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

1897 

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

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

1900 ''' 

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

1902 

1903_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK assert, see Fsum._fset, -._update 

1904 

1905 

1906def _Float_Int(arg, **name_Error): 

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

1908 ''' 

1909 U = Int if isint(arg) else Float 

1910 return U(arg, **name_Error) 

1911 

1912 

1913class DivMod2Tuple(_NamedTuple): 

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

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

1916 

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

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

1919 ''' 

1920 _Names_ = (_div_, _mod_) 

1921 _Units_ = (_Float_Int, Fsum) 

1922 

1923 

1924class Fsum2Tuple(_NamedTuple): 

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

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

1927 item is either C{float} or C{int}. 

1928 

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

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

1931 ''' 

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

1933 _Units_ = (_Float_Int, _Float_Int) 

1934 

1935 @Property_RO 

1936 def _Fsum(self): 

1937 '''(INTERNAL) Get this L{Fsum2Tuple} as an L{Fsum}. 

1938 ''' 

1939 s, r = map(float, self) 

1940 return _Psum(_2ps(s, r), name=self.name) 

1941 

1942 def is_exact(self): 

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

1944 ''' 

1945 return self._Fsum.is_exact() 

1946 

1947 def is_integer(self): 

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

1949 ''' 

1950 return self._Fsum.is_integer() 

1951 

1952 

1953class ResidualError(_ValueError): 

1954 '''Error raised for an operation involving a L{pygeodesy.sums.Fsum} 

1955 instance with a non-zero C{residual}, I{integer} or otherwise. 

1956 

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

1958 ''' 

1959 pass 

1960 

1961 

1962try: 

1963 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+ 

1964 

1965 # make sure _fsum works as expected (XXX check 

1966 # float.__getformat__('float')[:4] == 'IEEE'?) 

1967 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover 

1968 del _fsum # nope, remove _fsum ... 

1969 raise ImportError # ... use _fsum below 

1970 

1971 Fsum._math_fsum = _sum = _fsum # PYCHOK exported 

1972 

1973 if _getenv('PYGEODESY_FSUM_PARTIALS', NN) == _fsum.__name__: 

1974 _psum = _fsum # PYCHOK re-def 

1975 

1976except ImportError: 

1977 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic 

1978 

1979 def _fsum(xs): 

1980 '''(INTERNAL) Precision summation, Python 2.5-. 

1981 ''' 

1982 f = Fsum() 

1983 f.name = _fsum.__name__ 

1984 return f.fsum(xs) 

1985 

1986 

1987def fsum(xs, floats=False): 

1988 '''Precision floating point summation based on or like Python's C{math.fsum}. 

1989 

1990 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum} 

1991 instances). 

1992 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} are known 

1993 to be C{float} scalars (C{bool}). 

1994 

1995 @return: Precision C{fsum} (C{float}). 

1996 

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

1998 

1999 @raise TypeError: Non-scalar B{C{xs}} value. 

2000 

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

2002 

2003 @note: Exception and I{non-finite} handling may differ if not based 

2004 on Python's C{math.fsum}. 

2005 

2006 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}. 

2007 ''' 

2008 return _fsum(xs if floats else _2floats(xs)) if xs else _0_0 # PYCHOK yield 

2009 

2010 

2011def fsum_(*xs, **floats): 

2012 '''Precision floating point summation of all positional arguments. 

2013 

2014 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all 

2015 positional. 

2016 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} are I{known 

2017 to be scalar} (C{bool}). 

2018 

2019 @return: Precision C{fsum} (C{float}). 

2020 

2021 @see: Function C{fsum}. 

2022 ''' 

2023 return _fsum(xs if _xkwds_get(floats, floats=False) else 

2024 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield 

2025 

2026 

2027def fsumf_(*xs): 

2028 '''Precision floating point summation, L{fsum_}C{(*B{xs}, floats=True)}, 

2029 but only for C{B{xs}} I{known to be scalar}. 

2030 ''' 

2031 return _fsum(xs) if xs else _0_0 

2032 

2033 

2034def fsum1(xs, floats=False): 

2035 '''Precision floating point summation, 1-primed. 

2036 

2037 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum} 

2038 instances). 

2039 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} are known 

2040 to be C{float}. 

2041 

2042 @return: Precision C{fsum} (C{float}). 

2043 

2044 @see: Function C{fsum}. 

2045 ''' 

2046 return _fsum(_1primed(xs if floats else _2floats(xs))) if xs else _0_0 # PYCHOK yield 

2047 

2048 

2049def fsum1_(*xs, **floats): 

2050 '''Precision floating point summation, 1-primed. 

2051 

2052 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all 

2053 positional. 

2054 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} are I{known 

2055 to be scalar} (C{bool}). 

2056 

2057 @return: Precision C{fsum} (C{float}). 

2058 

2059 @see: Function C{fsum} 

2060 ''' 

2061 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) else 

2062 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield 

2063 

2064 

2065def fsum1f_(*xs): 

2066 '''Precision floating point summation, L{fsum1_}C{(*B{xs}, floats=True)}, 

2067 but only for C{B{xs}} I{known to be scalar}. 

2068 ''' 

2069 return _fsum(_1primed(xs)) if xs else _0_0 

2070 

2071 

2072if __name__ == '__main__': 

2073 

2074 # usage: [env PYGEODESY_FSUM_PARTIALS=fsum] python3 -m pygeodesy.fsums 

2075 

2076 def _test(n): 

2077 # copied from Hettinger, see L{Fsum} reference 

2078 from pygeodesy import frandoms, printf 

2079 

2080 printf(_fsum.__name__, end=_COMMASPACE_) 

2081 printf(_psum.__name__, end=_COMMASPACE_) 

2082 

2083 F = Fsum() 

2084 if F.is_math_fsum(): 

2085 for t in frandoms(n, seeded=True): 

2086 assert float(F.fset_(*t)) == _fsum(t) 

2087 printf(_DOT_, end=NN) 

2088 printf(NN) 

2089 

2090 _test(128) 

2091 

2092# **) MIT License 

2093# 

2094# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved. 

2095# 

2096# Permission is hereby granted, free of charge, to any person obtaining a 

2097# copy of this software and associated documentation files (the "Software"), 

2098# to deal in the Software without restriction, including without limitation 

2099# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

2100# and/or sell copies of the Software, and to permit persons to whom the 

2101# Software is furnished to do so, subject to the following conditions: 

2102# 

2103# The above copyright notice and this permission notice shall be included 

2104# in all copies or substantial portions of the Software. 

2105# 

2106# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

2107# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

2108# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

2109# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

2110# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

2111# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

2112# OTHER DEALINGS IN THE SOFTWARE.