Coverage for pygeodesy/fsums.py: 97%

705 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-02-12 13:15 -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, signOf, _signOf, \ 

30 _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 itemsorted, _OverflowError, _TypeError, \ 

34 _ValueError, _xError2, _xkwds_get, _xkwds_get_, \ 

35 _ZeroDivisionError 

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

37 _exceeds_, _from_, _iadd_op_, _LANGLE_, \ 

38 _negative_, _NOTEQUAL_, _not_finite_, \ 

39 _not_scalar_, _PERCENT_, _PLUS_, _R_, _RANGLE_, \ 

40 _SLASH_, _SPACE_, _STAR_, _UNDER_ 

41from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2 

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

43from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \ 

44 Property_RO, property_RO 

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

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

47 

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

49 

50__all__ = _ALL_LAZY.fsums 

51__version__ = '24.02.10' 

52 

53_add_op_ = _PLUS_ # in .auxilats.auxAngle 

54_eq_op_ = _EQUAL_ * 2 # _DEQUAL_ 

55_COMMASPACE_R_ = _COMMASPACE_ + _R_ 

56_exceeds_R_ = _SPACE_ + _exceeds_(_R_) 

57_floordiv_op_ = _SLASH_ * 2 # _DSLASH_ 

58_fset_op_ = _EQUAL_ 

59_ge_op_ = _RANGLE_ + _EQUAL_ 

60_gt_op_ = _RANGLE_ 

61_integer_ = 'integer' 

62_le_op_ = _LANGLE_ + _EQUAL_ 

63_lt_op_ = _LANGLE_ 

64_mod_op_ = _PERCENT_ 

65_mul_op_ = _STAR_ 

66_ne_op_ = _NOTEQUAL_ 

67_non_zero_ = 'non-zero' 

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

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

70_truediv_op_ = _SLASH_ 

71_divmod_op_ = _floordiv_op_ + _mod_op_ 

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

73 

74 

75def _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 _xisscalar(power=power) 

119 try: 

120 i, x = origin, None 

121 _fin = _isfinite 

122 _Fsum = Fsum 

123 _pow = pow # XXX math.pow 

124 for x in xs: 

125 if isinstance(x, _Fsum): 

126 P = x.pow(power) 

127 for p in P._ps: 

128 yield p 

129 else: 

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

131 if not _fin(p): 

132 raise ValueError(_not_finite_) 

133 yield p 

134 i += 1 

135 except Exception as e: 

136 E, t = _xError2(e) 

137 n = Fmt.SQUARE(xs=i) 

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

139 

140 

141def _1primed(xs): 

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

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

144 ''' 

145 yield _1_0 

146 for x in xs: 

147 if x: 

148 yield x 

149 yield _N_1_0 

150 

151 

152def _psum(ps): # PYCHOK used! 

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

154 ''' 

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

156 s = ps[i] 

157 _2s = _2sum 

158 while i > 0: 

159 i -= 1 

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

161 if r: # sum(ps) became inexact 

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

163 if i > 0: 

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

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

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

167 r *= 2 

168 t = s + r 

169 if r == (t - s): 

170 s = t 

171 break 

172 ps[i:] = [s] 

173 return s 

174 

175 

176def _2scalar(other, _raiser=None): 

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

178 ''' 

179 if isinstance(other, Fsum): 

180 s, r = other._fint2 

181 if r: 

182 s, r = other._fprs2 

183 if r: # PYCHOK no cover 

184 if _raiser and _raiser(r, s): 

185 raise ValueError(_stresidual(_non_zero_, r)) 

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

187 else: 

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

189 if isint(s, both=True): 

190 s = int(s) 

191 return s 

192 

193 

194def _strcomplex(s, *args): 

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

196 ''' 

197 c = iscomplex.__name__[2:] 

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

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

200 return unstr(t, *args) 

201 

202 

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

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

