Coverage for pygeodesy/fsums.py: 96%

745 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-04-12 12:41 -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, isinf, isnan, NEG0, _pos_self, \ 

31 _0_0, _1_0, _N_1_0, Float, Int 

32from pygeodesy.errors import _OverflowError, _TypeError, _ValueError, _xError, \ 

33 _xError2, _xkwds_get, _ZeroDivisionError 

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

35 _exceeds_, _from_, _iadd_op_, _LANGLE_, _negative_, \ 

36 _NOTEQUAL_, _not_finite_, _not_scalar_, _PERCENT_, \ 

37 _PLUS_, _R_, _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_ 

38from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2 

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

40from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \ 

41 Property_RO, property_RO 

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

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

44 

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

46 

47__all__ = _ALL_LAZY.fsums 

48__version__ = '24.04.09' 

49 

50_add_op_ = _PLUS_ # in .auxilats.auxAngle 

51_eq_op_ = _EQUAL_ * 2 # _DEQUAL_ 

52_COMMASPACE_R_ = _COMMASPACE_ + _R_ 

53_div_ = 'div' 

54_exceeds_R_ = _SPACE_ + _exceeds_(_R_) 

55_floordiv_op_ = _SLASH_ * 2 # _DSLASH_ 

56_fset_op_ = _EQUAL_ 

57_ge_op_ = _RANGLE_ + _EQUAL_ 

58_gt_op_ = _RANGLE_ 

59_integer_ = 'integer' 

60_le_op_ = _LANGLE_ + _EQUAL_ 

61_lt_op_ = _LANGLE_ 

62_mod_ = 'mod' 

63_mod_op_ = _PERCENT_ 

64_mul_op_ = _STAR_ 

65_ne_op_ = _NOTEQUAL_ 

66_non_zero_ = 'non-zero' 

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

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

69_truediv_op_ = _SLASH_ 

70_divmod_op_ = _floordiv_op_ + _mod_op_ 

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

72 

73 

74def _2delta(*ab): 

75 '''(INTERNAL) Helper for C{Fsum.fsum2f_}. 

76 ''' 

77 try: 

78 a, b = _2sum(*ab) 

79 except _OverflowError: 

80 a, b = ab 

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

82 

83 

84def _2error(unused): 

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

86 ''' 

87 raise ValueError(_not_finite_) 

88 

89 

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

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

92 ''' 

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

94 try: 

95 v = float(v) 

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

97 except Exception as X: 

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

99 

100 

101def _X_ps(X): # for _2floats only 

102 return X._ps 

103 

104 

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

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

107 ''' 

108 try: 

109 i, x = origin, None 

110 _fin = _isfinite 

111 _Fs = Fsum 

112 for x in xs: 

113 if isinstance(x, _Fs): 

114 for p in _X(x): 

115 yield p 

116 else: 

117 f = _x(x) 

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

119 i += 1 

120 except Exception as X: 

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

122 

123 

124def _2halfeven(s, r, p): 

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

126 ''' 

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

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

129 r *= 2 

130 t = s + r 

131 if r == (t - s): 

132 s = t 

133 return s 

134 

135 

136def _1primed(xs): # in .fmath 

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

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

139 ''' 

140 yield _1_0 

141 for x in xs: 

142 yield x 

143 yield _N_1_0 

144 

145 

146def _2ps(s, r): 

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

148 ''' 

149 return (s, r) if fabs(s) < fabs(r) else (r, s) 

150 

151 

152def _psum(ps): # PYCHOK used! 

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

154 ''' 

155 # assert isinstance(ps, list) 

156 i = len(ps) - 1 

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

158 _2s = _2sum 

159 while i > 0: 

160 i -= 1 

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

162 if r: # sum(ps) became inexact 

163 if s: 

164 ps[i:] = r, s 

165 if i > 0: 

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

167 break # return s 

168 s = r # PYCHOK no cover 

169 ps[i:] = s, 

170 return s 

171 

172 

173def _Psum(ps, **name): 

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

175 ''' 

176 f = Fsum(**name) if name else Fsum() 

177 if ps: 

178 f._ps[:] = ps 

179 f._n = len(f._ps) 

180 return f 

181 

182 

183def _Psum_1(p=_1_0, **name): 

184 '''(INTERNAL) Return an C{Fsum} from a single partial C{p}. 

185 ''' 

186 f = Fsum(**name) if name else Fsum() 

187 f._ps[:] = p, 

188 f._n = 1 # len(f._ps) 

189 return f 

190 

191 

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

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

194 ''' 

195 if isinstance(other, Fsum): 

196 s, r = other._fint2 

197 if r: 

198 s, r = other._fprs2 

199 if r: # PYCHOK no cover 

200 if _raiser and _raiser(r, s): 

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

202 raise ResidualError(t, txt=None) 

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

204 else: 

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

206 if isint(s, both=True): 

207 s = int(s) 

208 return s 

209 

210 

211def _strcomplex(s, *args): 

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

213 ''' 

214 c = _strcomplex.__name__[4:] 

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

216 t = unstr(pow, *args) 

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

218 

219 

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

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

