Coverage for pygeodesy/fsums.py: 98%

704 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-03-08 13:06 -0500

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, itemsorted, \ 

30 signOf, _signOf, _xisscalar 

31from pygeodesy.constants import INT0, _isfinite, isinf, isnan, _pos_self, \ 

32 _0_0, _1_0, _N_1_0, Float, Int 

33from pygeodesy.errors import _OverflowError, _TypeError, _ValueError, \ 

34 _xError2, _xkwds_get, _ZeroDivisionError 

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

36 _exceeds_, _from_, _iadd_op_, _LANGLE_, \ 

37 _negative_, _NOTEQUAL_, _not_finite_, \ 

38 _not_scalar_, _PERCENT_, _PLUS_, _R_, _RANGLE_, \ 

39 _SLASH_, _SPACE_, _STAR_, _UNDER_ 

40from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2 

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

42from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \ 

43 Property_RO, property_RO 

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

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

46 

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

48 

49__all__ = _ALL_LAZY.fsums 

50__version__ = '24.02.20' 

51 

52_add_op_ = _PLUS_ # in .auxilats.auxAngle 

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_ # 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 _2float(index=None, **name_value): # in .fmath, .fstats 

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

76 ''' 

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

78 try: 

79 v = float(v) 

80 if _isfinite(v): 

81 return v 

82 E, t = _ValueError, _not_finite_ 

83 except Exception as e: 

84 E, t = _xError2(e) 

85 raise E(Fmt.INDEX(n, index), v, txt=t) 

86 

87 

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

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

90 ''' 

91 try: 

92 i, x = origin, None 

93 _fin = _isfinite 

94 _Fsum = Fsum 

95 for x in xs: 

96 if isinstance(x, _Fsum): 

97 for p in x._ps: 

98 yield (-p) if sub else p 

99 else: 

100 f = float(x) 

101 if not _fin(f): 

102 raise ValueError(_not_finite_) 

103 if f: 

104 yield (-f) if sub else f 

105 i += 1 

106 except Exception as e: 

107 E, t = _xError2(e) 

108 n = Fmt.SQUARE(xs=i) 

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

110 

111 

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

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

114 ''' 

115 _xisscalar(power=power) 

116 try: 

117 i, x = origin, None 

118 _fin = _isfinite 

119 _Fsum = Fsum 

120 _pow = pow # XXX math.pow 

121 for x in xs: 

122 if isinstance(x, _Fsum): 

123 P = x.pow(power) 

124 for p in P._ps: 

125 yield p 

126 else: 

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

128 if not _fin(p): 

129 raise ValueError(_not_finite_) 

130 yield p 

131 i += 1 

132 except Exception as e: 

133 E, t = _xError2(e) 

134 n = Fmt.SQUARE(xs=i) 

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

136 

137 

138def _1primed(xs): 

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

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

141 ''' 

142 yield _1_0 

143 for x in xs: 

144 if x: 

145 yield x 

146 yield _N_1_0 

147 

148 

149def _psum(ps): # PYCHOK used! 

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

151 ''' 

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

153 s = ps[i] 

154 _2s = _2sum 

155 while i > 0: 

156 i -= 1 

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

158 if r: # sum(ps) became inexact 

159 ps[i:] = [s, r] if s else [r] 

160 if i > 0: 

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

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

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

164 r *= 2 

165 t = s + r 

166 if r == (t - s): 

167 s = t 

168 break 

169 ps[i:] = [s] 

170 return s 

171 

172 

173def _2scalar(other, _raiser=None): 

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

175 ''' 

176 if isinstance(other, Fsum): 

177 s, r = other._fint2 

178 if r: 

179 s, r = other._fprs2 

180 if r: # PYCHOK no cover 

181 if _raiser and _raiser(r, s): 

182 raise ValueError(_stresidual(_non_zero_, r)) 

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

184 else: 

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

186 if isint(s, both=True): 

187 s = int(s) 

188 return s 

189 

190 

191def _strcomplex(s, *args): 

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

