Coverage for pygeodesy/fsums.py: 95%

700 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-05-20 11:54 -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 an empty string (or anything 

18other than C{"fsum"}) for backward compatible summation of L{Fsum} partials. 

19 

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

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

22exponention of an L{Fsum} instance with a I{relative} C{residual} exceeding 

23the threshold, see methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__} 

24and L{Fsum.__itruediv__}. 

25''' 

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

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

28 

29from pygeodesy.basics import iscomplex, isint, isscalar, map1, signOf, _signOf 

30from pygeodesy.constants import INT0, _isfinite, isinf, isnan, \ 

31 _0_0, _1_0, _N_1_0 

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

33 _ValueError, _xError2, _xkwds_get, _xkwds_get_, \ 

34 _ZeroDivisionError 

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

36 _exceeds_, _from_, _iadd_, _LANGLE_, _negative_, \ 

37 _NOTEQUAL_, _not_finite_, _not_scalar_, \ 

38 _PERCENT_, _PLUS_, _R_, _RANGLE_, _SLASH_, \ 

39 _SPACE_, _STAR_, _UNDER_ 

40from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys, _sys_version_info2 

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

42from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \ 

43 Property_RO, property_RO 

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

45from pygeodesy.units import Float, Int 

46 

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

48 

49__all__ = _ALL_LAZY.fsums 

50__version__ = '23.05.18' 

51 

52_add_op_ = _PLUS_ 

53_eq_op_ = _EQUAL_ * 2 # _DEQUAL_ 

54_COMMASPACE_R_ = _COMMASPACE_ + _R_ 

55_exceeds_R_ = _SPACE_ + _exceeds_(_R_) 

56_floordiv_op_ = _SLASH_ * 2 # _DSLASH_ 

57_fset_op_ = _EQUAL_ 

58_ge_op_ = _RANGLE_ + _EQUAL_ 

59_gt_op_ = _RANGLE_ 

60_integer_ = 'integer' 

61_le_op_ = _LANGLE_ + _EQUAL_ 

62_lt_op_ = _LANGLE_ 

63_mod_op_ = _PERCENT_ 

64_mul_op_ = _STAR_ 

65_ne_op_ = _NOTEQUAL_ 

66_non_zero_ = 'non-zero' 

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

68_sub_op_ = _DASH_ 

69_truediv_op_ = _SLASH_ 

70_divmod_op_ = _floordiv_op_ + _mod_op_ 

71 

72_pos_self = _1_0.__pos__() is _1_0 # in .vector3dBase 

73 

74 

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

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

77 ''' 

78 n, v = name_value.popitem() # _xkwds_popitem(name_value) 

79 try: 

80 v = float(v) 

81 if _isfinite(v): 

82 return v 

83 E, t = _ValueError, _not_finite_ 

84 except Exception as e: 

85 E, t = _xError2(e) 

86 if index is not None: 

87 n = Fmt.SQUARE(n, index) 

88 raise E(n, v, txt=t) 

89 

90 

91def _2floats(xs, origin=0, sub=False): 

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

93 ''' 

94 try: 

95 i, x = origin, None 

96 _fin = _isfinite 

97 _Fsum = Fsum 

98 for x in xs: 

99 if isinstance(x, _Fsum): 

100 for p in x._ps: 

101 yield (-p) if sub else p 

102 else: 

103 f = float(x) 

104 if not _fin(f): 

105 raise ValueError(_not_finite_) 

106 if f: 

107 yield (-f) if sub else f 

108 i += 1 

109 except Exception as e: 

110 E, t = _xError2(e) 

111 n = Fmt.SQUARE(xs=i) 

112 raise E(n, x, txt=t) 

113 

114 

115def _Powers(power, xs, origin=1): # in .fmath 

116 '''(INTERNAL) Yield each C{xs} as C{float(x**power)}. 

117 ''' 

118 if not isscalar(power): 

119 raise _TypeError(power=power) 

120 try: 

121 i, x = origin, None 

122 _fin = _isfinite 

123 _Fsum = Fsum 

124 _pow = pow # XXX math.pow 

125 for x in xs: 

126 if isinstance(x, _Fsum): 

127 P = x.pow(power) 

128 for p in P._ps: 

129 yield p 

130 else: 

131 p = _pow(float(x), power) 

132 if not _fin(p): 

133 raise ValueError(_not_finite_) 

134 yield p 

135 i += 1 

136 except Exception as e: 

137 E, t = _xError2(e) 

138 n = Fmt.SQUARE(xs=i) 

139 raise E(n, x, txt=t) 

140 

141 

142def _1primed(xs): 

143 '''(INTERNAL) 1-Prime the summation of C{xs} 

144 arguments I{known} to be C{finite float}. 

145 ''' 

146 yield _1_0 

147 for x in xs: 

148 if x: 

149 yield x 

150 yield _N_1_0 

151 

152 

153def _psum(ps): # PYCHOK used! 

154 '''(INTERNAL) Partials summation updating C{ps}, I{overridden below}. 

155 ''' 

156 i = len(ps) - 1 # len(ps) > 2 

157 s = 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 ps[i:] = [s, r] if s else [r] 

164 if i > 0: 

165 p = ps[i-1] # round half-even 

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

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

168 r *= 2 

169 t = s + r 

170 if r == (t - s): 

171 s = t 

172 break 

173 ps[i:] = [s] 

174 return s 

175 

176 

177def _2scalar(other, _raiser=None): 

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

179 ''' 

180 if isinstance(other, Fsum): 

181 s, r = other._fint2 

182 if r: 

183 s, r = other._fprs2 

184 if r: # PYCHOK no cover 

185 if _raiser and _raiser(r, s): 

186 raise ValueError(_stresidual(_non_zero_, r)) 

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