222 ''' 

223 p = _stresidual.__name__[3:] 

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

225 for n, v in itemsorted(name_values): 

226 n = n.replace(_UNDER_, _SPACE_) 

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

228 t = _COMMASPACE_(t, p) 

229 return _SPACE_(prefix, t) 

230 

231 

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

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

234 ''' 

235 s = a + b 

236 if not _isfinite(s): 

237 u = unstr(_2sum, a, b) 

238 t = Fmt.PARENSPACED(_not_finite_, s) 

239 raise _OverflowError(u, txt=t) 

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

241 a, b = b, a 

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

243 

244 

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

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

247 

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

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

250 intermediate, I{running} summuation. 

251 

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

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

254 

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

256 Python's C{math.fsum}. 

257 

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

259 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}, U{Kahan 

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

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

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

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

264 ''' 

265 _math_fsum = None 

266 _n = 0 

267# _ps = [] # partial sums 

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

269 _ratio = None 

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

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

272 

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

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

275 

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

277 or an L{Fsum} instance). 

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

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

280 

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

282 ''' 

283 if name_RESIDUAL: 

284 n = _xkwds_get(name_RESIDUAL, name=NN) 

285 if n: # set name before ... 

286 self.name = n 

287 r = _xkwds_get(name_RESIDUAL, RESIDUAL=None) 

288 if r is not None: 

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

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

291 if xs: 

292 self._facc_any(xs, origin=1, up=False) 

293 

294 def __abs__(self): 

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

296 ''' 

297 s = _fsum(self._ps_1()) # == self._cmp_0(0, ...) 

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

299 

300 def __add__(self, other): 

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

302 

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

304 

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

306 

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

308 ''' 

309 f = self._copy_2(self.__add__) 

310 return f._fadd(other, _add_op_) 

311 

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

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

314 ''' 

315 s, r = self._fprs2 

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

317 

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

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

320 

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

322 

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

324 ''' 

325 return self.ceil 

326 

327 def __cmp__(self, other): # Python 2- 

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

329 

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

331 

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

333 ''' 

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

335 return _signOf(s, 0) 

336 

337 cmp = __cmp__ 

338 

339 def __divmod__(self, other): 

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

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

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

343 

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

345 

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

347 ''' 

348 f = self._copy_2(self.__divmod__) 

349 return f._fdivmod2(other, _divmod_op_) 

350 

351 def __eq__(self, other): 

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

353 ''' 

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

355 

356 def __float__(self): 

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

358 

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

360 ''' 

361 return float(self._fprs) 

362 

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

364 '''Return this instance' C{math.floor} 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.__ceil__} and property L{Fsum.floor}. 

369 ''' 

370 return self.floor 

371 

372 def __floordiv__(self, other): 

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

374 

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

376 

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

378 

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

380 ''' 

381 f = self._copy_2(self.__floordiv__) 

382 return f._floordiv(other, _floordiv_op_) 

383 

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

385 '''Not implemented.''' 

386 return _NotImplemented(self, *other) 

387 

388 def __ge__(self, other): 

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

390 ''' 

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

392 

393 def __gt__(self, other): 

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

395 ''' 

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

397 

398 def __hash__(self): # PYCHOK no cover 

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

400 ''' 

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

402 

403 def __iadd__(self, other): 

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

405 

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

407 

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

409 

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

411 C{scalar} nor L{Fsum}. 

412 

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

414 ''' 

415 return self._fadd(other, _iadd_op_) 

416 

417 def __ifloordiv__(self, other): 

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

419 

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

421 

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

423 

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

425 

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

427 

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

429 

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

431 

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

433 ''' 

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

435 

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

437 '''Not implemented.''' 

438 return _NotImplemented(self, other) 

439 

440 def __imod__(self, other): 

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

442 

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

444 

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

446 

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

448 ''' 

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

450 

451 def __imul__(self, other): 

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

453 

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

455 

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

457 

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

459 

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

461 

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

463 ''' 

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

465 

466 def __int__(self): 

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

468 

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

470 and L{Fsum.__floor__} and properties 

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

472 ''' 

473 i, _ = self._fint2 

474 return i 

475 

476 def __invert__(self): # PYCHOK no cover 

477 '''Not implemented.''' 

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

479 return _NotImplemented(self) 

480 

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

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

483 

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

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

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

487 version. 

488 

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

490 

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

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

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

494 

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

496 

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

498 env var C{PYGEODESY_FSUM_RESIDUAL} 

499 set or this instance has a non-zero 

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

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

502 is a negative or fractional C{scalar}. 

503 

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

505 C{pow} invocation failed. 

506 

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

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

509 is a fractional C{scalar} and this 

510 instance is negative or has a non-zero 

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

512 

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

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

515 ''' 

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

517 

518 def __isub__(self, other): 

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

520 

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

522 

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

524 

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

526 

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

528 ''' 

529 return self._fsub(other, _isub_op_) 

530 

531 def __iter__(self): 

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

533 ''' 

534 return iter(self.partials) 

535 

536 def __itruediv__(self, other): 

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

538 

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

540 

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

542 

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

544 

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

546 env var C{PYGEODESY_FSUM_RESIDUAL} set. 

547 

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

549 

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

551 

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

553 

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

555 ''' 

556 return self._ftruediv(other, _truediv_op_ + _fset_op_) 

557 

558 def __le__(self, other): 

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

560 ''' 

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

562 

563 def __len__(self): 

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

565 ''' 

566 return self._n 

567 

568 def __lt__(self, other): 

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

570 ''' 

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

572 

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

574 '''Not implemented.''' 

575 return _NotImplemented(self, other) 

576 

577 def __mod__(self, other): 

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

579 

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

581 ''' 

582 f = self._copy_2(self.__mod__) 

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

584 

585 def __mul__(self, other): 

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

587 

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

589 ''' 

590 f = self._copy_2(self.__mul__) 

591 return f._fmul(other, _mul_op_) 

592 

593 def __ne__(self, other): 

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

595 ''' 

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

597 

598 def __neg__(self): 

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

600 ''' 

601 f = self._copy_2(self.__neg__) 

602 return f._fset(self._neg) 

603 

604 def __pos__(self): 

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

606 ''' 

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

608 

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

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

611 

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

613 ''' 

614 f = self._copy_2(self.__pow__) 

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

616 

617 def __radd__(self, other): 

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

619 

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

621 ''' 

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

623 return f._fadd(self, _add_op_) 

624 

625 def __rdivmod__(self, other): 

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

627 remainder)}. 

628 

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

630 ''' 

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

632 return f._fdivmod2(self, _divmod_op_) 

633 

634# def __repr__(self): 

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

636# ''' 

637# return self.toRepr(lenc=True) 

638 

639 def __rfloordiv__(self, other): 

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

641 

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

643 ''' 

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

645 return f._floordiv(self, _floordiv_op_) 

646 

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

648 '''Not implemented.''' 

649 return _NotImplemented(self, other) 

650 

651 def __rmod__(self, other): 

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

653 

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

655 ''' 

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

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

658 

659 def __rmul__(self, other): 

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

661 

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

663 ''' 

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

665 return f._fmul(self, _mul_op_) 

666 

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

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

669 

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

671 ''' 

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

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

674 name=self.__round__.__name__) 