193 ''' 

194 c = iscomplex.__name__[2:] 

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

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

197 return unstr(t, *args) 

198 

199 

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

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

202 ''' 

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

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

205 for n, v in itemsorted(name_values): 

206 n = n.replace(_UNDER_, _SPACE_) 

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

208 t = _COMMASPACE_(t, p) 

209 return t 

210 

211 

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

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

214 ''' 

215 s = a + b 

216 if not _isfinite(s): 

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

218 t = Fmt.PARENSPACED(_not_finite_, s) 

219 raise _OverflowError(u, txt=t) 

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

221 a, b = b, a 

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

223 

224 

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

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

227 

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

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

230 intermediate, I{running} summuation. 

231 

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

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

234 method C{__float__}. 

235 

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

237 Python's C{math.fsum}. 

238 

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

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

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

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

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

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

245 ''' 

246 _math_fsum = None 

247 _n = 0 

248# _ps = [] # partial sums 

249# _px = 0 

250 _ratio = None 

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

252 

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

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

255 

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

257 L{Fsum} instance). 

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

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

260 L{ResidualError} threshold. 

261 

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

263 ''' 

264 if name_RESIDUAL: 

265 n = _xkwds_get(name_RESIDUAL, name=NN) 

266 if n: # set name ... 

267 self.name = n 

268 r = _xkwds_get(name_RESIDUAL, RESIDUAL=None) 

269 if r is not None: 

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

271# self._n = 0 

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

273 if len(xs) > 1: 

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

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

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

277 self._n = 1 

278 

279 def __abs__(self): 

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

281 ''' 

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

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

284 self._copy_2(self.__abs__) 

285 

286 def __add__(self, other): 

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

288 

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

290 

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

292 

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

294 ''' 

295 f = self._copy_2(self.__add__) 

296 return f._fadd(other, _add_op_) 

297 

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

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

300 ''' 

301 s, r = self._fprs2 

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

303 

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

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

306 

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

308 

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

310 ''' 

311 return self.ceil 

312 

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

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

315 

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

317 

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

319 ''' 

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

321 return _signOf(s, 0) 

322 

323 cmp = __cmp__ 

324 

325 def __divmod__(self, other): 

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

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

328 and an L{Fsum}. 

329 

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

331 

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

333 ''' 

334 f = self._copy_2(self.__divmod__) 

335 return f._fdivmod2(other, _divmod_op_) 

336 

337 def __eq__(self, other): 

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

339 ''' 

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

341 

342 def __float__(self): 

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

344 

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

346 ''' 

347 return float(self._fprs) 

348 

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

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

351 

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

353 

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

355 ''' 

356 return self.floor 

357 

358 def __floordiv__(self, other): 

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

360 

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

362 

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

364 

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

366 ''' 

367 f = self._copy_2(self.__floordiv__) 

368 return f._floordiv(other, _floordiv_op_) 

369 

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

371 '''Not implemented.''' 

372 return _NotImplemented(self, *other) 

373 

374 def __ge__(self, other): 

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

376 ''' 

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

378 

379 def __gt__(self, other): 

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

381 ''' 

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

383 

384 def __hash__(self): # PYCHOK no cover 

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

386 ''' 

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

388 

389 def __iadd__(self, other): 

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

391 

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

393 

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

395 

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

397 C{scalar} nor L{Fsum}. 

398 

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

400 ''' 

401 return self._fadd(other, _iadd_op_) 

402 

403 def __ifloordiv__(self, other): 

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

405 

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

407 

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

409 

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

411 

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

413 

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

415 

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

417 

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

419 ''' 

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

421 

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

423 '''Not implemented.''' 

424 return _NotImplemented(self, other) 

425 

426 def __imod__(self, other): 

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

428 

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

430 

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

432 

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

434 ''' 

435 self._fdivmod2(other, _mod_op_ + _fset_op_) 

436 return self 

437 

438 def __imul__(self, other): 

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

440 

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

442 

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

444 

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

446 

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

448 

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

450 ''' 

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

452 

453 def __int__(self): 

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

455 

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

457 and L{Fsum.__floor__} and properties 

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