188 else: 

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

190 if isint(s, both=True): 

191 s = int(s) 

192 return s 

193 

194 

195def _strcomplex(s, *args): 

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

197 ''' 

198 c = iscomplex.__name__[2:] 

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

200 t = _SPACE_(c, s, _from_, n, pow.__name__) 

201 return unstr(t, *args) 

202 

203 

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

205 '''(INTERNAL) Residual error C{str}. 

206 ''' 

207 p = _SPACE_(prefix, Fsum.residual.name) 

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

209 for n, v in itemsorted(name_values): 

210 n = n.replace(_UNDER_, _SPACE_) 

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

212 t = _COMMASPACE_(t, p) 

213 return t 

214 

215 

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

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

218 ''' 

219 s = a + b 

220 if not _isfinite(s): 

221 u = unstr(_2sum.__name__, a, b) 

222 t = Fmt.PARENSPACED(_not_finite_, s) 

223 raise _OverflowError(u, txt=t) 

224 r = (a - (s - b)) if fabs(a) < fabs(b) else \ 

225 (b - (s - a)) # fabs(a) >= fabs(b) 

226 return s, r 

227 

228 

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

230 '''Precision floating point I{running} summation. 

231 

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

233 I{running} precision floating point summation. Accumulation may continue after 

234 intermediate, I{running} summuation. 

235 

236 @note: Accumulated values may be L{Fsum} or C{scalar} instances with C{scalar} meaning 

237 type C{float}, C{int} or any C{type} convertible to a single C{float}, having 

238 method C{__float__}. 

239 

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

241 Python's C{math.fsum}. 

242 

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

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

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

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

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

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

249 ''' 

250 _math_fsum = None 

251 _n = 0 

252# _ps = [] # partial sums 

253# _px = 0 

254 _ratio = None 

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

256 

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

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

259 

260 @arg xs: No, one or more initial values (each C{scalar} or an 

261 L{Fsum} instance). 

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

263 (C{str}) and C{B{RESIDUAL}=None} for the 

264 L{ResidualError} threshold. 

265 

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

267 ''' 

268 if name_RESIDUAL: 

269 n, r = _xkwds_get_(name_RESIDUAL, name=NN, RESIDUAL=None) 

270 if n: # set name ... 

271 self.name = n 

272 if r is not None: 

273 self.RESIDUAL(r) # ... for ResidualError 

274# self._n = 0 

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

276 if len(xs) > 1: 

277 self._facc(_2floats(xs, origin=1), up=False) # PYCHOK yield 

278 elif xs: # len(xs) == 1 

279 self._ps = [_2float(x=xs[0])] 

280 self._n = 1 

281 

282 def __abs__(self): 

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

284 ''' 

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

286 return self._copy_n(self.__abs__) if s < 0 else \ 

287 self._copy_2(self.__abs__) 

288 

289 def __add__(self, other): 

290 '''Return the C{Fsum(B{self}, B{other})}. 

291 

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

293 

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

295 

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

297 ''' 

298 f = self._copy_2(self.__add__) 

299 return f._fadd(other, _add_op_) 

300 

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

302 '''Return C{True} if this instance is non-zero. 

303 ''' 

304 return self != 0 

305 

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

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

308 

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

310 

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

312 ''' 

313 return self.ceil 

314 

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

316 '''Compare this with an other instance or scalar. 

317 

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

319 

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

321 ''' 

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

323 return -1 if s < 0 else (+1 if s > 0 else 0) 

324 

325 cmp = __cmp__ 

326 

327 def __divmod__(self, other): 

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

329 remainder)}, an C{int} in Python 3+ or C{float} in Python 2- 

330 and an L{Fsum}. 

331 

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

333 

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

335 ''' 

336 f = self._copy_2(self.__divmod__) 

337 return f._fdivmod2(other, _divmod_op_) 

338 

339 def __eq__(self, other): 

340 '''Compare this with an other instance or scalar. 

341 ''' 

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

343 

344 def __float__(self): 

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

346 

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

348 ''' 

349 return float(self._fprs) 

350 

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

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

353 

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

355 

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

357 ''' 

358 return self.floor 

359 

360 def __floordiv__(self, other): 

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

362 

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

364 

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

366 

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

368 ''' 

369 f = self._copy_2(self.__floordiv__) 

370 return f._floordiv(other, _floordiv_op_) 

371 

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

373 '''Not implemented.''' 

374 return _NotImplemented(self, *other) 

375 

376 def __ge__(self, other): 

377 '''Compare this with an other instance or scalar. 

378 ''' 

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

380 

381 def __gt__(self, other): 

382 '''Compare this with an other instance or scalar. 

383 ''' 

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

385 

386 def __hash__(self): # PYCHOK no cover 

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

388 ''' 

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

390 

391 def __iadd__(self, other): 

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

393 

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

395 

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

397 

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

399 C{scalar} nor L{Fsum}. 

400 

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

402 ''' 

403 return self._fadd(other, _iadd_) 

404 

405 def __ifloordiv__(self, other): 

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

407 

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

409 

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

411 

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

413 

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

415 

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

417 

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

419 

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

421 ''' 

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

423 

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

425 '''Not implemented.''' 

426 return _NotImplemented(self, other) 

427 

428 def __imod__(self, other): 

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

430 

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

432 

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

434 

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

436 ''' 

437 self._fdivmod2(other, _mod_op_ + _fset_op_) 

438 return self 

439 

440 def __imul__(self, other): 

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

442 

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

444 

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

446 

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

448 

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

450 

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

452 ''' 

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

454 

455 def __int__(self): 

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

457 

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

459 and L{Fsum.__floor__} and properties 

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