675 

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

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

678 

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

680 ''' 

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

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

683 

684 def __rsub__(self, other): 

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

686 

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

688 ''' 

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

690 return f._fsub(self, _sub_op_) 

691 

692 def __rtruediv__(self, other): 

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

694 

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

696 ''' 

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

698 return f._ftruediv(self, _truediv_op_) 

699 

700 def __str__(self): 

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

702 ''' 

703 return self.toStr(lenc=True) 

704 

705 def __sub__(self, other): 

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

707 

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

709 

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

711 

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

713 ''' 

714 f = self._copy_2(self.__sub__) 

715 return f._fsub(other, _sub_op_) 

716 

717 def __truediv__(self, other): 

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

719 

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

721 

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

723 

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

725 ''' 

726 f = self._copy_2(self.__truediv__) 

727 return f._ftruediv(other, _truediv_op_) 

728 

729 __trunc__ = __int__ 

730 

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

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

733 __div__ = __truediv__ 

734 __idiv__ = __itruediv__ 

735 __long__ = __int__ 

736 __nonzero__ = __bool__ 

737 __rdiv__ = __rtruediv__ 

738 

739 def as_integer_ratio(self): 

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

741 

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

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

744 

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

746 ''' 

747 n, r = self._fint2 

748 if r: 

749 i, d = r.as_integer_ratio() 

750 n *= d 

751 n += i 

752 else: # PYCHOK no cover 

753 d = 1 

754 return n, d 

755 

756 @property_RO 

757 def ceil(self): 

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

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

760 

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

762 

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

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

765 ''' 

766 s, r = self._fprs2 

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

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

769 c += 1 

770 return c 

771 

772 def _cmp_0(self, other, op): 

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

774 ''' 

775 if isinstance(other, Fsum): 

776 s = _fsum(self._ps_1(*other._ps)) 

777 elif isscalar(other): 

778 if other: 

779 s = _fsum(self._ps_1(other)) 

780 else: 

781 s, r = self._fprs2 

782 s = _signOf(s, -r) 

783 else: 

784 raise self._TypeError(op, other) # txt=_invalid_ 

785 return s 

786 

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

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

789 

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

791 ''' 

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

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

794 f._n = self._n if deep else 1 

795 return f 

796 

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

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

799 ''' 

800 n = name or which.__name__ 

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

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

803 # assert f._n == self._n 

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

805 return f 

806 

807 def _copy_2r(self, other, which): 

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

809 ''' 

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

811 Fsum(other, name=which.__name__) 

812 

813# def _copy_RESIDUAL(self, other): 

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

815# ''' 

816# R = other._RESIDUAL 

817# if R is not Fsum._RESIDUAL: 

818# self._RESIDUAL = R 

819 

820 def divmod(self, other): 

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

822 remainder)}. 

823 

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

825 

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

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

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

829 

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

831 ''' 

832 f = self._copy_2(self.divmod) 

833 return f._fdivmod2(other, _divmod_op_) 

834 

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

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

837 ''' 

838 return Error(_SPACE_(self.toStr(), op, other), **txt_cause) 

839 

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

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

842 ''' 

843 E, t = _xError2(X) 

844 if mod: 

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

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

847 

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

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

850 ''' 

851 E, t = _xError2(X) 

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

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

854 

855 def _facc(self, xs, **up): 

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