205 ''' 

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

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

208 for n, v in itemsorted(name_values): 

209 n = n.replace(_UNDER_, _SPACE_) 

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

211 t = _COMMASPACE_(t, p) 

212 return t 

213 

214 

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

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

217 ''' 

218 s = a + b 

219 if not _isfinite(s): 

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

221 t = Fmt.PARENSPACED(_not_finite_, s) 

222 raise _OverflowError(u, txt=t) 

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

224 a, b = b, a 

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

226 

227 

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

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

230 

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

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

233 intermediate, I{running} summuation. 

234 

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

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

237 method C{__float__}. 

238 

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

240 Python's C{math.fsum}. 

241 

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

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

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

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

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

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

248 ''' 

249 _math_fsum = None 

250 _n = 0 

251# _ps = [] # partial sums 

252# _px = 0 

253 _ratio = None 

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

255 

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

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

258 

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

260 L{Fsum} instance). 

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

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

263 L{ResidualError} threshold. 

264 

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

266 ''' 

267 if name_RESIDUAL: 

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

269 if n: # set name ... 

270 self.name = n 

271 if r is not None: 

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

273# self._n = 0 

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

275 if len(xs) > 1: 

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

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

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

279 self._n = 1 

280 

281 def __abs__(self): 

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

283 ''' 

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

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

286 self._copy_2(self.__abs__) 

287 

288 def __add__(self, other): 

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

290 

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

292 

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

294 

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

296 ''' 

297 f = self._copy_2(self.__add__) 

298 return f._fadd(other, _add_op_) 

299 

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

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

302 ''' 

303 s, r = self._fprs2 

304 return bool(s or r) and s != -r # == 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 C{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 _signOf(s, 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 C{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 C{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 C{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_op_) 

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", O'Reilly, 2nd Ed, 2022 p. 567 

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, _isub_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 C{scalar}. 

549 ''' 

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

551 

552 def __len__(self): 

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