461 ''' 

462 i, _ = self._fint2 

463 return i 

464 

465 def __invert__(self): # PYCHOK no cover 

466 '''Not implemented.''' 

467 # Luciano Ramalho, "Fluent Python", 2nd Ed, page 567, O'Reilly, 2022 

468 return _NotImplemented(self) 

469 

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

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

472 

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

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

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

476 version. 

477 

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

479 

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

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

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

483 

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

485 

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

487 env var C{PYGEODESY_FSUM_RESIDUAL} 

488 set or this instance has a non-zero 

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

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

491 is a negative or fractional C{scalar}. 

492 

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

494 C{pow} invocation failed. 

495 

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

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

498 is a fractional C{scalar} and this 

499 instance is negative or has a non-zero 

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

501 

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

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

504 ''' 

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

506 

507 def __isub__(self, other): 

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

509 

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

511 

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

513 

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

515 

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

517 ''' 

518 return self._fsub(other, _sub_op_ + _fset_op_) 

519 

520 def __iter__(self): 

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

522 ''' 

523 return iter(self.partials) 

524 

525 def __itruediv__(self, other): 

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

527 

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

529 

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

531 

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

533 

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

535 env var C{PYGEODESY_FSUM_RESIDUAL} set. 

536 

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

538 

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

540 

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

542 

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

544 ''' 

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

546 

547 def __le__(self, other): 

548 '''Compare this with an other instance or scalar. 

549 ''' 

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

551 

552 def __len__(self): 

553 '''Return the I{total} number accumulations (C{int}). 

554 ''' 

555 return self._n 

556 

557 def __lt__(self, other): 

558 '''Compare this with an other instance or scalar. 

559 ''' 

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

561 

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

563 '''Not implemented.''' 

564 return _NotImplemented(self, other) 

565 

566 def __mod__(self, other): 

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

568 

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

570 ''' 

571 f = self._copy_2(self.__mod__) 

572 return f._fdivmod2(other, _mod_op_)[1] 

573 

574 def __mul__(self, other): 

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

576 

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

578 ''' 

579 f = self._copy_2(self.__mul__) 

580 return f._fmul(other, _mul_op_) 

581 

582 def __ne__(self, other): 

583 '''Compare this with an other instance or scalar. 

584 ''' 

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

586 

587 def __neg__(self): 

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

589 ''' 

590 return self._copy_n(self.__neg__) 

591 

592 def __pos__(self): 

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

594 ''' 

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

596 

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

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

599 

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

601 ''' 

602 f = self._copy_2(self.__pow__) 

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

604 

605 def __radd__(self, other): 

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

607 

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

609 ''' 

610 f = self._copy_r2(other, self.__radd__) 

611 return f._fadd(self, _add_op_) 

612 

613 def __rdivmod__(self, other): 

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

615 remainder)}. 

616 

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

618 ''' 

619 f = self._copy_r2(other, self.__rdivmod__) 

620 return f._fdivmod2(self, _divmod_op_) 

621 

622# def __repr__(self): 

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

624# ''' 

625# return self.toRepr(lenc=True) 

626 

627 def __rfloordiv__(self, other): 

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

629 

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

631 ''' 

632 f = self._copy_r2(other, self.__rfloordiv__) 

633 return f._floordiv(self, _floordiv_op_) 

634 

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

636 '''Not implemented.''' 

637 return _NotImplemented(self, other) 

638 

639 def __rmod__(self, other): 

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

641 

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

643 ''' 

644 f = self._copy_r2(other, self.__rmod__) 

645 return f._fdivmod2(self, _mod_op_)[1] 

646 

647 def __rmul__(self, other): 

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

649 

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

651 ''' 

652 f = self._copy_r2(other, self.__rmul__) 

653 return f._fmul(self, _mul_op_) 

654 

655 def __round__(self, ndigits=None): # PYCHOK no cover 

656 '''Not implemented.''' 

657 return _NotImplemented(self, ndigits=ndigits) 

658 

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

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

661 

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

663 ''' 

664 f = self._copy_r2(other, self.__rpow__) 

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

666 

667 def __rsub__(self, other): 

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

669 

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

671 ''' 

672 f = self._copy_r2(other, self.__rsub__) 

673 return f._fsub(self, _sub_op_) 

674 

675 def __rtruediv__(self, other): 

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

677 

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

679 ''' 

680 f = self._copy_r2(other, self.__rtruediv__) 

681 return f._ftruediv(self, _truediv_op_) 

682 

683 def __sizeof__(self): # PYCHOK not special in Python 2- 

684 '''Return the current size of this instance in C{bytes}. 

685 ''' 

686 return sum(map1(_sys.getsizeof, self._fint2, 

687 self._fint2[0], 

688 self._fint2[1], 

689 self._fprs, 

690 self._fprs2, 

691 self._fprs2.fsum, 

692 self._fprs2.residual, 

693 self._n, 

694 self._ps, *self._ps)) 

695 

696 def __str__(self): 

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

698 ''' 

699 return self.toStr(lenc=True) 

700 

701 def __sub__(self, other): 

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

703 

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

705 

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

707 

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

709 ''' 

710 f = self._copy_2(self.__sub__) 

711 return f._fsub(other, _sub_op_) 

712 

713 def __truediv__(self, other): 

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

715 

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

717 

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

719 

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

721 ''' 

722 f = self._copy_2(self.__truediv__) 

723 return f._ftruediv(other, _truediv_op_) 

724 

725 __trunc__ = __int__ 

726 

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

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

729 __div__ = __truediv__ 

730 __idiv__ = __itruediv__ 

731 __long__ = __int__ 

732 __nonzero__ = __bool__ 

733 __rdiv__ = __rtruediv__ 

734 

735 def as_integer_ratio(self): 

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

737 

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

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

740 

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

742 ''' 

743 n, r = self._fint2 

744 if r: 