857 ''' 

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

859 return self 

860 

861 def _facc_(self, *xs, **up): 

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

863 ''' 

864 if xs: 

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

866 return self 

867 

868 def _facc_any(self, xs, up=True, **origin_X_x): 

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

870 ''' 

871 self._ps[:] = self._ps_acc(list(self._ps), 

872 _2floats(xs, **origin_X_x), up=up) # PYCHOK yield 

873 return self 

874 

875 def _facc_any_neg(self, xs, up=True, **origin): 

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

877 ''' 

878 def _neg(x): 

879 return -x 

880 

881 self._ps[:] = self._ps_acc(list(self._ps), map(_neg, 

882 _2floats(xs, **origin)), up=up) # PYCHOK yield 

883 return self 

884 

885 def _facc_power(self, power, xs, which): # in .fmath 

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

887 ''' 

888 p = power 

889 if isinstance(p, Fsum): 

890 if p.is_exact: 

891 return self._facc_power(p._fprs, xs, which) 

892 _Pow = Fsum._pow_any 

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

894 _Pow, p = Fsum._pow_int, int(p) 

895 else: 

896 _Pow, p = Fsum._pow_scalar, _2float(power=p) 

897 

898 if p: 

899 from math import pow as _pow 

900 op = which.__name__ 

901 _Fs = Fsum 

902 

903 def _X(X): 

904 f = _Pow(X, p, power, op) 

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

906 

907 def _x(x): 

908 return _pow(float(x), p) 

909 

910 f = self._facc_any(xs, origin=1, _X=_X, _x=_x) 

911 else: 

912 f = self._facc_(float(len(xs))) # x**0 == 1 

913 return f 

914 

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

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

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

918# ''' 

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

920# p = self._ps.pop() 

921# if p: 

922# n = self._n 

923# self._facc_(p, up=False) 

924# self._n = n 

925# break 

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

927 

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

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

930 to this instance. 

931 

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

933 L{Fsum} instances). 

934 

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

936 

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

938 

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

940 nor L{Fsum}. 

941 

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

943 ''' 

944 if isinstance(xs, Fsum): 

945 self._facc(xs._ps) # tuple 

946 elif isscalar(xs): # for backward compatibility 

947 self._facc_(_2float(x=xs)) # PYCHOK no cover 

948 elif xs: 

949 self._facc_any(xs) 

950 return self 

951 

952 def fadd_(self, *xs): 

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

954 to this instance. 

955 

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

957 all positional. 

958 

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

960 

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

962 

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

964 nor L{Fsum}. 

965 

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

967 ''' 

968 return self._facc_any(xs, origin=1) 

969 

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

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

972 ''' 

973 if isinstance(other, Fsum): 

974 self._facc(other._ps, **up) # tuple 

975 elif not isscalar(other): 

976 raise self._TypeError(op, other) # txt=_invalid_ 

977 elif other: 

978 self._facc_(other, **up) 

979 return self 

980 

981 fcopy = copy # for backward compatibility 

982 fdiv = __itruediv__ # for backward compatibility 

983 fdivmod = __divmod__ # for backward compatibility 

984 

985 def _fdivmod2(self, other, op): 

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

987 ''' 

988 # result mostly follows CPython function U{float_divmod 

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

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

991 q = self._copy_2(self._fdivmod2)._ftruediv(other, op).floor 

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

993 self -= other * q 

994 

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

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

997 self += other 

998 q -= 1 

999# t = self.signOf() 

1000# if t and t != s: 

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

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

1003 

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

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

1006 ''' 

1007 if _isfinite(other): 

1008 return other 

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

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

1011 

1012 def fint(self, raiser=True, **name): 

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

1014 

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

1016 I{integer} residual is non-zero (C{bool}). 

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

1018 

1019 @return: The C{integer} (L{Fsum}). 

1020 

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

1022 

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

1024 ''' 

1025 i, r = self._fint2 

1026 if r and raiser: 

1027 t = _stresidual(_integer_, r) 

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

1029 f = self._copy_2(self.fint, **name) 

1030 return f._fset(i) 

1031 

1032 def fint2(self, **name): 

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

1034 the I{integer} residual. 

1035 

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

1037 

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

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

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

1041 ''' 

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

1043 

1044 @Property_RO 

1045 def _fint2(self): # see ._fset 

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

1047 ''' 

1048 s, r = self._fprs2 

1049 i = int(s) 

1050 r = _fsum(self._ps_1(i)) if r else float(s - i) 

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

1052 

1053 @deprecated_property_RO 

1054 def float_int(self): # PYCHOK no cover 

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

1056 return self.int_float() # raiser=False 

1057 

1058 @property_RO 

1059 def floor(self): 

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

1061 C{float} in Python 2-). 

1062 

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

1064 

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

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

1067 ''' 

1068 s, r = self._fprs2 

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

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

1071 f -= 1 

1072 return f 

1073 

1074# floordiv = __floordiv__ # for naming consistency 

1075 

1076 def _floordiv(self, other, op): # rather _ffloordiv? 

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

1078 ''' 

1079 q = self._ftruediv(other, op) # == self 

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

1081 

1082 fmul = __imul__ # for backward compatibility 

1083 

1084 def _fmul(self, other, op): 

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