554 ''' 

555 return self._n 

556 

557 def __lt__(self, other): 

558 '''Compare this with an other instance or C{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 C{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): # PYCHOK no cover 

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

657 

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

659 ''' 

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

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

662 f._n = 1 

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

664 return f 

665 

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

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

668 

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

670 ''' 

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

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

673 

674 def __rsub__(self, other): 

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

676 

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

678 ''' 

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

680 return f._fsub(self, _sub_op_) 

681 

682 def __rtruediv__(self, other): 

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

684 

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

686 ''' 

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

688 return f._ftruediv(self, _truediv_op_) 

689 

690 def __str__(self): 

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

692 ''' 

693 return self.toStr(lenc=True) 

694 

695 def __sub__(self, other): 

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

697 

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

699 

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

701 

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

703 ''' 

704 f = self._copy_2(self.__sub__) 

705 return f._fsub(other, _sub_op_) 

706 

707 def __truediv__(self, other): 

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

709 

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

711 

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

713 

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

715 ''' 

716 f = self._copy_2(self.__truediv__) 

717 return f._ftruediv(other, _truediv_op_) 

718 

719 __trunc__ = __int__ 

720 

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

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

723 __div__ = __truediv__ 

724 __idiv__ = __itruediv__ 

725 __long__ = __int__ 

726 __nonzero__ = __bool__ 

727 __rdiv__ = __rtruediv__ 

728 

729 def as_integer_ratio(self): 

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

731 

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

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

734 

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

736 ''' 

737 n, r = self._fint2 

738 if r: 

739 i, d = r.as_integer_ratio() 

740 n *= d 

741 n += i 

742 else: # PYCHOK no cover 

743 d = 1 

744 return n, d 

745 

746 @property_RO 

747 def ceil(self): 

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

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

750 

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

752 

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

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

755 ''' 

756 s, r = self._fprs2 

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

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

759 c += 1 

760 return c 

761 

762 def _cmp_0(self, other, op): 

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

764 ''' 

765 if isscalar(other): 

766 if other: 

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

768 else: 

769 s, r = self._fprs2 

770 s = _signOf(s, -r) 

771 elif isinstance(other, Fsum): 

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

773 else: 

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

775 return s 

776 

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

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

779 

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

781 ''' 

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

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

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

785 return f 

786 

787 def _copy_0(self, *xs): 

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

789 ''' 

790 # for x in xs: 

791 # assert isscalar(x) 

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

793 if self.name: 

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

795 return f 

796 

797 def _copy_2(self, which): 

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

799 ''' 

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

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

802 # assert f._n == self._n 

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

804 return f 

805 

806 def _copy_n(self, which): 

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

808 ''' 

809 if self._ps: 

810 f = self._Fsum(self._n) 

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

812# f._facc_up(up=False) 

813 else: 

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

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

816 return f 

817 

818 def _copy_r2(self, other, which): 

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

820 ''' 

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

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

823 

824 def _copy_RESIDUAL(self, other): 

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

826 ''' 

827 R = other._RESIDUAL 

828 if R is not Fsum._RESIDUAL: 

829 self._RESIDUAL = R 

830 

831 def _copy_up(self, _fprs2=False): 

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

833 ''' 

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

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

836 Fsum._fprs2._update_from(f, self) 

837 return f 

838 

839 def divmod(self, other): 

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

841 remainder)}. 

842 

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

844 

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

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

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

848 

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

850 ''' 

851 f = self._copy_2(self.divmod) 

852 return f._fdivmod2(other, _divmod_op_) 

853 

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

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

856 ''' 

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

858 

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

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

861 ''' 

862 E, t = _xError2(X) 

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

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

865 

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

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

868 ''' 

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

870 for x in xs: # _iter() 

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

872 i = 0 

873 for p in ps: 

874 x, p = _2s(x, p) 

875 if p: 

876 ps[i] = p 

877 i += 1 

878 ps[i:] = [x] 

879 n += 1 

880 # assert self._ps is ps 

881 if n: 

882 self._n += n 

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

884 if up: 

885 self._update() 

886 return self 

887 

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

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

890 ''' 

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

892 

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

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

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

896# ''' 

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

898# p = self._ps.pop() 

899# if p: 

900# n = self._n 

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

902# self._n = n 

903# break 

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

905 

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

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

908 to this instance. 

909 

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

911 L{Fsum} instances). 

912 

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

914 

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

916 

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

918 nor L{Fsum}. 

919 

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

921 ''' 

922 if isinstance(xs, Fsum): 

923 self._facc(xs._ps) 

924 elif isscalar(xs): # for backward compatibility 

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

926 elif xs: 

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

928 return self 

929 

930 def fadd_(self, *xs): 

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

932 to this instance. 

933 

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

935 all positional. 

936 

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

938 

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

940 

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

942 nor L{Fsum}. 

943 

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

945 ''' 

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

947 

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

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

950 ''' 

951 if isinstance(other, Fsum): 

952 if other is self: 

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

954 elif other._ps: 

955 self._facc(other._ps) 

956 elif not isscalar(other): 

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

958 elif other: 

959 self._facc_(other) 

960 return self 

961 

962 fcopy = copy # for backward compatibility 

963 fdiv = __itruediv__ # for backward compatibility 

964 fdivmod = __divmod__ # for backward compatibility 

965 

966 def _fdivmod2(self, other, op): 

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

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

969 ''' 

970 # result mostly follows CPython function U{float_divmod 

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

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

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

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

975 self -= other * q 

976 

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

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

979 self += other 

980 q -= 1 

981 

982# t = self.signOf() 

983# if t and t != s: 

984# from pygeodesy.errors import _AssertionError 

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

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

987 

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

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