745 i, d = r.as_integer_ratio() 

746 n *= d 

747 n += i 

748 else: # PYCHOK no cover 

749 d = 1 

750 return n, d 

751 

752 @property_RO 

753 def ceil(self): 

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

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

756 

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

758 

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

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

761 ''' 

762 s, r = self._fprs2 

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

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

765 c += 1 

766 return c 

767 

768 def _cmp_0(self, other, op): 

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

770 ''' 

771 if isscalar(other): 

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

773 elif isinstance(other, Fsum): 

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

775 else: 

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

777 return s 

778 

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

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

781 

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

783 ''' 

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

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

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

787 return f 

788 

789 def _copy_0(self, *xs): 

790 '''(INTERNAL) Copy with/-out overriding C{partials}. 

791 ''' 

792 # for x in xs: 

793 # assert isscalar(x) 

794 f = self._Fsum(self._n + len(xs), *xs) 

795 if self.name: 

796 f._name = self.name # .rename calls _update_attrs 

797 return f 

798 

799 def _copy_2(self, which): 

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

801 ''' 

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

803 f = _Named.copy(self, deep=False, name=which.__name__) 

804 # assert f._n == self._n 

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

806 return f 

807 

808 def _copy_n(self, which): 

809 '''(INTERNAL) Negated copy for I{monadic} C{__abs__} and C{__neg__}. 

810 ''' 

811 if self._ps: 

812 f = self._Fsum(self._n) 

813 f._ps[:] = self._ps_n() 

814# f._facc_up(up=False) 

815 else: 

816 f = self._Fsum(self._n, _0_0) 

817 f._name = which.__name__ # .rename calls _update_attrs 

818 return f 

819 

820 def _copy_r2(self, other, which): 

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

822 ''' 

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

824 Fsum(other, name=which.__name__) # see ._copy_2 

825 

826 def _copy_RESIDUAL(self, other): 

827 '''(INTERNAL) Copy C{other._RESIDUAL}. 

828 ''' 

829 R = other._RESIDUAL 

830 if R is not Fsum._RESIDUAL: 

831 self._RESIDUAL = R 

832 

833 def _copy_up(self, _fprs2=False): 

834 '''(INTERNAL) Minimal, anonymous copy. 

835 ''' 

836 f = self._Fsum(self._n, *self._ps) 

837 if _fprs2: # only the ._fprs2 2-tuple 

838 Fsum._fprs2._update_from(f, self) 

839 return f 

840 

841 def divmod(self, other): 

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

843 remainder)}. 

844 

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

846 

847 @return: 2-Tuple C{(quotient, remainder)}, with the C{quotient} 

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

849 the C{remainder} an L{Fsum} instance. 

850 

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

852 ''' 

853 f = self._copy_2(self.divmod) 

854 return f._fdivmod2(other, _divmod_op_) 

855 

856 def _Error(self, op, other, Error, **txt): 

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

858 ''' 

859 return Error(_SPACE_(self.toRepr(), op, repr(other)), **txt) 

860 

861 def _ErrorX(self, X, xs, **kwds): # in .fmath 

862 '''(INTERNAL) Format a caught exception. 

863 ''' 

864 E, t = _xError2(X) 

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

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

867 

868 def _facc(self, xs, up=True): # from .elliptic._Defer.Fsum 

869 '''(INTERNAL) Accumulate more known C{scalar}s. 

870 ''' 

871 n, ps, _2s = 0, self._ps, _2sum 

872 for x in xs: # _iter() 

873 # assert isscalar(x) and isfinite(x) 

874 i = 0 

875 for p in ps: 

876 x, p = _2s(x, p) 

877 if p: 

878 ps[i] = p 

879 i += 1 

880 ps[i:] = [x] 

881 n += 1 

882 # assert self._ps is ps 

883 if n: 

884 self._n += n 

885 # Fsum._px = max(Fsum._px, len(ps)) 

886 if up: 

887 self._update() 

888 return self 

889 

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

891 '''(INTERNAL) Accumulate all positional C{scalar}s. 

892 ''' 

893 return self._facc(xs, **up) if xs else self 

894 

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

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

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

898# ''' 

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

900# p = self._ps.pop() 

901# if p: 

902# n = self._n 

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

904# self._n = n 

905# break 

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

907 

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

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

910 to this instance. 

911 

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

913 L{Fsum} instances). 

914 

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

916 

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

918 

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

920 nor L{Fsum}. 

921 

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

923 ''' 

924 if isinstance(xs, Fsum): 

925 self._facc(xs._ps) 

926 elif isscalar(xs): # for backward compatibility 

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

928 elif xs: 

929 self._facc(_2floats(xs)) # PYCHOK yield 

930 return self 

931 

932 def fadd_(self, *xs): 

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

934 to this instance. 

935 

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

937 all positional. 

938 

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

940 

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

942 

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

944 nor L{Fsum}. 

945 

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

947 ''' 

948 return self._facc(_2floats(xs, origin=1)) # PYCHOK yield 

949 

950 def _fadd(self, other, op): # in .fmath.Fhorner 

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

952 ''' 

953 if isinstance(other, Fsum): 

954 if other is self: 

955 self._facc_(*other._ps) # == ._facc(tuple(other._ps)) 

956 elif other._ps: 

957 self._facc(other._ps) 

958 elif not isscalar(other): 

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

960 elif other: 

961 self._facc_(other) 

962 return self 

963 

964 fcopy = copy # for backward compatibility 

965 fdiv = __itruediv__ # for backward compatibility 

966 fdivmod = __divmod__ # for backward compatibility 

967 

968 def _fdivmod2(self, other, op): 

969 '''(INTERNAL) C{divmod(B{self}, B{other})} as 2-tuple 