459 ''' 

460 i, _ = self._fint2 

461 return i 

462 

463 def __invert__(self): # PYCHOK no cover 

464 '''Not implemented.''' 

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

466 return _NotImplemented(self) 

467 

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

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

470 

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

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

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

474 version. 

475 

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

477 

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

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

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

481 

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

483 

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

485 env var C{PYGEODESY_FSUM_RESIDUAL} 

486 set or this instance has a non-zero 

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

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

489 is a negative or fractional C{scalar}. 

490 

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

492 C{pow} invocation failed. 

493 

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

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

496 is a fractional C{scalar} and this 

497 instance is negative or has a non-zero 

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

499 

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

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

502 ''' 

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

504 

505 def __isub__(self, other): 

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

507 

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

509 

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

511 

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

513 

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

515 ''' 

516 return self._fsub(other, _isub_op_) 

517 

518 def __iter__(self): 

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

520 ''' 

521 return iter(self.partials) 

522 

523 def __itruediv__(self, other): 

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

525 

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

527 

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

529 

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

531 

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

533 env var C{PYGEODESY_FSUM_RESIDUAL} set. 

534 

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

536 

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

538 

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

540 

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

542 ''' 

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

544 

545 def __le__(self, other): 

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

547 ''' 

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

549 

550 def __len__(self): 

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

552 ''' 

553 return self._n 

554 

555 def __lt__(self, other): 

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

557 ''' 

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

559 

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

561 '''Not implemented.''' 

562 return _NotImplemented(self, other) 

563 

564 def __mod__(self, other): 

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

566 

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

568 ''' 

569 f = self._copy_2(self.__mod__) 

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

571 

572 def __mul__(self, other): 

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

574 

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

576 ''' 

577 f = self._copy_2(self.__mul__) 

578 return f._fmul(other, _mul_op_) 

579 

580 def __ne__(self, other): 

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

582 ''' 

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

584 

585 def __neg__(self): 

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

587 ''' 

588 return self._copy_n(self.__neg__) 

589 

590 def __pos__(self): 

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

592 ''' 

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

594 

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

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

597 

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

599 ''' 

600 f = self._copy_2(self.__pow__) 

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

602 

603 def __radd__(self, other): 

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

605 

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

607 ''' 

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

609 return f._fadd(self, _add_op_) 

610 

611 def __rdivmod__(self, other): 

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

613 remainder)}. 

614 

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

616 ''' 

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

618 return f._fdivmod2(self, _divmod_op_) 

619 

620# def __repr__(self): 

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

622# ''' 

623# return self.toRepr(lenc=True) 

624 

625 def __rfloordiv__(self, other): 

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

627 

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

629 ''' 

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

631 return f._floordiv(self, _floordiv_op_) 

632 

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

634 '''Not implemented.''' 

635 return _NotImplemented(self, other) 

636 

637 def __rmod__(self, other): 

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

639 

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

641 ''' 

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

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

644 

645 def __rmul__(self, other): 

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

647 

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

649 ''' 

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

651 return f._fmul(self, _mul_op_) 

652 

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

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

655 

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

657 ''' 

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

659 f = Fsum(name=self.__round__.__name__) 

660 f._n = 1 

661 f._ps = [round(float(self), *ndigits)] # can be C{int} 

662 return f 

663 

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

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

666 

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

668 ''' 

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

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

671 

672 def __rsub__(self, other): 

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

674 

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

676 ''' 

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

678 return f._fsub(self, _sub_op_) 

679 

680 def __rtruediv__(self, other): 

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

682 

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

684 ''' 

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

686 return f._ftruediv(self, _truediv_op_) 

687 

688 def __str__(self): 

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

690 ''' 

691 return self.toStr(lenc=True) 

692 

693 def __sub__(self, other): 

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

695 

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

697 

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

699 

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

701 ''' 

702 f = self._copy_2(self.__sub__) 

703 return f._fsub(other, _sub_op_) 

704 

705 def __truediv__(self, other): 

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

707 

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

709 

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

711 

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

713 ''' 

714 f = self._copy_2(self.__truediv__) 