990 ''' 

991 if _isfinite(other): 

992 return other 

993 raise ValueError(_not_finite_) if not op else \ 

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

995 

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

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

998 

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

1000 I{integer} residual is non-zero. 

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

1002 

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

1004 

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

1006 

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

1008 ''' 

1009 i, r = self._fint2 

1010 if r and raiser: 

1011 t = _stresidual(_integer_, r) 

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

1013 n = name or self.fint.__name__ 

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

1015 

1016 def fint2(self, **name): 

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

1018 the I{integer} residual. 

1019 

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

1021 

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

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

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

1025 ''' 

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

1027 

1028 @Property_RO 

1029 def _fint2(self): # see ._fset 

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

1031 ''' 

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

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

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

1035 return i, (r or INT0) 

1036 

1037 @deprecated_property_RO 

1038 def float_int(self): # PYCHOK no cover 

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

1040 return self.int_float() # raiser=False 

1041 

1042 @property_RO 

1043 def floor(self): 

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

1045 C{float} in Python 2-). 

1046 

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

1048 

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

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

1051 ''' 

1052 s, r = self._fprs2 

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

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

1055 f -= 1 

1056 return f 

1057 

1058# floordiv = __floordiv__ # for naming consistency 

1059 

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

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

1062 ''' 

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

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

1065 

1066 fmul = __imul__ # for backward compatibility 

1067 

1068 def _fmul(self, other, op): 

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

1070 ''' 

1071 if isscalar(other): 

1072 f = self._mul_scalar(other, op) 

1073 elif not isinstance(other, Fsum): 

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

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

1076 f = self._mul_Fsum(other, op) 

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

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

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

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

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

1082 return self._fset(f) 

1083 

1084 def fover(self, over): 

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

1086 

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

1088 

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

1090 

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

1092 ''' 

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

1094 

1095 fpow = __ipow__ # for backward compatibility 

1096 

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

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

1099 ''' 

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

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

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

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

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

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

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

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

1108 p = None 

1109 if isinstance(other, Fsum): 

1110 x, r = other._fprs2 

1111 if r: 

1112 if self._raiser(r, x): 

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

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

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

1116 elif not isscalar(other): 

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

1118 else: 

1119 x = self._finite(other, op) 

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

1121 if p is not None: 

1122 s *= p 

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

1124 

1125 @Property_RO 

1126 def _fprs(self): 

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

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

1129 

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

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

1132 ''' 

1133 ps = self._ps 

1134 n = len(ps) - 1 

1135 if n > 1: 

1136 s = _psum(ps) 

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

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

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

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

1141 s = _0_0 

1142 ps[:] = [s] 

1143 else: # len(ps) == 1 

1144 s = ps[0] 

1145 # assert self._ps is ps 

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

1147 return s 

1148 

1149 @Property_RO 

1150 def _fprs2(self): 

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

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

1153 ''' 

1154 s = self._fprs 

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

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

1157 

1158# def _fpsqz(self): 

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

1160# ''' 

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

1162# _ = self._fprs 

1163# return self 

1164 

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

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

1167 ''' 

1168 if other is self: 

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

1170 elif isinstance(other, Fsum): 

1171 self._n = other._n 

1172 self._ps[:] = other._ps 

1173 self._copy_RESIDUAL(other) 

1174 # use or zap the C{Property_RO} values 

1175 Fsum._fint2._update_from(self, other) 

1176 Fsum._fprs ._update_from(self, other) 

1177 Fsum._fprs2._update_from(self, other) 

1178 elif isscalar(other): 

1179 s = other if asis else float(other) 

1180 i = int(s) # see ._fint2 

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

1182 self._n = n 

1183 self._ps[:] = [s] 

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

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

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

1187 else: # PYCHOK no cover 

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

1189 return self 

1190 

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

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

1193 from this instance. 

1194 

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

1196 or L{Fsum} instances). 

1197 

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

1199 

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

1201 ''' 

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

1203 

1204 def fsub_(self, *xs): 

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

1206 from this instance. 