970 (C{int} or C{float}, remainder C{self}). 

971 ''' 

972 # result mostly follows CPython function U{float_divmod 

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

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

975 q = self._copy_up(_fprs2=True)._ftruediv(other, op).floor 

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

977 self -= other * q 

978 

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

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

981 self += other 

982 q -= 1 

983 

984# t = self.signOf() 

985# if t and t != s: 

986# from pygeodesy.errors import _AssertionError 

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

988 return q, self # q is C{int} in Python 3+, but C{float} in Python 2- 

989 

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

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

992 ''' 

993 if _isfinite(other): 

994 return other 

995 raise ValueError(_not_finite_) if not op else \ 

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

997 

998 def fint(self, raiser=True, name=NN): 

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

1000 

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

1002 I{integer} residual is non-zero. 

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

1004 

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

1006 

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

1008 

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

1010 ''' 

1011 i, r = self._fint2 

1012 if r and raiser: 

1013 t = _stresidual(_integer_, r) 

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

1015 n = name or self.fint.__name__ 

1016 return Fsum(name=n)._fset(i, asis=True) 

1017 

1018 def fint2(self, **name): 

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

1020 the I{integer} residual. 

1021 

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

1023 

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

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

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

1027 ''' 

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

1029 

1030 @Property_RO 

1031 def _fint2(self): # see ._fset 

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

1033 ''' 

1034 i = int(self._fprs) # int(self) 

1035 r = _fsum(self._ps_1(i)) if len(self._ps) > 1 else ( 

1036 (self._ps[0] - i) if self._ps else -i) 

1037 return i, (r or INT0) 

1038 

1039 @deprecated_property_RO 

1040 def float_int(self): # PYCHOK no cover 

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

1042 return self.int_float() # raiser=False 

1043 

1044 @property_RO 

1045 def floor(self): 

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

1047 C{float} in Python 2-). 

1048 

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

1050 

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

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

1053 ''' 

1054 s, r = self._fprs2 

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

1056 while r < (f - s): # (s + r) < f 

1057 f -= 1 

1058 return f 

1059 

1060# floordiv = __floordiv__ # for naming consistency 

1061 

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

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

1064 ''' 

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

1066 return self._fset(q.floor, asis=True) # floor(q) 

1067 

1068 fmul = __imul__ # for backward compatibility 

1069 

1070 def _fmul(self, other, op): 

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

1072 ''' 

1073 if isscalar(other): 

1074 f = self._mul_scalar(other, op) 

1075 elif not isinstance(other, Fsum): 

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

1077 elif len(self._ps) != 1: 

1078 f = self._mul_Fsum(other, op) 

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

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

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

1082 s = self._finite(self._ps[0] * other._ps[0]) 

1083 return self._fset(s, asis=True, n=len(self) + 1) 

1084 return self._fset(f) 

1085 

1086 def fover(self, over): 

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

1088 

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

1090 

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

1092 

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

1094 ''' 

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

1096 

1097 fpow = __ipow__ # for backward compatibility 

1098 

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

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

1101 ''' 

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

1103 s = self._pow_3(other, mod[0], op) 

1104 elif mod and mod[0] is None and self.is_integer(): 

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

1106 i = self._copy_0(self._fint2[0]) # assert _fint2[1] == 0 

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

1108 s = i._pow_2(x, other, op) if isscalar(x) else i._fpow(x, op) 

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

1110 p = None 

1111 if isinstance(other, Fsum): 

1112 x, r = other._fprs2 

1113 if r: 

1114 if self._raiser(r, x): 

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

1116 p = self._pow_scalar(r, other, op) 

1117# p = _2scalar(p) # _raiser = None 

1118 elif not isscalar(other): 

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

1120 else: 

1121 x = self._finite(other, op) 

1122 s = self._pow_scalar(x, other, op) 

1123 if p is not None: 

1124 s *= p 

1125 return self._fset(s, asis=isint(s), n=max(len(self), 1)) 

1126 

1127 @Property_RO 

1128 def _fprs(self): 

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

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

1131 

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

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

1134 ''' 

1135 ps = self._ps 

1136 n = len(ps) - 1 

1137 if n > 1: 

1138 s = _psum(ps) 

1139 elif n > 0: # len(ps) == 2 

1140 s, p = _2sum(*ps) if ps[1] else ps 

1141 ps[:] = ([p, s] if s else [p]) if p else [s] 

1142 elif n < 0: # see L{Fsum.__init__} 

1143 s = _0_0 

1144 ps[:] = [s] 

1145 else: # len(ps) == 1 

1146 s = ps[0] 

1147 # assert self._ps is ps 

1148 # assert Fsum._fprs2.name not in self.__dict__ 

1149 return s 

1150 

1151 @Property_RO 

1152 def _fprs2(self): 

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

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

1155 ''' 

1156 s = self._fprs 

1157 r = _fsum(self._ps_1(s)) if len(self._ps) > 1 else INT0 

1158 return Fsum2Tuple(s, r) # name=Fsum.fsum2.__name__ 

1159 

1160# def _fpsqz(self): 

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

1162# ''' 

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

1164# _ = self._fprs 

1165# return self 

1166 

1167 def _fset(self, other, asis=False, n=1): 

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

1169 ''' 

1170 if other is self: 

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

1172 elif isinstance(other, Fsum): 

1173 self._n = other._n 

1174 self._ps[:] = other._ps 

1175 self._copy_RESIDUAL(other) 

1176 # use or zap the C{Property_RO} values 

1177 Fsum._fint2._update_from(self, other) 

1178 Fsum._fprs ._update_from(self, other) 

1179 Fsum._fprs2._update_from(self, other) 

1180 elif isscalar(other): 

1181 s = other if asis else float(other) 

1182 i = int(s) # see ._fint2 

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

1184 self._n = n 

1185 self._ps[:] = [s] 

1186 # Property_RO _fint2, _fprs and _fprs2 can't be a Property: 

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

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

1189 else: # PYCHOK no cover 

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

1191 return self 

1192 

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

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

1195 from this instance. 

1196 

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

1198 or L{Fsum} instances). 

1199 

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

1201 

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

1203 ''' 