715 return f._ftruediv(other, _truediv_op_) 

716 

717 __trunc__ = __int__ 

718 

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

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

721 __div__ = __truediv__ 

722 __idiv__ = __itruediv__ 

723 __long__ = __int__ 

724 __nonzero__ = __bool__ 

725 __rdiv__ = __rtruediv__ 

726 

727 def as_integer_ratio(self): 

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

729 

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

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

732 

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

734 ''' 

735 n, r = self._fint2 

736 if r: 

737 i, d = r.as_integer_ratio() 

738 n *= d 

739 n += i 

740 else: # PYCHOK no cover 

741 d = 1 

742 return n, d 

743 

744 @property_RO 

745 def ceil(self): 

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

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

748 

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

750 

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

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

753 ''' 

754 s, r = self._fprs2 

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

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

757 c += 1 

758 return c 

759 

760 def _cmp_0(self, other, op): 

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

762 ''' 

763 if isscalar(other): 

764 if other: 

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

766 else: 

767 s, r = self._fprs2 

768 s = _signOf(s, -r) 

769 elif isinstance(other, Fsum): 

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

771 else: 

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

773 return s 

774 

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

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

777 

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

779 ''' 

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

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

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

783 return f 

784 

785 def _copy_0(self, *xs): 

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

787 ''' 

788 # for x in xs: 

789 # assert isscalar(x) 

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

791 if self.name: 

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

793 return f 

794 

795 def _copy_2(self, which): 

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

797 ''' 

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

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

800 # assert f._n == self._n 

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

802 return f 

803 

804 def _copy_n(self, which): 

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

806 ''' 

807 if self._ps: 

808 f = self._Fsum(self._n) 

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

810# f._facc_up(up=False) 

811 else: 

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

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

814 return f 

815 

816 def _copy_r2(self, other, which): 

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

818 ''' 

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

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

821 

822 def _copy_RESIDUAL(self, other): 

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

824 ''' 

825 R = other._RESIDUAL 

826 if R is not Fsum._RESIDUAL: 

827 self._RESIDUAL = R 

828 

829 def _copy_up(self, _fprs2=False): 

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

831 ''' 

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

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

834 Fsum._fprs2._update_from(f, self) 

835 return f 

836 

837 def divmod(self, other): 

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

839 remainder)}. 

840 

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

842 

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

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

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

846 

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

848 ''' 

849 f = self._copy_2(self.divmod) 

850 return f._fdivmod2(other, _divmod_op_) 

851 

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

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

854 ''' 

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

856 

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

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

859 ''' 

860 E, t = _xError2(X) 

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

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

863 

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

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

866 ''' 

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

868 for x in xs: # _iter() 

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

870 i = 0 

871 for p in ps: 

872 x, p = _2s(x, p) 

873 if p: 

874 ps[i] = p 

875 i += 1 

876 ps[i:] = [x] 

877 n += 1 

878 # assert self._ps is ps 

879 if n: 

880 self._n += n 

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

882 if up: 

883 self._update() 

884 return self 

885 

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

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

888 ''' 

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

890 

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

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

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

894# ''' 

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

896# p = self._ps.pop() 

897# if p: 

898# n = self._n 

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

900# self._n = n 

901# break 

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

903 

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

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

906 to this instance. 

907 

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

909 L{Fsum} instances). 

910 

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

912 

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

914 

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

916 nor L{Fsum}. 

917 

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

919 ''' 

920 if isinstance(xs, Fsum): 

921 self._facc(xs._ps) 

922 elif isscalar(xs): # for backward compatibility 

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

924 elif xs: 

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

926 return self 

927 

928 def fadd_(self, *xs): 

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

930 to this instance. 

931 

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

933 all positional. 

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 return self._facc(_2floats(xs, origin=1)) # PYCHOK yield 

945 

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

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

948 ''' 

949 if isinstance(other, Fsum): 

950 if other is self: 

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

952 elif other._ps: 

953 self._facc(other._ps) 

954 elif not isscalar(other): 

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

956 elif other: 

957 self._facc_(other) 

958 return self 

959 