1207 

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

1209 L{Fsum} instances), all positional. 

1210 

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

1212 

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

1214 ''' 

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

1216 

1217 def _fsub(self, other, op): 

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

1219 ''' 

1220 if isinstance(other, Fsum): 

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

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

1223 elif other._ps: 

1224 self._facc(other._ps_n()) 

1225 elif not isscalar(other): 

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

1227 elif self._finite(other, op): 

1228 self._facc_(-other) 

1229 return self 

1230 

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

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

1233 ''' 

1234 f = Fsum() 

1235 f._n = n 

1236 if ps: 

1237 f._ps[:] = ps 

1238 f._copy_RESIDUAL(self) 

1239 return f 

1240 

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

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

1243 

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

1245 L{Fsum} instances). 

1246 

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

1248 

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

1250 

1251 @note: Accumulation can continue after summation. 

1252 ''' 

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

1254 return f._fprs 

1255 

1256 def fsum_(self, *xs): 

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

1258 

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

1260 all positional. 

1261 

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

1263 

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

1265 ''' 

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

1267 return f._fprs 

1268 

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

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

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

1272 

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

1274 L{Fsum} instances). 

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

1276 

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

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

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

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

1281 to be I{exact}. 

1282 

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

1284 ''' 

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

1286 t = f._fprs2 

1287 if name: 

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

1289 return t 

1290 

1291 def fsum2_(self, *xs): 

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

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

1294 

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

1296 all positional. 

1297 

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

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

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

1301 

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

1303 ''' 

1304 p, r = self._fprs2 

1305 if xs: 

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

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

1308 else: # PYCHOK no cover 

1309 return p, _0_0 

1310 

1311 def fsumf_(self, *xs): 

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

1313 ''' 

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

1315 return f._fprs 

1316 

1317# ftruediv = __itruediv__ # for naming consistency 

1318 

1319 def _ftruediv(self, other, op): 

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

1321 ''' 

1322 n = _1_0 

1323 if isinstance(other, Fsum): 

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

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

1326 d, r = other._fprs2 

1327 if r: 

1328 if not d: # PYCHOK no cover 

1329 d = r 

1330 elif self._raiser(r, d): 

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

1332 else: 

1333 d, n = other.as_integer_ratio() 

1334 elif isscalar(other): 

1335 d = other 

1336 else: # PYCHOK no cover 

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

1338 try: 

1339 s = 0 if isinf(d) else ( 

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

1341 except Exception as x: 

1342 E, t = _xError2(x) 

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

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

1345 return self._fset(f) 

1346 

1347 @property_RO 

1348 def imag(self): 

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

1350 

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

1352 ''' 

1353 return _0_0 

1354 

1355 def int_float(self, raiser=False): 

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

1357 

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

1359 residual is non-zero. 

1360 

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

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

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

1364 

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

1366 

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

1368 ''' 

1369 s, r = self._fint2 

1370 if r: 

1371 s, r = self._fprs2 

1372 if r and raiser: # PYCHOK no cover 

1373 t = _stresidual(_non_zero_, r) 

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

1375 s = float(s) # redundant 

1376 return s 

1377 

1378 def is_exact(self): 

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

1380 be exact? (C{bool}). 

1381 ''' 

1382 return self.residual is INT0 

1383 

1384 def is_integer(self): 

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

1386 

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

1388 ''' 

1389 _, r = self._fint2 

1390 return False if r else True 

1391 

1392 def is_math_fsum(self): 

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

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

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

1396 

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

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

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

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

1401 none are. 

1402 ''' 

1403 f = Fsum._math_fsum 

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

1405 

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

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

1408 ''' 

1409 # assert isinstance(other, Fsum) 

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

1411 

1412 def _mul_scalar(self, factor, op): 

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

1414 ''' 

1415 # assert isscalar(factor) 

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

1417 if factor == _1_0: 

1418 return self 

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