1204 return self._facc(_2floats(xs, sub=True)) if xs else self # PYCHOK yield 

1205 

1206 def fsub_(self, *xs): 

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

1208 from this instance. 

1209 

1210 @arg xs: Values to subtract (C{scalar} or 

1211 L{Fsum} instances), all positional. 

1212 

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

1214 

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

1216 ''' 

1217 return self._facc(_2floats(xs, origin=1, sub=True)) if xs else self # PYCHOK yield 

1218 

1219 def _fsub(self, other, op): 

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

1221 ''' 

1222 if isinstance(other, Fsum): 

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

1224 self._fset(_0_0, asis=True, n=len(self) * 2) # self -= self 

1225 elif other._ps: 

1226 self._facc(other._ps_n()) 

1227 elif not isscalar(other): 

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

1229 elif self._finite(other, op): 

1230 self._facc_(-other) 

1231 return self 

1232 

1233 def _Fsum(self, n, *ps): 

1234 '''(INTERNAL) New L{Fsum} instance. 

1235 ''' 

1236 f = Fsum() 

1237 f._n = n 

1238 if ps: 

1239 f._ps[:] = ps 

1240 f._copy_RESIDUAL(self) 

1241 return f 

1242 

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

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

1245 

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

1247 L{Fsum} instances). 

1248 

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

1250 

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

1252 

1253 @note: Accumulation can continue after summation. 

1254 ''' 

1255 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield 

1256 return f._fprs 

1257 

1258 def fsum_(self, *xs): 

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

1260 

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

1262 all positional. 

1263 

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

1265 

1266 @see: Method L{Fsum.fsum}. 

1267 ''' 

1268 f = self._facc(_2floats(xs, origin=1)) if xs else self # PYCHOK yield 

1269 return f._fprs 

1270 

1271 def fsum2(self, xs=(), **name): 

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

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

1274 

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

1276 L{Fsum} instances). 

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

1278 

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

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

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

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

1283 to be I{exact}. 

1284 

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

1286 ''' 

1287 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield 

1288 t = f._fprs2 

1289 if name: 

1290 t = t.dup(name=_xkwds_get(name, name=NN)) 

1291 return t 

1292 

1293 def fsum2_(self, *xs): 

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

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

1296 

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

1298 all positional. 

1299 

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

1301 running C{fsum} and C{delta}, the difference with 

1302 the previous running C{fsum} (C{float}s). 

1303 

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

1305 ''' 

1306 p, r = self._fprs2 

1307 if xs: 

1308 s, t = self._facc(_2floats(xs, origin=1))._fprs2 # PYCHOK yield 

1309 return s, _fsum((s, -p, r, -t)) # ((s - p) + (r - t)) 

1310 else: # PYCHOK no cover 

1311 return p, _0_0 

1312 

1313# ftruediv = __itruediv__ # for naming consistency 

1314 

1315 def _ftruediv(self, other, op): 

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

1317 ''' 

1318 n = _1_0 

1319 if isinstance(other, Fsum): 

1320 if other is self or other._fprs2 == self._fprs2: 

1321 return self._fset(_1_0, asis=True, n=len(self)) 

1322 d, r = other._fprs2 

1323 if r: 

1324 if not d: # PYCHOK no cover 

1325 d = r 

1326 elif self._raiser(r, d): 

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

1328 else: 

1329 d, n = other.as_integer_ratio() 

1330 elif isscalar(other): 

1331 d = other 

1332 else: # PYCHOK no cover 

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

1334 try: 

1335 s = 0 if isinf(d) else ( 

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

1337 except Exception as x: 

1338 E, t = _xError2(x) 

1339 raise self._Error(op, other, E, txt=t) 

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

1341 return self._fset(f) 

1342 

1343 @property_RO 

1344 def imag(self): 

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

1346 

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

1348 ''' 

1349 return _0_0 

1350 

1351 def int_float(self, raiser=False): 

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

1353 

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

1355 residual is non-zero. 

1356 

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

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

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

1360 

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

1362 

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

1364 ''' 

1365 s, r = self._fint2 

1366 if r: 

1367 s, r = self._fprs2 

1368 if r and raiser: # PYCHOK no cover 

1369 t = _stresidual(_non_zero_, r) 

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

1371 s = float(s) # redundant 

1372 return s 

1373 

1374 def is_exact(self): 

1375 '''Is this instance' current running C{fsum} considered to 

1376 be exact? (C{bool}). 

1377 ''' 

1378 return self.residual is INT0 

1379 

1380 def is_integer(self): 

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

1382 

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

1384 ''' 

1385 _, r = self._fint2 

1386 return False if r else True 

1387 

1388 def is_math_fsum(self): 

1389 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} 

1390 and L{fsum1_} plus partials summation are based on 

1391 Python's C{math.fsum} or not. 

1392 

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

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

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

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

1397 none are. 

1398 ''' 

1399 f = Fsum._math_fsum 

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

1401 

1402 def _mul_Fsum(self, other, op=_mul_op_): 

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

1404 ''' 

1405 # assert isinstance(other, Fsum) 

1406 return self._copy_0()._facc(self._ps_x(op, *other._ps), up=False) 

1407 

1408 def _mul_scalar(self, factor, op): 

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