960 fcopy = copy # for backward compatibility 

961 fdiv = __itruediv__ # for backward compatibility 

962 fdivmod = __divmod__ # for backward compatibility 

963 

964 def _fdivmod2(self, other, op): 

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

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

967 ''' 

968 # result mostly follows CPython function U{float_divmod 

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

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

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

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

973 self -= other * q 

974 

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

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

977 self += other 

978 q -= 1 

979 

980# t = self.signOf() 

981# if t and t != s: 

982# from pygeodesy.errors import _AssertionError 

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

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

985 

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

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

988 ''' 

989 if _isfinite(other): 

990 return other 

991 raise ValueError(_not_finite_) if not op else \ 

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

993 

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

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

996 

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

998 I{integer} residual is non-zero. 

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

1000 

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

1002 

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

1004 

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

1006 ''' 

1007 i, r = self._fint2 

1008 if r and raiser: 

1009 t = _stresidual(_integer_, r) 

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

1011 n = name or self.fint.__name__ 

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

1013 

1014 def fint2(self, **name): 

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

1016 the I{integer} residual. 

1017 

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

1019 

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

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

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

1023 ''' 

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

1025 

1026 @Property_RO 

1027 def _fint2(self): # see ._fset 

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

1029 ''' 

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

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

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

1033 return i, (r or INT0) 

1034 

1035 @deprecated_property_RO 

1036 def float_int(self): # PYCHOK no cover 

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

1038 return self.int_float() # raiser=False 

1039 

1040 @property_RO 

1041 def floor(self): 

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

1043 C{float} in Python 2-). 

1044 

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

1046 

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

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

1049 ''' 

1050 s, r = self._fprs2 

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

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

1053 f -= 1 

1054 return f 

1055 

1056# floordiv = __floordiv__ # for naming consistency 

1057 

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

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

1060 ''' 

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

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

1063 

1064 fmul = __imul__ # for backward compatibility 

1065 

1066 def _fmul(self, other, op): 

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

1068 ''' 

1069 if isscalar(other): 

1070 f = self._mul_scalar(other, op) 

1071 elif not isinstance(other, Fsum): 

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

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

1074 f = self._mul_Fsum(other, op) 

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

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

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

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

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

1080 return self._fset(f) 

1081 

1082 def fover(self, over): 

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

1084 

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

1086 

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

1088 

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

1090 ''' 

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

1092 

1093 fpow = __ipow__ # for backward compatibility 

1094 

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

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

1097 ''' 

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

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

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

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

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

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

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

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

1106 p = None 

1107 if isinstance(other, Fsum): 

1108 x, r = other._fprs2 

1109 if r: 

1110 if self._raiser(r, x): 

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

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

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

1114 elif not isscalar(other): 

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

1116 else: 

1117 x = self._finite(other, op) 

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

1119 if p is not None: 

1120 s *= p 

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

1122 

1123 @Property_RO 

1124 def _fprs(self): 

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

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

1127 

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

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

1130 ''' 

1131 ps = self._ps 

1132 n = len(ps) - 1 

1133 if n > 1: 

1134 s = _psum(ps) 

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

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

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

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

1139 s = _0_0 

1140 ps[:] = [s] 

1141 else: # len(ps) == 1 

1142 s = ps[0] 

1143 # assert self._ps is ps 

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

1145 return s 

1146 

1147 @Property_RO 

1148 def _fprs2(self): 

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

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

1151 ''' 

1152 s = self._fprs 

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

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

1155 

1156# def _fpsqz(self): 

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

1158# ''' 

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

1160# _ = self._fprs 

1161# return self 

1162 

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

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

1165 ''' 

1166 if other is self: 

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

1168 elif isinstance(other, Fsum): 

1169 self._n = other._n 

1170 self._ps[:] = other._ps 

1171 self._copy_RESIDUAL(other) 

1172 # use or zap the C{Property_RO} values 

1173 Fsum._fint2._update_from(self, other) 

1174 Fsum._fprs ._update_from(self, other) 

1175 Fsum._fprs2._update_from(self, other) 

1176 elif isscalar(other): 

1177 s = other if asis else float(other) 

1178 i = int(s) # see ._fint2 

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

1180 self._n = n 

1181 self._ps[:] = [s] 

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

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

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

1185 else: # PYCHOK no cover 

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

1187 return self 

1188 

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

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

1191 from this instance. 

1192 

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

1194 or L{Fsum} instances). 

1195 

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

1197 

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

1199 ''' 

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