1420 else: 

1421 f = self._copy_0(_0_0) 

1422 return f 

1423 

1424 @property_RO 

1425 def partials(self): 

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

1427 ''' 

1428 return tuple(self._ps) 

1429 

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

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

1432 

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

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

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

1436 

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

1438 result (L{Fsum}). 

1439 

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

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

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

1443 

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

1445 ''' 

1446 f = self._copy_2(self.pow) 

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

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

1449 else: 

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

1451 return f 

1452 

1453 def _pow_0_1(self, x, other): 

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

1455 ''' 

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

1457 

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

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

1460 ''' 

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

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

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

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

1465 if not iscomplex(s): 

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

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

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

1469 except Exception as x: 

1470 E, t = _xError2(x) 

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

1472 

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

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

1475 ''' 

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

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

1478 t = _non_zero_ if mod is None else _integer_ 

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

1480 else: 

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

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

1483 s = pow(b, x, mod) 

1484 if not iscomplex(s): 

1485 return self._finite(s) 

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

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

1488 except Exception as x: 

1489 E, t = _xError2(x) 

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

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

1492 

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

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

1495 ''' 

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

1497 if len(self._ps) > 1: 

1498 if x > 2: 

1499 p = self._copy_up() 

1500 m = 1 # single-bit mask 

1501 if x & m: 

1502 x -= m # x ^= m 

1503 f = p._copy_up() 

1504 else: 

1505 f = self._copy_0(_1_0) 

1506 while x: 

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

1508 m += m # m <<= 1 

1509 if x & m: 

1510 x -= m # x ^= m 

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

1512 elif x > 1: # self**2 

1513 f = self._mul_Fsum(self, op) 

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

1515 f = self._pow_0_1(x, other) 

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

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

1518 else: # PYCHOK no cover 

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

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

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

1522 

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

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

1525 ''' 

1526 s, r = self._fprs2 

1527 if isint(x, both=True): 

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

1529 y = abs(x) 

1530 if y > 1: 

1531 if r: 

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

1533 if x > 0: # > 1 

1534 return f 

1535 # assert x < 0 # < -1 

1536 s, r = f._fprs2 

1537 if r: 

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

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

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

1541 x = -1 

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

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

1544# if x < 0: 

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

1546# return f 

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

1548 if r: 

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

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

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

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

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

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

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

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

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

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

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

1560 

1561 def _ps_1(self, *less): 

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

1563 ''' 

1564 yield _1_0 

1565 for p in self._ps: 

1566 if p: 

1567 yield p 

1568 for p in less: 

1569 if p: 

1570 yield -p 

1571 yield _N_1_0 

1572 

1573 def _ps_n(self): 

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

1575 ''' 

1576 for p in self._ps: 

1577 if p: 

1578 yield -p 

1579 

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

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

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

1583 ''' 

1584 ps = self._ps 

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

1586 ps, factors = factors, ps 

1587 _f = _isfinite 

1588 for f in factors: 

1589 for p in ps: 

1590 p *= f 

1591 if _f(p): 

1592 yield p 

1593 else: # PYCHOK no cover 

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

1595 

1596 @property_RO 

1597 def real(self): 

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

1599 

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

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

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

1603 ''' 

1604 return float(self._fprs) 

1605 

1606 @property_RO 

1607 def residual(self): 

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

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

1610 

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

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

1613 

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

1615 ''' 

1616 return self._fprs2.residual 

1617 

1618 def _raiser(self, r, s): 

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

1620 ''' 

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

1622 return t > self._RESIDUAL 

1623 

1624 def RESIDUAL(self, *threshold): 

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

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

1627 

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

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

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

1631 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

1632 current setting. 

1633 

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

1635 

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

1637 

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

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

1640 ''' 

1641 r = self._RESIDUAL 

1642 if threshold: 

1643 t = threshold[0] 

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

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

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