1410 ''' 

1411 # assert isscalar(factor) 

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

1413 if factor == _1_0: 

1414 return self 

1415 f = self._copy_0()._facc(self._ps_x(op, factor), up=False) 

1416 else: 

1417 f = self._copy_0(_0_0) 

1418 return f 

1419 

1420 @property_RO 

1421 def partials(self): 

1422 '''Get this instance' current partial sums (C{tuple} of C{float}s and/or C{int}s). 

1423 ''' 

1424 return tuple(self._ps) 

1425 

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

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

1428 

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

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

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

1432 

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

1434 result (L{Fsum}). 

1435 

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

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

1438 or set C{integer} with L{Fsum.fint}. 

1439 

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

1441 ''' 

1442 f = self._copy_2(self.pow) 

1443 if f and isint(x) and x >= 0 and not mod: 

1444 f._pow_int(x, x, _pow_op_) # f **= x 

1445 else: 

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

1447 return f 

1448 

1449 def _pow_0_1(self, x, other): 

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

1451 ''' 

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

1453 

1454 def _pow_2(self, x, other, op): 

1455 '''(INTERNAL) 2-arg C{pow(B{self}, scalar B{x})} embellishing errors. 

1456 ''' 

1457 # assert len(self._ps) == 1 and isscalar(x) 

1458 b = self._ps[0] # assert isscalar(b) 

1459 try: # type(s) == type(x) if x in (_1_0, 1) 

1460 s = pow(b, x) # -1**2.3 == -(1**2.3) 

1461 if not iscomplex(s): 

1462 return self._finite(s) # 0**INF == 0.0, 1**INF==1.0 

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

1464 E, t = _ValueError, _strcomplex(s, b, x) # PYCHOK no cover 

1465 except Exception as x: 

1466 E, t = _xError2(x) 

1467 raise self._Error(op, other, E, txt=t) 

1468 

1469 def _pow_3(self, other, mod, op): 

1470 '''(INTERNAL) 3-arg C{pow(B{self}, B{other}, int B{mod} or C{None})}. 

1471 ''' 

1472 b, r = self._fprs2 if mod is None else self._fint2 

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

1474 t = _non_zero_ if mod is None else _integer_ 

1475 E, t = ResidualError, _stresidual(t, r, mod=mod) 

1476 else: 

1477 try: # b, other, mod all C{int}, unless C{mod} is C{None} 

1478 x = _2scalar(other, _raiser=self._raiser) 

1479 s = pow(b, x, mod) 

1480 if not iscomplex(s): 

1481 return self._finite(s) 

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

1483 E, t = _ValueError, _strcomplex(s, b, x, mod) # PYCHOK no cover 

1484 except Exception as x: 

1485 E, t = _xError2(x) 

1486 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod), t) 

1487 raise self._Error(op, other, E, txt=t) 

1488 

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

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

1491 ''' 

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

1493 if len(self._ps) > 1: 

1494 if x > 2: 

1495 p = self._copy_up() 

1496 m = 1 # single-bit mask 

1497 if x & m: 

1498 x -= m # x ^= m 

1499 f = p._copy_up() 

1500 else: 

1501 f = self._copy_0(_1_0) 

1502 while x: 

1503 p = p._mul_Fsum(p, op) # p **= 2 

1504 m += m # m <<= 1 

1505 if x & m: 

1506 x -= m # x ^= m 

1507 f = f._mul_Fsum(p, op) # f *= p 

1508 elif x > 1: # self**2 

1509 f = self._mul_Fsum(self, op) 

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

1511 f = self._pow_0_1(x, other) 

1512 elif self._ps: # self._ps[0]**x 

1513 f = self._pow_2(x, other, op) 

1514 else: # PYCHOK no cover 

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

1516 f = 0 if x else 1 # like ._fprs 

1517 return self._fset(f, asis=isint(f), n=len(self)) 

1518 

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

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

1521 ''' 

1522 s, r = self._fprs2 

1523 if isint(x, both=True): 

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

1525 y = abs(x) 

1526 if y > 1: 

1527 if r: 

1528 f = self._copy_up()._pow_int(y, other, op) 

1529 if x > 0: # > 1 

1530 return f 

1531 # assert x < 0 # < -1 

1532 s, r = f._fprs2 

1533 if r: 

1534 return self._copy_0(_1_0)._ftruediv(f, op) 

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

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

1537 x = -1 

1538# elif y > 1: # self**2 or self**-2 

1539# f = self._mul_Fsum(self, op) 

1540# if x < 0: 

1541# f = f._copy_0(_1_0)._ftruediv(f, op) 

1542# return f 

1543 elif x < 0: # self**-1 == 1 / self 

1544 if r: 

1545 return self._copy_0(_1_0)._ftruediv(self, op) 

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

1547 return self._pow_0_1(x, other) # self or 0.0 

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

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

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

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

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

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

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

1555 return self._copy_0(s)._pow_2(x, other, op) 

1556 

1557 def _ps_1(self, *less): 

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

1559 ''' 

1560 yield _1_0 

1561 for p in self._ps: 

1562 if p: 

1563 yield p 

1564 for p in less: 

1565 if p: 

1566 yield -p 

1567 yield _N_1_0 

1568 

1569 def _ps_n(self): 

1570 '''(INTERNAL) Yield partials, negated. 

1571 ''' 

1572 for p in self._ps: 

1573 if p: 

1574 yield -p 

1575 

1576 def _ps_x(self, op, *factors): # see .fmath.Fhorner 

1577 '''(INTERNAL) Yield all C{partials} times each B{C{factor}}, 

1578 in total, up to C{len(partials) * len(factors)} items. 

1579 ''' 

1580 ps = self._ps 

1581 if len(ps) < len(factors): 

1582 ps, factors = factors, ps 

1583 _f = _isfinite 

1584 for f in factors: 

1585 for p in ps: 

1586 p *= f 

1587 if _f(p): 