1086 ''' 

1087 if isinstance(other, Fsum): 

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

1089 f = self._mul_Fsum(other, op) 

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

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

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

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

1094 elif isscalar(other): 

1095 f = self._mul_scalar(other, op) if other != _1_0 else self 

1096 else: 

1097 raise self._TypeError(op, other) # txt=_invalid_ 

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

1099 

1100 def fover(self, over): 

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

1102 

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

1104 

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

1106 

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

1108 ''' 

1109 return float(self.fdiv(over)._fprs) 

1110 

1111 fpow = __ipow__ # for backward compatibility 

1112 

1113 def _fpow(self, other, op, *mod): 

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

1115 ''' 

1116 if mod: 

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

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

1119 elif self.is_integer(): 

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

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

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

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

1124 _Psum_1(i)._pow_any(x, other, op) 

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

1126 f = self._pow_any(other, other, op) 

1127 else: # pow(self, other) == pow(self, other, None) 

1128 f = self._pow_any(other, other, op) 

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

1130 

1131 @Property_RO 

1132 def _fprs(self): 

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

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

1135 

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

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

1138 ''' 

1139 return self._fprs2.fsum 

1140 

1141 @Property_RO 

1142 def _fprs2(self): 

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

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

1145 ''' 

1146 ps = self._ps 

1147 n = len(ps) - 2 

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

1149 s = _psum(ps) 

1150 n = len(ps) - 2 

1151 if n > 0: 

1152 r = _fsum(self._ps_1(s)) or INT0 

1153 return Fsum2Tuple(s, r) 

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

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

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

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

1158 s, r = ps[0], INT0 

1159 else: # len(ps) == 0 

1160 s, r = _0_0, INT0 

1161 ps[:] = s, 

1162 # assert self._ps is ps 

1163 return Fsum2Tuple(s, r) 

1164 

1165# def _fpsqz(self): 

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

1167# ''' 

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

1169# _ = self._fprs2 

1170# return self 

1171 

1172 def fset_(self, *xs): 

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

1174 

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

1176 instances), all positional. 

1177 

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

1179 

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

1181 ''' 

1182 self._ps[:] = 0, 

1183 self._n = 0 

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

1185 

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

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

1188 ''' 

1189 if other is self: 

1190 pass # from ._fmul, ._ftruediv and ._pow_scalar 

1191 elif isinstance(other, Fsum): 

1192 self._ps[:] = other._ps 

1193 self._n = n or other._n 

1194# self._copy_RESIDUAL(other) 

1195 # use or zap the C{Property_RO} values 

1196 Fsum._fint2._update_from(self, other) 

1197 Fsum._fprs ._update_from(self, other) 

1198 Fsum._fprs2._update_from(self, other) 

1199 elif isscalar(other): 

1200 s = other if asis else float(other) 

1201 i = int(s) # see ._fint2 

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

1203 self._ps[:] = s, 

1204 self._n = n or 1 

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

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

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

1208 else: # PYCHOK no cover 

1209 raise self._TypeError(_fset_op_, other) # txt=_invalid_ 

1210 return self 

1211 

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

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

1214 ''' 

1215 if isinstance(other, Fsum): 

1216 self._ps[:] = other._ps 

1217 self._n = n or other._n 

1218 else: # assert isscalar(other) 

1219 self._ps[:] = other, 

1220 self._n = n or 1 

1221 return self 

1222 

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

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

1225 this instance. 

1226 

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

1228 instances). 

1229 

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

1231 

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

1233 ''' 

1234 return self._facc_any_neg(xs) if xs else self 

1235 

1236 def fsub_(self, *xs): 

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

1238 this instance. 

1239 

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

1241 all positional. 

1242 

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

1244 

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

1246 ''' 

1247 return self._facc_any_neg(xs, origin=1) if xs else self 

1248 

1249 def _fsub(self, other, op): 

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

1251 ''' 

1252 if isinstance(other, Fsum): 

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

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

1255 elif other._ps: 

1256 self._facc(other._ps_neg) 

1257 elif not isscalar(other): 

1258 raise self._TypeError(op, other) # txt=_invalid_ 

1259 elif self._finite(other, op): 

1260 self._facc_(-other) 

1261 return self 

1262 

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

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

1265 

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

1267 L{Fsum} instances). 

1268 

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

1270 

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

1272 

1273 @note: Accumulation can continue after summation. 

1274 ''' 

1275 f = self._facc_any(xs) if xs else self 

1276 return f._fprs 

1277 

1278 def fsum_(self, *xs): 

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

1280 

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

1282 positional. 

1283 

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

1285 

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

1287 ''' 

1288 f = self._facc_any(xs, origin=1) if xs else self 

1289 return f._fprs 

1290 

1291 def Fsum_(self, *xs): 

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

1293 

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

1295 ''' 

1296 return self._facc_any(xs, origin=1)._copy_2(self.Fsum_) 

1297 

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

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

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

1301 

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

1303 instances). 

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

1305 

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

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

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

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

1310 to be I{exact}. 

1311 

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

1313 ''' 

1314 f = self._facc_any(xs) if xs else self 

1315 t = f._fprs2 

1316 if name: 

1317 t = t.dup(name=name) 

1318 return t 

1319 

1320 def fsum2_(self, *xs): 

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

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