1201 

1202 def fsub_(self, *xs): 

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

1204 from this instance. 

1205 

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

1207 L{Fsum} instances), all positional. 

1208 

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

1210 

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

1212 ''' 

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

1214 

1215 def _fsub(self, other, op): 

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

1217 ''' 

1218 if isinstance(other, Fsum): 

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

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

1221 elif other._ps: 

1222 self._facc(other._ps_n()) 

1223 elif not isscalar(other): 

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

1225 elif self._finite(other, op): 

1226 self._facc_(-other) 

1227 return self 

1228 

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

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

1231 ''' 

1232 f = Fsum() 

1233 f._n = n 

1234 if ps: 

1235 f._ps[:] = ps 

1236 f._copy_RESIDUAL(self) 

1237 return f 

1238 

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

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

1241 

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

1243 L{Fsum} instances). 

1244 

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

1246 

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

1248 

1249 @note: Accumulation can continue after summation. 

1250 ''' 

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

1252 return f._fprs 

1253 

1254 def fsum_(self, *xs): 

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

1256 

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

1258 all positional. 

1259 

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

1261 

1262 @see: Methods L{Fsum.fsum} and L{Fsum.fsumf_}. 

1263 ''' 

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

1265 return f._fprs 

1266 

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

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

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

1270 

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

1272 L{Fsum} instances). 

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

1274 

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

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

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

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

1279 to be I{exact}. 

1280 

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

1282 ''' 

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

1284 t = f._fprs2 

1285 if name: 

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

1287 return t 

1288 

1289 def fsum2_(self, *xs): 

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

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

1292 

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

1294 all positional. 

1295 

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

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

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

1299 

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

1301 ''' 

1302 p, r = self._fprs2 

1303 if xs: 

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

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

1306 else: # PYCHOK no cover 

1307 return p, _0_0 

1308 

1309 def fsumf_(self, *xs): 

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

1311 ''' 

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

1313 return f._fprs 

1314 

1315# ftruediv = __itruediv__ # for naming consistency 

1316 

1317 def _ftruediv(self, other, op): 

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

1319 ''' 

1320 n = _1_0 

1321 if isinstance(other, Fsum): 

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

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

1324 d, r = other._fprs2 

1325 if r: 

1326 if not d: # PYCHOK no cover 

1327 d = r 

1328 elif self._raiser(r, d): 

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

1330 else: 

1331 d, n = other.as_integer_ratio() 

1332 elif isscalar(other): 

1333 d = other 

1334 else: # PYCHOK no cover 

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

1336 try: 

1337 s = 0 if isinf(d) else ( 

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

1339 except Exception as x: 

1340 E, t = _xError2(x) 

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

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

1343 return self._fset(f) 

1344 

1345 @property_RO 

1346 def imag(self): 

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

1348 

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

1350 ''' 

1351 return _0_0 

1352 

1353 def int_float(self, raiser=False): 

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

1355 

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

1357 residual is non-zero. 

1358 

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

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

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

1362 

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

1364 

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

1366 ''' 

1367 s, r = self._fint2 

1368 if r: 

1369 s, r = self._fprs2 

1370 if r and raiser: # PYCHOK no cover 

1371 t = _stresidual(_non_zero_, r) 

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

1373 s = float(s) # redundant 

1374 return s 

1375 

1376 def is_exact(self): 

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

1378 be exact? (C{bool}). 

1379 ''' 

1380 return self.residual is INT0 

1381 

1382 def is_integer(self): 

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

1384 

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

1386 ''' 

1387 _, r = self._fint2 

1388 return False if r else True 

1389 

1390 def is_math_fsum(self): 

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

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

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

1394 

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

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

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

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

1399 none are. 

1400 ''' 