1588 yield p 

1589 else: # PYCHOK no cover 

1590 self._finite(p, op) # throw ValueError 

1591 

1592 @property_RO 

1593 def real(self): 

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

1595 

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

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

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

1599 ''' 

1600 return float(self._fprs) 

1601 

1602 @property_RO 

1603 def residual(self): 

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

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

1606 

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

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

1609 

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

1611 ''' 

1612 return self._fprs2.residual 

1613 

1614 def _raiser(self, r, s): 

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

1616 ''' 

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

1618 return t > self._RESIDUAL 

1619 

1620 def RESIDUAL(self, *threshold): 

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

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

1623 

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

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

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

1627 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

1628 current setting. 

1629 

1630 @return: The previous C{RESIDUAL} setting (C{float}). 

1631 

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

1633 

1634 @note: A L{ResidualError} is thrown if the non-zero I{ratio} 

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

1636 ''' 

1637 r = self._RESIDUAL 

1638 if threshold: 

1639 t = threshold[0] 

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

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

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

1643 if t < 0: 

1644 u = self._unstr(self.RESIDUAL, *threshold) 

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

1646 self._RESIDUAL = t 

1647 return r 

1648 

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

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

1651 ''' 

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

1653 RESIDUAL=self._RESIDUAL) 

1654 t = t.replace(_COMMASPACE_R_, _exceeds_R_) 

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

1656 

1657 def signOf(self, res=True): 

1658 '''Determine the sign of this instance. 

1659 

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

1661 ignore the residual (C{bool}). 

1662 

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

1664 ''' 

1665 s, r = self._fprs2 if res else (self._fprs, 0) 

1666 return _signOf(r, -s) 

1667 

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

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

1670 

1671 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1675 

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

1677 ''' 

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

1679 

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

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

1682 

1683 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1687 

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

1689 ''' 

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

1691 

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

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

1694 ''' 

1695 n = self.named3 

1696 if lenc: 

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

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

1699 

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

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

1702 ''' 

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

1704 

1705 def _update(self): # see ._fset 

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

1707 ''' 

1708 Fsum._fint2._update(self) 

1709 Fsum._fprs ._update(self) 

1710 Fsum._fprs2._update(self) 

1711 return self 

1712 

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

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

1715 ''' 

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

1717 

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

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

1720 ''' 

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

1722 

1723_allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK assert, see Fsum._fset, -._update 

1724 

1725 

1726def _Float_Int(arg, **name_Error): 

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

1728 ''' 

1729 U = Int if isint(arg) else Float 

1730 return U(arg, **name_Error) 

1731 

1732 

1733class Fsum2Tuple(_NamedTuple): 

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

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

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

1737 

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

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

1740 ''' 

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

1742 _Units_ = (_Float_Int, _Float_Int) 

1743 

1744 @Property_RO 

1745 def Fsum(self): 

1746 '''Get this L{Fsum2Tuple} as an L{Fsum}. 

1747 ''' 

1748 f = Fsum(name=self.name) 

1749 return f._copy_0(*(s for s in reversed(self) if s)) 

1750 

1751 def is_exact(self): 

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

1753 ''' 

1754 return self.Fsum.is_exact() 

1755 

1756 def is_integer(self): 

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

1758 ''' 

1759 return self.Fsum.is_integer() 

1760 

1761 

1762class ResidualError(_ValueError): 

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

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

1765 

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

1767 ''' 

1768 pass 

1769 

1770 

1771try: 

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

1773 

1774 # make sure _fsum works as expected (XXX check 

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

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

1777 del _fsum # nope, remove _fsum ... 

1778 raise ImportError # ... use _fsum below 

1779 

1780 Fsum._math_fsum = _fsum 

1781 

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

1783 _psum = _fsum # PYCHOK redef 

1784 

1785except ImportError: 

1786 

1787 def _fsum(xs): 

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

1789 ''' 

1790 return Fsum(name=_fsum.__name__)._facc(xs, up=False)._fprs 

1791 

1792 

1793def fsum(xs, floats=False): 

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

1795 

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

1797 L{Fsum} instances). 

1798 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} 

1799 B{C{xs}} are known to be C{float}. 

1800 

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

1802 

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

1804 

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

1806 

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

1808 

1809 @note: Exceptions and I{non-finite} handling may differ if not 

1810 based on Python's C{math.fsum}. 

1811 

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

1813 ''' 

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

1815 

1816 

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

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

1819 

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

1821 all positional. 

1822 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} 

1823 B{C{xs}} are known to be C{float}. 

1824 

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

1826 

1827 @see: Function C{fsum}. 

1828 ''' 

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

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

1831 

1832 

1833def fsumf_(*xs): 

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

1835 ''' 

1836 return _fsum(xs) if xs else _0_0 

1837 

1838 

1839def fsum1(xs, floats=False): 

1840 '''Precision floating point summation of a few arguments, 1-primed. 

1841 

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

1843 L{Fsum} instances). 

1844 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} 

1845 B{C{xs}} are known to be C{float}. 

1846 

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

1848 

1849 @see: Function C{fsum}. 

1850 ''' 

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

1852 

1853 

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

1855 '''Precision floating point summation of a few arguments, 1-primed. 

1856 

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

1858 all positional. 

1859 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} 

1860 B{C{xs}} are known to be C{float}. 

1861 

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

1863 

1864 @see: Function C{fsum} 

1865 ''' 

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

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

1868 

1869 

1870def fsum1f_(*xs): 

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

1872 ''' 

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

1874 

1875 

1876# **) MIT License 

1877# 

1878# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved. 

1879# 

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

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

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

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

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

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

1886# 

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

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

1889# 

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

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

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

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

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

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

1896# OTHER DEALINGS IN THE SOFTWARE.