1323 

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

1325 positional. 

1326 

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

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

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

1330 

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

1332 ''' 

1333 return self._fsum2f_any(xs, self._facc_any, origin=1) 

1334 

1335 def fsumf_(self, *xs): 

1336 '''Like method L{Fsum.fsum_} but only for I{known} C{float B{xs}}. 

1337 ''' 

1338 f = self._facc(xs) if xs else self 

1339 return f._fprs 

1340 

1341 def Fsumf_(self, *xs): 

1342 '''Like method L{Fsum.Fsum_} but only for I{known} C{float B{xs}}. 

1343 ''' 

1344 return self._facc(xs)._copy_2(self.Fsumf_) 

1345 

1346 def fsum2f_(self, *xs): 

1347 '''Like method L{Fsum.fsum2_} but only for I{known} C{float B{xs}}. 

1348 ''' 

1349 return self._fsum2f_any(xs, self._facc) 

1350 

1351 def _fsum2f_any(self, xs, _facc, **origin): 

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

1353 ''' 

1354 p, q = self._fprs2 

1355 if xs: 

1356 s, r = _facc(xs, **origin)._fprs2 

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

1358 else: 

1359 return p, _0_0 

1360 

1361# ftruediv = __itruediv__ # for naming consistency? 

1362 

1363 def _ftruediv(self, other, op): 

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

1365 ''' 

1366 n = _1_0 

1367 if isinstance(other, Fsum): 

1368 if other is self or other == self: 

1369 return self._fset(_1_0) # n=len(self) 

1370 d, r = other._fprs2 

1371 if r: 

1372 if d: 

1373 if self._raiser(r, d): 

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

1375 d, n = other.as_integer_ratio() 

1376 else: # PYCHOK no cover 

1377 d = r 

1378 elif isscalar(other): 

1379 d = other 

1380 else: # PYCHOK no cover 

1381 raise self._TypeError(op, other) # txt=_invalid_ 

1382 try: 

1383 s = 0 if isinf(d) else ( 

1384 d if isnan(d) else self._finite(n / d)) 

1385 except Exception as X: 

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

1387 f = self._mul_scalar(s, _mul_op_) # handles 0, NAN, etc. 

1388 return self._fset(f, asis=False) 

1389 

1390 @property_RO 

1391 def imag(self): 

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

1393 

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

1395 ''' 

1396 return _0_0 

1397 

1398 def int_float(self, raiser=False): 

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

1400 

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

1402 residual is non-zero. 

1403 

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

1405 otherwise return the C{float} sum if the residual 

1406 is zero or if C{B{raiser}=False}. 

1407 

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

1409 

1410 @see: Methods L{Fsum.fint} and L{Fsum.fint2}. 

1411 ''' 

1412 s, r = self._fint2 

1413 if r: 

1414 s, r = self._fprs2 

1415 if r and raiser: # PYCHOK no cover 

1416 t = _stresidual(_non_zero_, r) 

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

1418 s = float(s) # redundant 

1419 return s 

1420 

1421 def is_exact(self): 

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

1423 ''' 

1424 return self.residual is INT0 

1425 

1426 def is_integer(self): 

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

1428 

1429 @see: Methods L{Fsum.fint} and L{Fsum.fint2}. 

1430 ''' 

1431 _, r = self._fint2 

1432 return False if r else True 

1433 

1434 def is_math_fsum(self): 

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

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

1437 C{math.fsum} or not. 

1438 

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

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

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

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

1443 none are. 

1444 ''' 

1445 f = Fsum._math_fsum 

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

1447 

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

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

1450 ''' 

1451 # assert isinstance(other, Fsum) 

1452 if self._ps and other._ps: 

1453 f = self._ps_mul(op, *other._ps) # NO ._2scalar 

1454 else: 

1455 f = _0_0 

1456 return f 

1457 

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

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

1460 ''' 

1461 # assert isscalar(factor) 

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

1463 f = self if factor == _1_0 else ( 

1464 self._neg if factor == _N_1_0 else 

1465 self._ps_mul(op, factor)._2scalar) 

1466 else: 

1467 f = _0_0 

1468 return f 

1469 

1470 @property_RO 

1471 def _neg(self): 

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

1473 ''' 

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

1475 

1476 @property_RO 

1477 def partials(self): 

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

1479 ''' 

1480 return tuple(self._ps) 

1481 

1482 def pow(self, x, *mod): 

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

1484 

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

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

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

1488 

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

1490 result (L{Fsum}). 

1491 

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

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

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

1495 

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

1497 ''' 

1498 f = self._copy_2(self.pow) 

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

1500 

1501 def _pow_0_1(self, x, other): 

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

1503 ''' 

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

1505 

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

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

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

1509 ''' 

1510 try: 

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

1512 m = mod[0] 

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

1514 if r and self._raiser(r, b): 

1515 t = _non_zero_ if m is None else _integer_ 

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

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

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

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

1520 if iscomplex(s): 

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

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

1523 return self._finite(s) 

1524 except Exception as X: 

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

1526 

1527 def _pow_any(self, other, unused, op): 

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

1529 ''' 

1530 if isinstance(other, Fsum): 

1531 x, r = other._fprs2 

1532 if r and self._raiser(r, x): 

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