1401 f = Fsum._math_fsum 

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

1403 

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

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

1406 ''' 

1407 # assert isinstance(other, Fsum) 

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

1409 

1410 def _mul_scalar(self, factor, op): 

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

1412 ''' 

1413 # assert isscalar(factor) 

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

1415 if factor == _1_0: 

1416 return self 

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

1418 else: 

1419 f = self._copy_0(_0_0) 

1420 return f 

1421 

1422 @property_RO 

1423 def partials(self): 

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

1425 ''' 

1426 return tuple(self._ps) 

1427 

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

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

1430 

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

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

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

1434 

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

1436 result (L{Fsum}). 

1437 

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

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

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

1441 

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

1443 ''' 

1444 f = self._copy_2(self.pow) 

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

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

1447 else: 

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

1449 return f 

1450 

1451 def _pow_0_1(self, x, other): 

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

1453 ''' 

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

1455 

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

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

1458 ''' 

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

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

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

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

1463 if not iscomplex(s): 

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

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

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

1467 except Exception as x: 

1468 E, t = _xError2(x) 

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

1470 

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

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

1473 ''' 

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

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

1476 t = _non_zero_ if mod is None else _integer_ 

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

1478 else: 

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

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

1481 s = pow(b, x, mod) 

1482 if not iscomplex(s): 

1483 return self._finite(s) 

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

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

1486 except Exception as x: 

1487 E, t = _xError2(x) 

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

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

1490 

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

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

1493 ''' 

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

1495 if len(self._ps) > 1: 

1496 if x > 2: 

1497 p = self._copy_up() 

1498 m = 1 # single-bit mask 

1499 if x & m: 

1500 x -= m # x ^= m 

1501 f = p._copy_up() 

1502 else: 

1503 f = self._copy_0(_1_0) 

1504 while x: 

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

1506 m += m # m <<= 1 

1507 if x & m: 

1508 x -= m # x ^= m 

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

1510 elif x > 1: # self**2 

1511 f = self._mul_Fsum(self, op) 

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

1513 f = self._pow_0_1(x, other) 

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

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

1516 else: # PYCHOK no cover 

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

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

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

1520 

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

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

1523 ''' 

1524 s, r = self._fprs2 

1525 if isint(x, both=True): 

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

1527 y = abs(x) 

1528 if y > 1: 

1529 if r: 

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

1531 if x > 0: # > 1 

1532 return f 

1533 # assert x < 0 # < -1 

1534 s, r = f._fprs2 

1535 if r: 

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

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

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

1539 x = -1 

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

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

1542# if x < 0: 

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

1544# return f 

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

1546 if r: 

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

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

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

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

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

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

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

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

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

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

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

1558 

1559 def _ps_1(self, *less): 

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

1561 ''' 

1562 yield _1_0 

1563 for p in self._ps: 

1564 if p: 

1565 yield p 

1566 for p in less: 

1567 if p: 

1568 yield -p 

1569 yield _N_1_0 

1570 

1571 def _ps_n(self): 

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

1573 ''' 

1574 for p in self._ps: 

1575 if p: 

1576 yield -p 

1577 

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

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

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

1581 ''' 

1582 ps = self._ps 

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

1584 ps, factors = factors, ps 

1585 _f = _isfinite 

1586 for f in factors: 

1587 for p in ps: 

1588 p *= f 

1589 if _f(p): 

1590 yield p 

1591 else: # PYCHOK no cover 

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

1593 

1594 @property_RO 

1595 def real(self): 

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

1597 

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

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

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

1601 ''' 

1602 return float(self._fprs) 

1603 

1604 @property_RO 

1605 def residual(self): 

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

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

1608 

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

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

1611 

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

1613 ''' 

1614 return self._fprs2.residual 

1615 

1616 def _raiser(self, r, s): 

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

1618 ''' 

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

1620 return t > self._RESIDUAL 

1621 

1622 def RESIDUAL(self, *threshold): 

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

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

1625 

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

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

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

1629 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

1630 current setting. 

1631 

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

1633 

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

1635 

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

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

1638 ''' 