1647 if t < 0: 

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

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

1650 self._RESIDUAL = t 

1651 return r 

1652 

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

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

1655 ''' 

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

1657 RESIDUAL=self._RESIDUAL) 

1658 t = t.replace(_COMMASPACE_R_, _exceeds_R_) 

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

1660 

1661 def signOf(self, res=True): 

1662 '''Determine the sign of this instance. 

1663 

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

1665 ignore the residual (C{bool}). 

1666 

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

1668 ''' 

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

1670 return _signOf(s, -r) 

1671 

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

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

1674 

1675 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1679 

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

1681 ''' 

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

1683 

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

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

1686 

1687 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for 

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

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

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

1691 

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

1693 ''' 

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

1695 

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

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

1698 ''' 

1699 n = self.named3 

1700 if lenc: 

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

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

1703 

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

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

1706 ''' 

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

1708 

1709 def _update(self): # see ._fset 

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

1711 ''' 

1712 Fsum._fint2._update(self) 

1713 Fsum._fprs ._update(self) 

1714 Fsum._fprs2._update(self) 

1715 return self 

1716 

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

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

1719 ''' 

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

1721 

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

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

1724 ''' 

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

1726 

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

1728 

1729 

1730def _Float_Int(arg, **name_Error): 

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

1732 ''' 

1733 U = Int if isint(arg) else Float 

1734 return U(arg, **name_Error) 

1735 

1736 

1737class Fsum2Tuple(_NamedTuple): 

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

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

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

1741 

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

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

1744 ''' 

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

1746 _Units_ = (_Float_Int, _Float_Int) 

1747 

1748 @Property_RO 

1749 def Fsum(self): 

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

1751 ''' 

1752 f = Fsum(name=self.name) 

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

1754 

1755 def is_exact(self): 

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

1757 ''' 

1758 return self.Fsum.is_exact() 

1759 

1760 def is_integer(self): 

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

1762 ''' 

1763 return self.Fsum.is_integer() 

1764 

1765 

1766class ResidualError(_ValueError): 

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

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

1769 

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

1771 ''' 

1772 pass 

1773 

1774 

1775try: 

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

1777 

1778 # make sure _fsum works as expected (XXX check 

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

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

1781 del _fsum # nope, remove _fsum ... 

1782 raise ImportError # ... use _fsum below 

1783 

1784 Fsum._math_fsum = _sum = _fsum # PYCHOK exported 

1785 

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

1787 _psum = _fsum # PYCHOK redef 

1788 

1789except ImportError: 

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

1791 

1792 def _fsum(xs): 

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

1794 ''' 

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

1796 

1797 

1798def fsum(xs, floats=False): 

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

1800 

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

1802 L{Fsum} instances). 

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

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

1805 

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

1807 

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

1809 

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

1811 

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

1813 

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

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

1816 

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

1818 ''' 

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

1820 

1821 

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

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

1824 

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

1826 all positional. 

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

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

1829 

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

1831 

1832 @see: Function C{fsum}. 

1833 ''' 

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

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

1836 

1837 

1838def fsumf_(*xs): 

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

1840 ''' 

1841 return _fsum(xs) if xs else _0_0 

1842 

1843 

1844def fsum1(xs, floats=False): 

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

1846 

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

1848 L{Fsum} instances). 

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

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

1851 

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

1853 

1854 @see: Function C{fsum}. 

1855 ''' 

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

1857 

1858 

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

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

1861 

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

1863 all positional. 

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

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

1866 

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

1868 

1869 @see: Function C{fsum} 

1870 ''' 

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

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

1873 

1874 

1875def fsum1f_(*xs): 

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

1877 ''' 

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

1879 

1880 

1881# **) MIT License 

1882# 

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

1884# 

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

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

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

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

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

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

1891# 

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

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

1894# 

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

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

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

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

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

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

1901# OTHER DEALINGS IN THE SOFTWARE.