1534 f = self._pow_scalar(x, other, op) 

1535 if r: 

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

1537 elif isscalar(other): 

1538 x = self._finite(other, op) 

1539 f = self._pow_scalar(x, other, op) 

1540 else: 

1541 raise self._TypeError(op, other) # txt=_invalid_ 

1542 return f 

1543 

1544 def _pow_int(self, x, other, op): 

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

1546 ''' 

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

1548 ps = self._ps 

1549 if len(ps) > 1: 

1550 _mul_Fsum = Fsum._mul_Fsum 

1551 if x > 4: 

1552 p = self 

1553 f = self if (x & 1) else _Psum_1() 

1554 m = x >> 1 # // 2 

1555 while m: 

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

1557 if (m & 1): 

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

1559 m >>= 1 # //= 2 

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

1561 f = _mul_Fsum(self, self, op) 

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

1563 p = self if x < 4 else f 

1564 f = _mul_Fsum(f, p, op)._2scalar 

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

1566 f = self._pow_0_1(x, other) 

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

1568 f = self._pow_2_3(ps[0], x, other, op) 

1569 else: # PYCHOK no cover 

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

1571 f = 0 if x else 1 

1572 return f 

1573 

1574 def _pow_scalar(self, x, other, op): 

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

1576 ''' 

1577 s, r = self._fprs2 

1578 if isint(x, both=True): 

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

1580 y = abs(x) 

1581 if y > 1: 

1582 if r: 

1583 f = self._pow_int(y, other, op) 

1584 if x > 0: # > 1 

1585 return f 

1586 # assert x < 0 # < -1 

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

1588 if r: 

1589 return _Psum_1()._ftruediv(f, op) 

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

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

1592 x = -1 

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

1594 if r: 

1595 return _Psum_1()._ftruediv(self, op) 

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

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

1598 elif not isscalar(x): # assert ... 

1599 raise self._TypeError(op, other, txt=_not_scalar_) 

1600 elif r and self._raiser(r, s): # non-zero residual**fractional 

1601 # raise self._ResidualError(op, other, r, fractional_power=x) 

1602 t = _stresidual(_non_zero_, r, fractional_power=x) 

1603 raise self._Error(op, other, ResidualError, txt=t) 

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

1605 return self._pow_2_3(s, x, other, op) 

1606 

1607 def _ps_1(self, *less): 

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

1609 ''' 

1610 yield _1_0 

1611 for p in self._ps: 

1612 yield p 

1613 for p in less: 

1614 yield -p 

1615 yield _N_1_0 

1616 

1617 def _ps_acc(self, ps, xs, up=True): 

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

1619 ''' 

1620 n = 0 

1621 _2s = _2sum 

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

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

1624 if x: 

1625 i = 0 

1626 for p in ps: 

1627 x, p = _2s(x, p) 

1628 if p: 

1629 ps[i] = p 

1630 i += 1 

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

1632 n += 1 

1633 if n: 

1634 self._n += n 

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

1636 if up: 

1637 self._update() 

1638 return ps 

1639 

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

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

1642 each of the B{C{factors}}, all known to be scalar. 

1643 ''' 

1644 def _pfs(ps, fs): 

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

1646 ps, fs = fs, ps 

1647 _fin = _isfinite 

1648 for f in fs: 

1649 for p in ps: 

1650 p *= f 

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

1652 

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

1654 

1655 @property_RO 

1656 def _ps_neg(self): 

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

1658 ''' 

1659 for p in self._ps: 

1660 yield -p 

1661 

1662 def _raiser(self, r, s): 

1663 '''(INTERNAL) Does ratio C{r / s} exceed threshold? 

1664 ''' 

1665 self._ratio = t = fabs((r / s) if s else r) 

1666 return t > self._RESIDUAL 

1667 

1668 @property_RO 

1669 def real(self): 

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

1671 

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

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

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

1675 ''' 

1676 return float(self._fprs) 

1677 

1678 @property_RO 

1679 def residual(self): 

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

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

1682 

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

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

1685 

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

1687 ''' 

1688 return self._fprs2.residual 

1689 

1690 def RESIDUAL(self, *threshold): 

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

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

1693 

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

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

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

1697 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

1698 current setting. 

1699 

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

1701 

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

1703 

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

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

1706 ''' 

1707 r = self._RESIDUAL 

1708 if threshold: 

1709 t = threshold[0] 

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

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

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

1713 if t < 0: 

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

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

1716 self._RESIDUAL = t 

1717 return r 

1718 

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

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

1721 ''' 

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

1723 RESIDUAL=self._RESIDUAL) 

1724 t = t.replace(_COMMASPACE_R_, _exceeds_R_) 

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

1726 

1727 @property_RO 

1728 def _2scalar(self): 

1729 '''(INTERNAL) Get this instance as C{scalar} or C{as-is}. 

1730 ''' 

1731 s, r = self._fprs2 

1732 return self if r else s 

1733 

1734 def signOf(self, res=True): 

1735 '''Determine the sign of this instance. 

1736 

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

1738 ignore the residual (C{bool}). 

1739 

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

1741 ''' 

1742 s, r = self._fprs2 

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

1744 

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

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

1747 

1748 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1752 

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