1639 r = self._RESIDUAL 

1640 if threshold: 

1641 t = threshold[0] 

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

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

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

1645 if t < 0: 

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

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

1648 self._RESIDUAL = t 

1649 return r 

1650 

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

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

1653 ''' 

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

1655 RESIDUAL=self._RESIDUAL) 

1656 t = t.replace(_COMMASPACE_R_, _exceeds_R_) 

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

1658 

1659 def signOf(self, res=True): 

1660 '''Determine the sign of this instance. 

1661 

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

1663 ignore the residual (C{bool}). 

1664 

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

1666 ''' 

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

1668 return _signOf(s, -r) 

1669 

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

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

1672 

1673 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1677 

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

1679 ''' 

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

1681 

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

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

1684 

1685 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1689 

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

1691 ''' 

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

1693 

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

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

1696 ''' 

1697 n = self.named3 

1698 if lenc: 

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

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

1701 

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

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

1704 ''' 

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

1706 

1707 def _update(self): # see ._fset 

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

1709 ''' 

1710 Fsum._fint2._update(self) 

1711 Fsum._fprs ._update(self) 

1712 Fsum._fprs2._update(self) 

1713 return self 

1714 

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

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

1717 ''' 

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

1719 

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

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

1722 ''' 

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

1724 

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

1726 

1727 

1728def _Float_Int(arg, **name_Error): 

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

1730 ''' 

1731 U = Int if isint(arg) else Float 

1732 return U(arg, **name_Error) 

1733 

1734 

1735class Fsum2Tuple(_NamedTuple): 

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

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

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

1739 

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

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

1742 ''' 

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

1744 _Units_ = (_Float_Int, _Float_Int) 

1745 

1746 @Property_RO 

1747 def Fsum(self): 

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

1749 ''' 

1750 f = Fsum(name=self.name) 

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

1752 

1753 def is_exact(self): 

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

1755 ''' 

1756 return self.Fsum.is_exact() 

1757 

1758 def is_integer(self): 

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

1760 ''' 

1761 return self.Fsum.is_integer() 

1762 

1763 

1764class ResidualError(_ValueError): 

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

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

1767 

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

1769 ''' 

1770 pass 

1771 

1772 

1773try: 

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

1775 

1776 # make sure _fsum works as expected (XXX check 

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

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

1779 del _fsum # nope, remove _fsum ... 

1780 raise ImportError # ... use _fsum below 

1781 

1782 Fsum._math_fsum = _sum = _fsum # PYCHOK exported 

1783 

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

1785 _psum = _fsum # PYCHOK redef 

1786 

1787except ImportError: 

1788 _sum = sum # Fsum(NAN) exception fall-back 

1789 

1790 def _fsum(xs): 

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

1792 ''' 

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

1794 

1795 

1796def fsum(xs, floats=False): 

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

1798 

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

1800 L{Fsum} instances). 

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

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

1803 

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

1805 

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

1807 

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

1809 

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

1811 

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

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

1814 

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

1816 ''' 

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

1818 

1819 

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

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

1822 

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

1824 all positional. 

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

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

1827 

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

1829 

1830 @see: Function C{fsum}. 

1831 ''' 

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

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

1834 

1835 

1836def fsumf_(*xs): 

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

1838 ''' 

1839 return _fsum(xs) if xs else _0_0 

1840 

1841 

1842def fsum1(xs, floats=False): 

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

1844 

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

1846 L{Fsum} instances). 

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

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

1849 

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

1851 

1852 @see: Function C{fsum}. 

1853 ''' 

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

1855 

1856 

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

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

1859 

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

1861 all positional. 

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

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

1864 

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

1866 

1867 @see: Function C{fsum} 

1868 ''' 

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

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

1871 

1872 

1873def fsum1f_(*xs): 

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

1875 ''' 

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

1877 

1878 

1879# **) MIT License 

1880# 

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

1882# 

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

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

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

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

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

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

1889# 

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

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

1892# 

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

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

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

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

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

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

1899# OTHER DEALINGS IN THE SOFTWARE.