1754 ''' 

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

1756 

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

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

1759 

1760 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1764 

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

1766 ''' 

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

1768 

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

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

1771 ''' 

1772 n = self.named3 

1773 if lenc: 

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

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

1776 

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

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

1779 ''' 

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

1781 

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

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

1784 ''' 

1785 if updated: 

1786 _pop = self.__dict__.pop 

1787 for p in _ROs: 

1788 _ = _pop(p, None) 

1789# Fsum._fint2._update(self) 

1790# Fsum._fprs ._update(self) 

1791# Fsum._fprs2._update(self) 

1792 return self # for .fset_ 

1793 

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

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

1796 ''' 

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

1798 

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

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

1801 ''' 

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

1803 

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

1805 

1806 

1807def _Float_Int(arg, **name_Error): 

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

1809 ''' 

1810 U = Int if isint(arg) else Float 

1811 return U(arg, **name_Error) 

1812 

1813 

1814class DivMod2Tuple(_NamedTuple): 

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

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

1817 

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

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

1820 ''' 

1821 _Names_ = (_div_, _mod_) 

1822 _Units_ = (_Float_Int, Fsum) 

1823 

1824 

1825class Fsum2Tuple(_NamedTuple): 

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

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

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

1829 

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

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

1832 ''' 

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

1834 _Units_ = (_Float_Int, _Float_Int) 

1835 

1836 @Property_RO 

1837 def _Fsum(self): 

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

1839 ''' 

1840 s, r = map(float, self) 

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

1842 

1843 def is_exact(self): 

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

1845 ''' 

1846 return self._Fsum.is_exact() 

1847 

1848 def is_integer(self): 

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

1850 ''' 

1851 return self._Fsum.is_integer() 

1852 

1853 

1854class ResidualError(_ValueError): 

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

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

1857 

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

1859 ''' 

1860 pass 

1861 

1862 

1863try: 

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

1865 

1866 # make sure _fsum works as expected (XXX check 

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

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

1869 del _fsum # nope, remove _fsum ... 

1870 raise ImportError # ... use _fsum below 

1871 

1872 Fsum._math_fsum = _sum = _fsum # PYCHOK exported 

1873 

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

1875 _psum = _fsum # PYCHOK re-def 

1876 

1877except ImportError: 

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

1879 

1880 def _fsum(xs): 

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

1882 ''' 

1883 f = Fsum() 

1884 f.name = _fsum.__name__ 

1885 return f.fsum(xs) 

1886 

1887 

1888def fsum(xs, floats=False): 

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

1890 

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

1892 instances). 

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

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

1895 

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

1897 

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

1899 

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

1901 

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

1903 

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

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

1906 

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

1908 ''' 

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

1910 

1911 

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

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

1914 

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

1916 positional. 

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

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

1919 

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

1921 

1922 @see: Function C{fsum}. 

1923 ''' 

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

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

1926 

1927 

1928def fsumf_(*xs): 

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

1930 ''' 

1931 return _fsum(xs) if xs else _0_0 

1932 

1933 

1934def fsum1(xs, floats=False): 

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

1936 

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

1938 instances). 

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

1940 to be C{float}. 

1941 

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

1943 

1944 @see: Function C{fsum}. 

1945 ''' 

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

1947 

1948 

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

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

1951 

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

1953 positional. 

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

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

1956 

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

1958 

1959 @see: Function C{fsum} 

1960 ''' 

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

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

1963 

1964 

1965def fsum1f_(*xs): 

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

1967 ''' 

1968 return _fsum(_1primed(xs)) if xs else _0_0 

1969 

1970 

1971if __name__ == '__main__': 

1972 

1973 # usage: [env PYGEODESY_FSUM_PARTIALS=fsum] python3 -m pygeodesy.fsums 

1974 

1975 def _test(n): 

1976 # copied from Hettinger, see L{Fsum} reference 

1977 from pygeodesy import printf 

1978 from random import gauss, random, shuffle 

1979 

1980 printf(_fsum.__name__, end=_COMMASPACE_) 

1981 printf(_psum.__name__, end=_COMMASPACE_) 

1982 

1983 F = Fsum() 

1984 if F.is_math_fsum(): 

1985 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 10 

1986 for _ in range(n): 

1987 t = list(c) 

1988 s = 0 

1989 for _ in range(n * 8): 

1990 v = gauss(0, random())**7 - s 

1991 t.append(v) 

1992 s += v 

1993 shuffle(t) 

1994 assert float(F.fset_(*t)) == _fsum(t) 

1995 printf(_DOT_, end=NN) 

1996 printf(NN) 

1997 

1998 _test(128) 

1999 

2000# **) MIT License 

2001# 

2002# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved. 

2003# 

2004# Permission is hereby granted, free of charge, to any person obtaining a 

2005# copy of this software and associated documentation files (the "Software"), 

2006# to deal in the Software without restriction, including without limitation 

2007# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

2008# and/or sell copies of the Software, and to permit persons to whom the 

2009# Software is furnished to do so, subject to the following conditions: 

2010# 

2011# The above copyright notice and this permission notice shall be included 

2012# in all copies or substantial portions of the Software. 

2013# 

2014# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

2015# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

2016# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

2017# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

2018# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

2019# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

2020# OTHER DEALINGS IN THE SOFTWARE.