Coverage for pygeodesy/fsums.py: 95%

1096 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-09 12:50 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Class L{Fsum} for precision floating point summation similar to 

5Python's C{math.fsum} enhanced with I{running} summation and as an 

6option, accurate I{TwoProduct} multiplication. 

7 

8Accurate multiplication is based on the C{math.fma} function for 

9Python 3.13 and newer or one of two equivalent C{fma} implementations 

10for Python 3.12 and older. To enable accurate multiplication, set 

11env variable C{PYGEODESY_FSUM_F2PRODUCT} to C{"std"} or any non-empty 

12string or invoke function C{pygeodesy.f2product(True)} or set. With 

13C{"std"} the C{fma} implemention follows the C{math.fma} function, 

14otherwise the C{PyGeodesy 24.09.09} release. 

15 

16Generally, an L{Fsum} instance is considered a C{float} plus a small or 

17zero C{residue} aka C{residual} value, see property L{Fsum.residual}. 

18 

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

20than C{"0.0"} as the threshold to throw a L{ResidualError} for a division, 

21power or root operation of an L{Fsum} with a C{residual} I{ratio} exceeding 

22the threshold. See methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__} 

23and L{Fsum.__itruediv__}. 

24 

25There are several C{integer} L{Fsum} cases, for example the result from 

26functions C{ceil}, C{floor}, C{Fsum.__floordiv__} and methods L{Fsum.fint}, 

27L{Fsum.fint2} and L{Fsum.is_integer}. Also, L{Fsum} methods L{Fsum.pow}, 

28L{Fsum.__ipow__}, L{Fsum.__pow__} and L{Fsum.__rpow__} return a (very long) 

29C{int} if invoked with optional argument C{mod} set to C{None}. The 

30C{residual} of an C{integer} L{Fsum} is between C{-1.0} and C{+1.0} and 

31will be C{INT0} if that is considered to be I{exact}. 

32 

33Set env variable C{PYGEODESY_FSUM_NONFINITES} to C{"std"} or use function 

34C{pygeodesy.nonfiniterrors(False)} to allow I{non-finite} C{float}s like 

35C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} and to ignore C{OverflowError} 

36respectively C{ValueError} exceptions. However, in that case I{non-finite} 

37results may differ from Python's C{math.fsum} results. 

38''' 

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

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

41 

42from pygeodesy.basics import isbool, iscomplex, isint, isscalar, \ 

43 _signOf, itemsorted, signOf, _xiterable 

44from pygeodesy.constants import INF, INT0, MANT_DIG, NEG0, NINF, _0_0, \ 

45 _1_0, _N_1_0, _isfinite, _pos_self, \ 

46 Float, Int 

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

48 _ValueError, _xError, _xError2, _xkwds, \ 

49 _xkwds_get, _xkwds_get1, _xkwds_not, \ 

50 _xkwds_pop, _xsError 

51from pygeodesy.internals import _enquote, _passarg 

52from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DOT_, _from_, \ 

53 _not_finite_, _SPACE_, _std_, _UNDER_ 

54from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2 

55from pygeodesy.named import _name__, _name2__, _Named, _NamedTuple, \ 

56 _NotImplemented 

57from pygeodesy.props import _allPropertiesOf_n, deprecated_method, \ 

58 deprecated_property_RO, Property, \ 

59 Property_RO, property_RO 

60from pygeodesy.streprs import Fmt, fstr, unstr 

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

62 

63from math import fabs, isinf, isnan, \ 

64 ceil as _ceil, floor as _floor # PYCHOK used! .ltp 

65 

66__all__ = _ALL_LAZY.fsums 

67__version__ = '24.10.09' 

68 

69from pygeodesy.interns import ( 

70 _PLUS_ as _add_op_, # in .auxilats.auxAngle 

71 _EQUAL_ as _fset_op_, 

72 _RANGLE_ as _gt_op_, 

73 _LANGLE_ as _lt_op_, 

74 _PERCENT_ as _mod_op_, 

75 _STAR_ as _mul_op_, 

76 _NOTEQUAL_ as _ne_op_, 

77 _DASH_ as _sub_op_, # in .auxilats.auxAngle 

78 _SLASH_ as _truediv_op_ 

79) 

80_floordiv_op_ = _truediv_op_ * 2 # _DSLASH_ 

81_divmod_op_ = _floordiv_op_ + _mod_op_ 

82_F2PRODUCT = _getenv('PYGEODESY_FSUM_F2PRODUCT', NN) 

83_iadd_op_ = _add_op_ + _fset_op_ # in .auxilats.auxAngle, .fstats 

84_integer_ = 'integer' 

85_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle 

86_NONFINITEr = _0_0 # NOT INT0! 

87_NONFINITES = _getenv('PYGEODESY_FSUM_NONFINITES', NN) 

88_non_zero_ = 'non-zero' 

89_pow_op_ = _mul_op_ * 2 # _DSTAR_ 

90_RESIDUAL_0_0 = _getenv('PYGEODESY_FSUM_RESIDUAL', _0_0) 

91_significant_ = 'significant' 

92_threshold_ = 'threshold' 

93 

94 

95def _2finite(x, _isfine=_isfinite): # in .fstats 

96 '''(INTERNAL) return C{float(x)} if finite. 

97 ''' 

98 return (float(x) if _isfine(x) # and isscalar(x) 

99 else _nfError(x)) 

100 

101 

102def _2float(index=None, _isfine=_isfinite, **name_x): # in .fmath, .fstats 

103 '''(INTERNAL) Raise C{TypeError} or C{Overflow-/ValueError} if not finite. 

104 ''' 

105 n, x = name_x.popitem() # _xkwds_item2(name_x) 

106 try: 

107 f = float(x) 

108 return f if _isfine(f) else _nfError(x) 

109 except Exception as X: 

110 raise _xError(X, Fmt.INDEX(n, index), x) 

111 

112 

113try: # MCCABE 26 

114 from math import fma as _fma 

115 

116 def _2products(x, ys, *zs): 

117 # yield(x * y for y in ys) + yield(z in zs) 

118 # TwoProductFMA U{Algorithm 3.5 

119 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} 

120 for y in ys: 

121 f = x * y 

122 yield f 

123 if _isfinite(f): 

124 yield _fma(x, y, -f) 

125 for z in zs: 

126 yield z 

127 

128# _2split3 = \ 

129 _2split3s = _passarg # in Fsum.is_math_fma 

130 

131except ImportError: # PYCHOK DSPACE! Python 3.12- 

132 

133 if _F2PRODUCT and _F2PRODUCT != _std_: 

134 # backward to PyGeodesy 24.09.09, with _fmaX 

135 

136 def _fma(*a_b_c): # PYCHOK no cover 

137 # mimick C{math.fma} from Python 3.13+, 

138 # the same accuracy, but ~14x slower 

139 (na, da), (nb, db), (nc, dc) = map(_2n_d, a_b_c) 

140 n = na * nb * dc 

141 n += da * db * nc 

142 d = da * db * dc 

143 try: 

144 n, d = _n_d2(n, d) 

145 r = float(n / d) 

146 except OverflowError: # "integer division result too large ..." 

147 r = NINF if (_signOf(n, 0) * _signOf(d, 0)) < 0 else INF 

148 return r if _isfinite(r) else _fmaX(r, *a_b_c) # "overflow in fma" 

149 

150 def _2n_d(x): # PYCHOK no cover 

151 try: # int.as_integer_ratio in 3.8+ 

152 return x.as_integer_ratio() 

153 except (AttributeError, OverflowError, TypeError, ValueError): 

154 return (x if isint(x) else float(x)), 1 

155 else: 

156 

157 def _fma(a, b, c): # PYCHOK redef 

158 # mimick C{math.fma} from Python 3.13+, 

159 # the same accuracy, but ~13x slower 

160 b3s = _2split3(b), # 1-tuple of 3-tuple 

161 r = _fsum(_2products(a, b3s, c)) 

162 return r if _isfinite(r) else _fmaX(r, a, b, c) 

163 

164 _2n_d = None # redef 

165 

166 def _fmaX(r, *a_b_c): # like Python 3.13+ I{Modules/mathmodule.c}: 

167 # raise a ValueError for a NAN result from non-NAN C{a_b_c}s or an 

168 # OverflowError for a non-NAN non-finite from all finite C{a_b_c}s. 

169 if isnan(r): 

170 def _x(x): 

171 return not isnan(x) 

172 else: # non-NAN non-finite 

173 _x = _isfinite 

174 if all(map(_x, a_b_c)): 

175 raise _nfError(r, unstr(_fma, *a_b_c)) 

176 return r 

177 

178 def _2products(x, y3s, *zs): # PYCHOK in _fma, ... 

179 # yield(x * y3 for y3 in y3s) + yield(z in zs) 

180 # TwoProduct U{Algorithm 3.3 

181 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} 

182 # also in Python 3.13+ C{Modules/mathmodule.c} under 

183 # #ifndef UNRELIABLE_FMA ... #else ... #endif 

184 _, a, b = _2split3(x) 

185 for y, c, d in y3s: 

186 y *= x 

187 yield y 

188 if _isfinite(y): 

189 # yield b * d - (((y - a * c) - b * c) - a * d) 

190 # = b * d + (a * d - ((y - a * c) - b * c)) 

191 # = b * d + (a * d + (b * c - (y - a * c))) 

192 # = b * d + (a * d + (b * c + (a * c - y))) 

193 yield a * c - y 

194 yield b * c 

195 if d: 

196 yield a * d 

197 yield b * d 

198 for z in zs: 

199 yield z 

200 

201 _2FACTOR = pow(2, (MANT_DIG + 1) // 2) + _1_0 # 134217729 if MANT_DIG == 53 

202 

203 def _2split3(x): 

204 # Split U{Algorithm 3.2 

205 # <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} 

206 a = c = x * _2FACTOR 

207 a -= c - x 

208 b = x - a 

209 return x, a, b 

210 

211 def _2split3s(xs): # in Fsum.is_math_fma 

212 return map(_2split3, xs) 

213 

214 

215def f2product(*two): 

216 '''Turn accurate I{TwoProduct} multiplication on or off. 

217 

218 @arg two: If C{True}, turn I{TwoProduct} on, if C{False} off or 

219 if C{None} or omitted, keep the current setting. 

220 

221 @return: The previous setting (C{bool}). 

222 

223 @see: I{TwoProduct} multiplication is based on the I{TwoProductFMA} 

224 U{Algorithm 3.5 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} 

225 using function C{math.fma} from Python 3.13 and later or an 

226 equivalent, slower implementation when not available. 

227 ''' 

228 t = Fsum._f2product 

229 if two and two[0] is not None: 

230 Fsum._f2product = bool(two[0]) 

231 return t 

232 

233 

234def _Fsumf_(*xs): # in .auxLat, .ltp, ... 

235 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}. 

236 ''' 

237 return Fsum()._facc_scalarf(xs, up=False) 

238 

239 

240def _Fsum1f_(*xs): # in .albers 

241 '''(INTERNAL) An C{Fsum(xs)}, all C{scalar}, an L{Fsum} or L{Fsum2Tuple}, 1-primed. 

242 ''' 

243 return Fsum()._facc_scalarf(_1primed(xs), origin=-1, up=False) 

244 

245 

246def _halfeven(s, r, p): 

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

248 ''' 

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

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

251 r *= 2 

252 t = s + r 

253 if r == (t - s): 

254 s = t 

255 return s 

256 

257 

258def _isFsum(x): # in .fmath 

259 '''(INTERNAL) Is C{x} an C{Fsum} instance? 

260 ''' 

261 return isinstance(x, Fsum) 

262 

263 

264def _isFsum_2Tuple(x): # in .basics, .constants, .fmath, .fstats 

265 '''(INTERNAL) Is C{x} an C{Fsum} or C{Fsum2Tuple} instance? 

266 ''' 

267 return isinstance(x, _Fsum_2Tuple_types) 

268 

269 

270def _isOK(unused): 

271 '''(INTERNAL) Helper for C{Fsum._fsum2} and C{Fsum.nonfinites}. 

272 ''' 

273 return True 

274 

275 

276def _isOK_or_finite(x, _isfine=_isfinite): 

277 '''(INTERNAL) Is C{x} finite or is I{non-finite} OK? 

278 ''' 

279 # assert _isfine in (_isOK, _isfinite) 

280 return _isfine(x) # C{bool} 

281 

282 

283try: 

284 from math import gcd as _gcd 

285 

286 def _n_d2(n, d): 

287 '''(INTERNAL) Reduce C{n} and C{d} by C{gcd}. 

288 ''' 

289 if n and d: 

290 try: 

291 c = _gcd(n, d) 

292 if c > 1: 

293 n, d = (n // c), (d // c) 

294 except TypeError: # non-int float 

295 pass 

296 return n, d 

297 

298except ImportError: # 3.4- 

299 

300 def _n_d2(*n_d): # PYCHOK redef 

301 return n_d 

302 

303 

304def _nfError(x, *args): 

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

306 ''' 

307 E = _NonfiniteError(x) 

308 t = Fmt.PARENSPACED(_not_finite_, x) 

309 if args: # in _fmaX, _2sum 

310 return E(txt=t, *args) 

311 raise E(t, txt=None) 

312 

313 

314def _NonfiniteError(x): 

315 '''(INTERNAL) Return the Error class for C{x}, I{non-finite}. 

316 ''' 

317 return _OverflowError if isinf(x) else ( 

318 _ValueError if isnan(x) else _AssertionError) 

319 

320 

321def nonfiniterrors(*raiser): 

322 '''Throw C{OverflowError} and C{ValueError} exceptions for or 

323 handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, 

324 C{nan} and C{NAN} in summations and multiplications. 

325 

326 @arg raiser: If C{True}, throw exceptions, if C{False} handle 

327 I{non-finites} or if C{None} or omitted, leave 

328 the setting unchanged. 

329 

330 @return: Previous setting (C{bool}). 

331 

332 @note: C{inf}, C{INF} and C{NINF} throw an C{OverflowError}, 

333 C{nan} and C{NAN} a C{ValueError}. 

334 ''' 

335 d = Fsum._isfine 

336 if raiser and raiser[0] is not None: 

337 Fsum._isfine = {} if bool(raiser[0]) else Fsum._nonfinites_isfine_kwds[True] 

338 return (False if d is Fsum._nonfinites_isfine_kwds[True] else 

339 _xkwds_get1(d, _isfine=_isfinite) is _isfinite) if d else True 

340 

341 

342def _1primed(xs): # in .fmath 

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

344 items, all I{known} to be C{scalar}. 

345 ''' 

346 yield _1_0 

347 for x in xs: 

348 yield x 

349 yield _N_1_0 

350 

351 

352def _psum(ps, **_isfine): # PYCHOK used! 

353 '''(INTERNAL) Partials summation, updating C{ps}. 

354 ''' 

355 # assert isinstance(ps, list) 

356 i = len(ps) - 1 

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

358 while i > 0: 

359 i -= 1 

360 s, r = _2sum(s, ps[i], **_isfine) 

361 if r: # sum(ps) became inexact 

362 if s: 

363 ps[i:] = r, s 

364 if i > 0: 

365 s = _halfeven(s, r, ps[i-1]) 

366 break # return s 

367 s = r # PYCHOK no cover 

368 elif not _isfinite(s): # non-finite OK 

369 i = 0 # collapse ps 

370 if ps: 

371 s += sum(ps) 

372 ps[i:] = s, 

373 return s 

374 

375 

376def _Psum(ps, **name_f2product_nonfinites_RESIDUAL): 

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

378 ''' 

379 F = Fsum(**name_f2product_nonfinites_RESIDUAL) 

380 if ps: 

381 F._ps[:] = ps 

382 F._n = len(F._ps) 

383 return F 

384 

385 

386def _Psum_(*ps, **name_f2product_nonfinites_RESIDUAL): # in .fmath 

387 '''(INTERNAL) Return an C{Fsum} from I{known scalar} C{ps}. 

388 ''' 

389 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL) 

390 

391 

392def _residue(other): 

393 '''(INTERNAL) Return the C{residual} or C{None} for C{scalar}. 

394 ''' 

395 try: 

396 r = other.residual 

397 except AttributeError: 

398 r = None # float, int, other 

399 return r 

400 

401 

402def _s_r(s, r): 

403 '''(INTERNAL) Return C{(s, r)}, I{ordered}. 

404 ''' 

405 if _isfinite(s): 

406 if r: 

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

408 s, r = r, (s or INT0) 

409 else: 

410 r = INT0 

411 else: 

412 r = _NONFINITEr 

413 return s, r 

414 

415 

416def _2s_r(other): 

417 '''(INTERNAL) Return 2-tuple C{(other, r)} with C{other} as C{int}, 

418 C{float} or C{as-is} and C{r} the residual of C{as-is} or 0. 

419 ''' 

420 if _isFsum_2Tuple(other): 

421 s, r = other._fint2 

422 if r: 

423 s, r = other._nfprs2 

424 if r: # PYCHOK no cover 

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

426 else: 

427 r = 0 

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

429 if isint(s, both=True): 

430 s = int(s) 

431 return s, r 

432 

433 

434def _strcomplex(s, *args): 

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

436 ''' 

437 c = _strcomplex.__name__[4:] 

438 n = _sub_op_(len(args), _arg_) 

439 t = unstr(pow, *args) 

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

441 

442 

443def _stresidual(prefix, residual, R=0, **mod_ratio): 

444 '''(INTERNAL) Residual error txt C{str}. 

445 ''' 

446 p = _stresidual.__name__[3:] 

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

448 for n, v in itemsorted(mod_ratio): 

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

450 t = _COMMASPACE_(t, p) 

451 return _SPACE_(prefix, t, Fmt.exceeds_R(R), _threshold_) 

452 

453 

454def _2sum(a, b, _isfine=_isfinite): # in .testFmath 

455 '''(INTERNAL) Return C{a + b} as 2-tuple C{(sum, residual)} with finite C{sum}, 

456 otherwise as 2-tuple C{(nonfinite, 0)} iff I{non-finites} are OK. 

457 ''' 

458 # FastTwoSum U{Algorithm 1.1<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} 

459 

460 # Neumaier, A. U{Rundungsfehleranalyse einiger Verfahren zur Summation endlicher 

461 # Summen<https://OnlineLibrary.Wiley.com/doi/epdf/10.1002/zamm.19740540106>}, 

462 # 1974, Zeitschrift für Angewandte Mathmatik und Mechanik, vol 51, nr 1, p 39-51 

463 # <https://StackOverflow.com/questions/78633770/can-neumaier-summation-be-sped-up> 

464 s = a + b 

465 if _isfinite(s): 

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

467 r = (b - s) + a 

468 else: 

469 r = (a - s) + b 

470 elif _isfine(s): 

471 r = _NONFINITEr 

472 else: # non-finite and not OK 

473 t = unstr(_2sum, a, b) 

474 raise _nfError(s, t) 

475 return s, r 

476 

477 

478def _threshold(threshold=_0_0, **kwds): 

479 '''(INTERNAL) Get the L{ResidualError}s threshold, 

480 optionally from single kwds C{B{RESIDUAL}=scalar}. 

481 ''' 

482 if kwds: 

483 threshold = _xkwds_get1(kwds, RESIDUAL=threshold) 

484 try: 

485 return _2finite(threshold) # PYCHOK None 

486 except Exception as x: 

487 raise ResidualError(threshold=threshold, cause=x) 

488 

489 

490class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase, .fstats, ... 

491 '''Precision floating point summation, I{running} summation and accurate multiplication. 

492 

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

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

495 intermediate, I{running} summuation. 

496 

497 @note: Values may be L{Fsum}, L{Fsum2Tuple}, C{int}, C{float} or C{scalar} instances, 

498 i.e. any C{type} having method C{__float__}. 

499 

500 @note: Handling of I{non-finites} as C{inf}, C{INF}, C{NINF}, C{nan} and C{NAN} is 

501 determined by function L{nonfiniterrors<fsums.nonfiniterrors>} for the default 

502 and by method L{nonfinites<Fsum.nonfinites>} for individual C{Fsum} instances, 

503 overruling the default. For backward compatibility, I{non-finites} raise 

504 exceptions by default. 

505 

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

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

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

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

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

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

512 

513 @see: Method L{f2product<Fsum.f2product>} for details about accurate I{TwoProduct} 

514 multiplication. 

515 

516 @see: Module L{fsums<pygeodesy.fsums>} for env variables C{PYGEODESY_FSUM_F2PRODUCT}, 

517 C{PYGEODESY_FSUM_NONFINITES} and C{PYGEODESY_FSUM_RESIDUAL}. 

518 ''' 

519 _f2product = _sys_version_info2 > (3, 12) or bool(_F2PRODUCT) 

520 _isfine = {} # == _isfinite, see nonfiniterrors() 

521 _n = 0 

522# _ps = [] # partial sums 

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

524 _RESIDUAL = _threshold(_RESIDUAL_0_0) 

525 

526 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL): 

527 '''New L{Fsum}. 

528 

529 @arg xs: No, one or more initial items to accumulate (each C{scalar}, an 

530 L{Fsum} or L{Fsum2Tuple}), all positional. 

531 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str}) 

532 and settings C{B{f2product}=None} (C{bool}), C{B{nonfinites}=None} 

533 (C{bool}) and C{B{RESIDUAL}=0.0} threshold (C{scalar}) for this 

534 L{Fsum}. 

535 

536 @see: Methods L{Fsum.f2product}, L{Fsum.nonfinites}, L{Fsum.RESIDUAL}, 

537 L{Fsum.fadd} and L{Fsum.fadd_}. 

538 ''' 

539 if name_f2product_nonfinites_RESIDUAL: 

540 self._optionals(**name_f2product_nonfinites_RESIDUAL) 

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

542 if xs: 

543 self._facc_args(xs, up=False) 

544 

545 def __abs__(self): 

546 '''Return C{abs(self)} as an L{Fsum}. 

547 ''' 

548 s = self.signOf() # == self._cmp_0(0) 

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

550 

551 def __add__(self, other): 

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

553 

554 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}. 

555 

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

557 

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

559 ''' 

560 f = self._copy_2(self.__add__) 

561 return f._fadd(other) 

562 

563 def __bool__(self): # PYCHOK Python 3+ 

564 '''Return C{bool(B{self})}, C{True} iff C{residual} is zero. 

565 ''' 

566 s, r = self._nfprs2 

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

568 

569 def __call__(self, other, **up): # in .fmath 

570 '''Reset this C{Fsum} to C{other}, default C{B{up}=True}. 

571 ''' 

572 self._ps[:] = 0, # clear for errors 

573 self._fset(other, op=_fset_op_, **up) 

574 return self 

575 

576 

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

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

579 

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

581 

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

583 ''' 

584 return self.ceil 

585 

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

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

588 

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

590 

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

592 ''' 

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

594 return _signOf(s, 0) 

595 

596 def __divmod__(self, other, **raiser_RESIDUAL): 

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

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

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

600 

601 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus. 

602 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

603 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

604 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

605 

606 @raise ResidualError: Non-zero, significant residual or invalid 

607 B{C{RESIDUAL}}. 

608 

609 @see: Method L{Fsum.fdiv}. 

610 ''' 

611 f = self._copy_2(self.__divmod__) 

612 return f._fdivmod2(other, _divmod_op_, **raiser_RESIDUAL) 

613 

614 def __eq__(self, other): 

615 '''Return C{(B{self} == B{other})} as C{bool} where B{C{other}} 

616 is C{scalar}, an other L{Fsum} or L{Fsum2Tuple}. 

617 ''' 

618 return self._cmp_0(other, _fset_op_ + _fset_op_) == 0 

619 

620 def __float__(self): 

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

622 

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

624 ''' 

625 return float(self._fprs) 

626 

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

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

629 

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

631 

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

633 ''' 

634 return self.floor 

635 

636 def __floordiv__(self, other): 

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

638 

639 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

640 

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

642 

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

644 ''' 

645 f = self._copy_2(self.__floordiv__) 

646 return f._floordiv(other, _floordiv_op_) 

647 

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

649 '''Not implemented.''' 

650 return _NotImplemented(self, *other) 

651 

652 def __ge__(self, other): 

653 '''Return C{(B{self} >= B{other})}, see C{__eq__}. 

654 ''' 

655 return self._cmp_0(other, _gt_op_ + _fset_op_) >= 0 

656 

657 def __gt__(self, other): 

658 '''Return C{(B{self} > B{other})}, see C{__eq__}. 

659 ''' 

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

661 

662 def __hash__(self): # PYCHOK no cover 

663 '''Return C{hash(B{self})} as C{float}. 

664 ''' 

665 # @see: U{Notes for type implementors<https://docs.Python.org/ 

666 # 3/library/numbers.html#numbers.Rational>} 

667 return hash(self.partials) # tuple.__hash__() 

668 

669 def __iadd__(self, other): 

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

671 

672 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or 

673 an iterable of several of the former. 

674 

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

676 

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

678 C{scalar} nor L{Fsum}. 

679 

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

681 ''' 

682 try: 

683 return self._fadd(other, op=_iadd_op_) 

684 except TypeError: 

685 pass 

686 _xiterable(other) 

687 return self._facc(other) 

688 

689 def __ifloordiv__(self, other): 

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

691 

692 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

693 

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

695 

696 @raise ResidualError: Non-zero, significant residual 

697 in B{C{other}}. 

698 

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

700 

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

702 

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

704 

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

706 ''' 

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

708 

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

710 '''Not implemented.''' 

711 return _NotImplemented(self, other) 

712 

713 def __imod__(self, other): 

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

715 

716 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} modulus. 

717 

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

719 

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

721 ''' 

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

723 

724 def __imul__(self, other): 

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

726 

727 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} factor. 

728 

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

730 

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

732 

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

734 

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

736 ''' 

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

738 

739 def __int__(self): 

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

741 

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

743 and L{Fsum.floor}. 

744 ''' 

745 i, _ = self._fint2 

746 return i 

747 

748 def __invert__(self): # PYCHOK no cover 

749 '''Not implemented.''' 

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

751 return _NotImplemented(self) 

752 

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

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

755 

756 @arg other: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

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

759 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

760 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

761 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

762 

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

764 

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

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

767 set to C{as_integer} and B{C{mod}} is given and C{None}. 

768 

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

770 

771 @raise ResidualError: Invalid B{C{RESIDUAL}} or the residual 

772 is non-zero and significant and either 

773 B{C{other}} is a fractional or negative 

774 C{scalar} or B{C{mod}} is given and not 

775 C{None}. 

776 

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

778 invocation failed. 

779 

780 @raise ValueError: If B{C{other}} is a negative C{scalar} and this 

781 instance is C{0} or B{C{other}} is a fractional 

782 C{scalar} and this instance is negative or has a 

783 non-zero and significant residual or B{C{mod}} 

784 is given as C{0}. 

785 

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

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

788 ''' 

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

790 

791 def __isub__(self, other): 

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

793 

794 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} value or 

795 an iterable of several of the former. 

796 

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

798 

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

800 

801 @see: Methods L{Fsum.fsub_} and L{Fsum.fsub}. 

802 ''' 

803 try: 

804 return self._fsub(other, _isub_op_) 

805 except TypeError: 

806 pass 

807 _xiterable(other) 

808 return self._facc_neg(other) 

809 

810 def __iter__(self): 

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

812 ''' 

813 return iter(self.partials) 

814 

815 def __itruediv__(self, other, **raiser_RESIDUAL): 

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

817 

818 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

819 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

820 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

821 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

822 

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

824 

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

826 

827 @raise ResidualError: Non-zero, significant residual or invalid 

828 B{C{RESIDUAL}}. 

829 

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

831 

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

833 

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

835 

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

837 ''' 

838 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser_RESIDUAL) 

839 

840 def __le__(self, other): 

841 '''Return C{(B{self} <= B{other})}, see C{__eq__}. 

842 ''' 

843 return self._cmp_0(other, _lt_op_ + _fset_op_) <= 0 

844 

845 def __len__(self): 

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

847 ''' 

848 return self._n 

849 

850 def __lt__(self, other): 

851 '''Return C{(B{self} < B{other})}, see C{__eq__}. 

852 ''' 

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

854 

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

856 '''Not implemented.''' 

857 return _NotImplemented(self, other) 

858 

859 def __mod__(self, other): 

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

861 

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

863 ''' 

864 f = self._copy_2(self.__mod__) 

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

866 

867 def __mul__(self, other): 

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

869 

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

871 ''' 

872 f = self._copy_2(self.__mul__) 

873 return f._fmul(other, _mul_op_) 

874 

875 def __ne__(self, other): 

876 '''Return C{(B{self} != B{other})}, see C{__eq__}. 

877 ''' 

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

879 

880 def __neg__(self): 

881 '''Return C{copy(B{self})}, I{negated}. 

882 ''' 

883 f = self._copy_2(self.__neg__) 

884 return f._fset(self._neg) 

885 

886 def __pos__(self): 

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

888 ''' 

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

890 

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

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

893 

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

895 ''' 

896 f = self._copy_2(self.__pow__) 

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

898 

899 def __radd__(self, other): 

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

901 

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

903 ''' 

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

905 return f._fadd(self) 

906 

907 def __rdivmod__(self, other): 

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

909 C{(quotient, remainder)}. 

910 

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

912 ''' 

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

914 return f._fdivmod2(self, _divmod_op_) 

915 

916# def __repr__(self): 

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

918# ''' 

919# return self.toRepr(lenc=True) 

920 

921 def __rfloordiv__(self, other): 

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

923 

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

925 ''' 

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

927 return f._floordiv(self, _floordiv_op_) 

928 

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

930 '''Not implemented.''' 

931 return _NotImplemented(self, other) 

932 

933 def __rmod__(self, other): 

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

935 

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

937 ''' 

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

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

940 

941 def __rmul__(self, other): 

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

943 

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

945 ''' 

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

947 return f._fmul(self, _mul_op_) 

948 

949 def __round__(self, *ndigits): # PYCHOK Python 3+ 

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

951 

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

953 ''' 

954 f = self._copy_2(self.__round__) 

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

956 return f._fset(round(float(self), *ndigits)) # can be C{int} 

957 

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

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

960 

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

962 ''' 

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

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

965 

966 def __rsub__(self, other): 

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

968 

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

970 ''' 

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

972 return f._fsub(self, _sub_op_) 

973 

974 def __rtruediv__(self, other, **raiser_RESIDUAL): 

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

976 

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

978 ''' 

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

980 return f._ftruediv(self, _truediv_op_, **raiser_RESIDUAL) 

981 

982 def __str__(self): 

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

984 ''' 

985 return self.toStr(lenc=True) 

986 

987 def __sub__(self, other): 

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

989 

990 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar}. 

991 

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

993 

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

995 ''' 

996 f = self._copy_2(self.__sub__) 

997 return f._fsub(other, _sub_op_) 

998 

999 def __truediv__(self, other, **raiser_RESIDUAL): 

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

1001 

1002 @arg other: An L{Fsum}, L{Fsum2Tuple} or C{scalar} divisor. 

1003 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

1004 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

1005 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

1006 

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

1008 

1009 @raise ResidualError: Non-zero, significant residual or invalid 

1010 B{C{RESIDUAL}}. 

1011 

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

1013 ''' 

1014 return self._truediv(other, _truediv_op_, **raiser_RESIDUAL) 

1015 

1016 __trunc__ = __int__ 

1017 

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

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

1020 __div__ = __truediv__ 

1021 __idiv__ = __itruediv__ 

1022 __long__ = __int__ 

1023 __nonzero__ = __bool__ 

1024 __rdiv__ = __rtruediv__ 

1025 

1026 def as_integer_ratio(self): 

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

1028 

1029 @return: 2-Tuple C{(numerator, denominator)} both C{int} with 

1030 C{numerator} signed and C{denominator} non-zero and 

1031 positive. The C{numerator} is I{non-finite} if this 

1032 instance is. 

1033 

1034 @see: Method L{Fsum.fint2} and C{float.as_integer_ratio} in 

1035 Python 2.7+. 

1036 ''' 

1037 n, r = self._fint2 

1038 if r: 

1039 i, d = float(r).as_integer_ratio() 

1040 n, d = _n_d2(n * d + i, d) 

1041 else: # PYCHOK no cover 

1042 d = 1 

1043 return n, d 

1044 

1045 @property_RO 

1046 def as_iscalar(self): 

1047 '''Get this instance I{as-is} (L{Fsum} with C{non-zero residual}, 

1048 C{scalar} or I{non-finite}). 

1049 ''' 

1050 s, r = self._nfprs2 

1051 return self if r else s 

1052 

1053 @property_RO 

1054 def ceil(self): 

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

1056 C{float} in Python 2-). 

1057 

1058 @note: This C{ceil} takes the C{residual} into account. 

1059 

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

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

1062 ''' 

1063 s, r = self._fprs2 

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

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

1066 c += 1 

1067 return c # _ceil(self._n_d) 

1068 

1069 cmp = __cmp__ 

1070 

1071 def _cmp_0(self, other, op): 

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

1073 ''' 

1074 if _isFsum_2Tuple(other): 

1075 s = self._ps_1sum(*other._ps) 

1076 elif self._scalar(other, op): 

1077 s = self._ps_1sum(other) 

1078 else: 

1079 s = self.signOf() # res=True 

1080 return s 

1081 

1082 def copy(self, deep=False, **name): 

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

1084 

1085 @kwarg name: Optional, overriding C{B{name}='"copy"} (C{str}). 

1086 

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

1088 ''' 

1089 n = _name__(name, name__=self.copy) 

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

1091 if f._ps is self._ps: 

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

1093 if not deep: 

1094 f._n = 1 

1095 # assert f._f2product == self._f2product 

1096 # assert f._Fsum is f 

1097 # assert f._isfine is self._isfine 

1098 # assert f._RESIDUAL is self._RESIDUAL 

1099 return f 

1100 

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

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

1103 ''' 

1104 n = name or which.__name__ # _dunder_nameof 

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

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

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

1108 # assert f._n == self._n 

1109 # assert f._f2product == self._f2product 

1110 # assert f._Fsum is f 

1111 # assert f._isfine is self._isfine 

1112 # assert f._RESIDUAL is self._RESIDUAL 

1113 return f 

1114 

1115 def _copy_2r(self, other, which): 

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

1117 ''' 

1118 return other._copy_2(which) if _isFsum(other) else \ 

1119 self._copy_2(which)._fset(other) 

1120 

1121 divmod = __divmod__ 

1122 

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

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

1125 ''' 

1126 # self.as_iscalar causes RecursionError for ._fprs2 errors 

1127 s = _Psum(self._ps, nonfinites=True, name=self.name) 

1128 return Error(_SPACE_(s.as_iscalar, op, other), **txt_cause) 

1129 

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

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

1132 ''' 

1133 E, t = _xError2(X) 

1134 if mod: 

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

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

1137 

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

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

1140 ''' 

1141 E, t = _xError2(X) 

1142 u = unstr(self.named3, *xs, _ELLIPSIS=4, **kwds) 

1143 return E(u, txt=t, cause=X) 

1144 

1145 def _facc(self, xs, up=True, **_X_x_origin): 

1146 '''(INTERNAL) Accumulate more C{scalar}s or L{Fsum}s. 

1147 ''' 

1148 if xs: 

1149 kwds = self._isfine 

1150 if _X_x_origin: 

1151 kwds = _xkwds(_X_x_origin, **kwds) 

1152 fs = _xs(xs, **kwds) # PYCHOK yield 

1153 ps = self._ps 

1154 ps[:] = self._ps_acc(list(ps), fs, up=up) 

1155 return self 

1156 

1157 def _facc_args(self, xs, **up): 

1158 '''(INTERNAL) Accumulate 0, 1 or more C{xs}, all positional 

1159 arguments in the caller of this method. 

1160 ''' 

1161 return self._fadd(xs[0], **up) if len(xs) == 1 else \ 

1162 self._facc(xs, **up) # origin=1? 

1163 

1164 def _facc_neg(self, xs, **up_origin): 

1165 '''(INTERNAL) Accumulate more C{xs}, negated. 

1166 ''' 

1167 def _N(X): 

1168 return X._ps_neg 

1169 

1170 def _n(x): 

1171 return -float(x) 

1172 

1173 return self._facc(xs, _X=_N, _x=_n, **up_origin) 

1174 

1175 def _facc_power(self, power, xs, which, **raiser_RESIDUAL): # in .fmath 

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

1177 ''' 

1178 def _Pow4(p): 

1179 r = 0 

1180 if _isFsum_2Tuple(p): 

1181 s, r = p._fprs2 

1182 if r: 

1183 m = Fsum._pow 

1184 else: # scalar 

1185 return _Pow4(s) 

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

1187 p = s = int(p) 

1188 m = Fsum._pow_int 

1189 else: 

1190 p = s = _2float(power=p, **self._isfine) 

1191 m = Fsum._pow_scalar 

1192 return m, p, s, r 

1193 

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

1195 if p: # and xs: 

1196 op = which.__name__ 

1197 _FsT = _Fsum_2Tuple_types 

1198 _pow = self._pow_2_3 

1199 

1200 def _P(X): 

1201 f = _Pow(X, p, power, op, **raiser_RESIDUAL) 

1202 return f._ps if isinstance(f, _FsT) else (f,) 

1203 

1204 def _p(x): 

1205 x = float(x) 

1206 f = _pow(x, s, power, op, **raiser_RESIDUAL) 

1207 if f and r: 

1208 f *= _pow(x, r, power, op, **raiser_RESIDUAL) 

1209 return f 

1210 

1211 f = self._facc(xs, _X=_P, _x=_p) # origin=1? 

1212 else: 

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

1214 return f 

1215 

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

1217 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}. 

1218 ''' 

1219 if xs: 

1220 ps = self._ps 

1221 ps[:] = self._ps_acc(list(ps), xs, **up) 

1222 return self 

1223 

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

1225 '''(INTERNAL) Accumulate all positional C{xs}, each C{scalar}. 

1226 ''' 

1227 return self._facc_scalar(xs, **up) 

1228 

1229 def _facc_scalarf(self, xs, up=True, **origin_which): 

1230 '''(INTERNAL) Accumulate all C{xs}, each C{scalar}, an L{Fsum} or 

1231 L{Fsum2Tuple}, like function C{_xsum}. 

1232 ''' 

1233 _C = self.__class__ 

1234 fs = _xs(xs, **_x_isfine(self.nonfinitesOK, _Cdot=_C, 

1235 **origin_which)) # PYCHOK yield 

1236 return self._facc_scalar(fs, up=up) 

1237 

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

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

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

1241# ''' 

1242# ps = self._ps 

1243# while len(ps) > 1: 

1244# p = ps.pop() 

1245# if p: 

1246# n = self._n 

1247# _ = self._ps_acc(ps, (p,), up=False) 

1248# self._n = n 

1249# break 

1250# return self._update() if up else self 

1251 

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

1253 '''Add an iterable's items to this instance. 

1254 

1255 @arg xs: Iterable of items to add (each C{scalar}, 

1256 an L{Fsum} or L{Fsum2Tuple}). 

1257 

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

1259 

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

1261 

1262 @raise TypeError: An invalid B{C{xs}} item. 

1263 

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

1265 ''' 

1266 if _isFsum_2Tuple(xs): 

1267 self._facc_scalar(xs._ps) 

1268 elif isscalar(xs): # for backward compatibility # PYCHOK no cover 

1269 x = _2float(x=xs, **self._isfine) 

1270 self._facc_scalar_(x) 

1271 elif xs: # _xiterable(xs) 

1272 self._facc(xs) 

1273 return self 

1274 

1275 def fadd_(self, *xs): 

1276 '''Add all positional items to this instance. 

1277 

1278 @arg xs: Values to add (each C{scalar}, an L{Fsum} 

1279 or L{Fsum2Tuple}), all positional. 

1280 

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

1282 ''' 

1283 return self._facc_args(xs) 

1284 

1285 def _fadd(self, other, op=_add_op_, **up): 

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

1287 ''' 

1288 if _isFsum_2Tuple(other): 

1289 self._facc_scalar(other._ps, **up) 

1290 elif self._scalar(other, op): 

1291 self._facc_scalar_(other, **up) 

1292 return self 

1293 

1294 fcopy = copy # for backward compatibility 

1295 fdiv = __itruediv__ 

1296 fdivmod = __divmod__ 

1297 

1298 def _fdivmod2(self, other, op, **raiser_RESIDUAL): 

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

1300 ''' 

1301 # result mostly follows CPython function U{float_divmod 

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

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

1304 q = self._truediv(other, op, **raiser_RESIDUAL).floor 

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

1306 self -= self._Fsum_as(q) * other # NOT other * q! 

1307 

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

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

1310 self += other 

1311 q -= 1 

1312# t = self.signOf() 

1313# if t and t != s: 

1314# raise self._Error(op, other, _AssertionError, txt__=signOf) 

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

1316 

1317 def _fhorner(self, x, cs, where, incx=True): # in .fmath 

1318 '''(INTERNAL) Add an L{Fhorner} evaluation of polynomial 

1319 C{sum(cs[i] * B{x}**i for i=0..len(cs)-1) if B{incx} 

1320 else sum(... i=len(cs)-1..0)}. 

1321 ''' 

1322 # assert _xiterablen(cs) 

1323 try: 

1324 n = len(cs) 

1325 H = self._Fsum_as(name__=self._fhorner) 

1326 _m = H._mul_Fsum if _isFsum_2Tuple(x) else \ 

1327 H._mul_scalar 

1328 if _2finite(x, **self._isfine) and n > 1: 

1329 for c in (reversed(cs) if incx else cs): 

1330 H._fset(_m(x, _mul_op_), up=False) 

1331 H._fadd(c, up=False) 

1332 else: # x == 0 

1333 H = cs[0] if n else 0 

1334 self._fadd(H) 

1335 except Exception as X: 

1336 t = unstr(where, x, *cs, _ELLIPSIS=4, incx=incx) 

1337 raise self._ErrorX(X, _add_op_, t) 

1338 return self 

1339 

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

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

1342 ''' 

1343 if _isOK_or_finite(other, **self._isfine): 

1344 return other 

1345 E = _NonfiniteError(other) 

1346 raise self._Error(op, other, E, txt=_not_finite_) 

1347 

1348 def fint(self, name=NN, **raiser_RESIDUAL): 

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

1350 

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

1352 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

1353 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

1354 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

1355 

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

1357 with a zero or insignificant I{integer} residual. 

1358 

1359 @raise ResidualError: Non-zero, significant residual or invalid 

1360 B{C{RESIDUAL}}. 

1361 

1362 @see: Methods L{Fsum.fint2}, L{Fsum.int_float} and L{Fsum.is_integer}. 

1363 ''' 

1364 i, r = self._fint2 

1365 if r: 

1366 R = self._raiser(r, i, **raiser_RESIDUAL) 

1367 if R: 

1368 t = _stresidual(_integer_, r, **R) 

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

1370 return self._Fsum_as(i, name=_name__(name, name__=self.fint)) 

1371 

1372 def fint2(self, **name): 

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

1374 I{integer} residual. 

1375 

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

1377 

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

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

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

1381 The C{fsum} is I{non-finite} if this instance is. 

1382 ''' 

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

1384 

1385 @Property 

1386 def _fint2(self): # see ._fset 

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

1388 ''' 

1389 s, r = self._nfprs2 

1390 if _isfinite(s): 

1391 i = int(s) 

1392 r = (self._ps_1sum(i) if len(self._ps) > 1 else 

1393 float(s - i)) or INT0 

1394 else: # INF, NAN, NINF 

1395 i = float(s) 

1396# r = _NONFINITEr 

1397 return i, r # Fsum2Tuple? 

1398 

1399 @_fint2.setter_ # PYCHOK setter_UNDERscore! 

1400 def _fint2(self, s): # in _fset 

1401 '''(INTERNAL) Replace the C{_fint2} value. 

1402 ''' 

1403 if _isfinite(s): 

1404 i = int(s) 

1405 r = (s - i) or INT0 

1406 else: # INF, NAN, NINF 

1407 i = float(s) 

1408 r = _NONFINITEr 

1409 return i, r # like _fint2.getter 

1410 

1411 @deprecated_property_RO 

1412 def float_int(self): # PYCHOK no cover 

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

1414 return self.int_float() # raiser=False 

1415 

1416 @property_RO 

1417 def floor(self): 

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

1419 C{float} in Python 2-). 

1420 

1421 @note: This C{floor} takes the C{residual} into account. 

1422 

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

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

1425 ''' 

1426 s, r = self._fprs2 

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

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

1429 f -= 1 

1430 return f # _floor(self._n_d) 

1431 

1432# ffloordiv = __ifloordiv__ # for naming consistency? 

1433# floordiv = __floordiv__ # for naming consistency? 

1434 

1435 def _floordiv(self, other, op, **raiser_RESIDUAL): # rather _ffloordiv? 

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

1437 ''' 

1438 q = self._ftruediv(other, op, **raiser_RESIDUAL) # == self 

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

1440 

1441 def fma(self, other1, other2, **nonfinites): # in .fmath.fma 

1442 '''Fused-multiply-add C{self *= B{other1}; self += B{other2}}. 

1443 

1444 @arg other1: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

1445 @arg other2: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

1446 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{False}, to 

1447 override L{nonfinites<Fsum.nonfinites>} and 

1448 L{nonfiniterrors} default (C{bool}). 

1449 ''' 

1450 op = self.fma.__name__ 

1451 _fs = self._ps_other 

1452 try: 

1453 s, r = self._fprs2 

1454 if r: 

1455 f = self._f2mul(self.fma, other1, **nonfinites) 

1456 f += other2 

1457 elif _residue(other1) or _residue(other2): 

1458 fs = _2split3s(_fs(op, other1)) 

1459 fs = _2products(s, fs, *_fs(op, other2)) 

1460 f = _Psum(self._ps_acc([], fs, up=False), name=op) 

1461 else: 

1462 f = _fma(s, other1, other2) 

1463 f = _2finite(f, **self._isfine) 

1464 except TypeError as X: 

1465 raise self._ErrorX(X, op, (other1, other2)) 

1466 except (OverflowError, ValueError) as X: # from math.fma 

1467 f = self._mul_reduce(s, other1) # INF, NAN, NINF 

1468 f += sum(_fs(op, other2)) 

1469 f = self._nonfiniteX(X, op, f, **nonfinites) 

1470 return self._fset(f) 

1471 

1472 fmul = __imul__ 

1473 

1474 def _fmul(self, other, op): 

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

1476 ''' 

1477 if _isFsum_2Tuple(other): 

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

1479 f = self._mul_Fsum(other, op) 

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

1481 f = self._ps_mul(op, *other._ps) if other._ps else _0_0 

1482 elif self._f2product: # len(other._ps) == 1 

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

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

1485 f = self._finite(self._ps[0] * other._ps[0], op=op) 

1486 else: 

1487 s = self._scalar(other, op) 

1488 f = self._mul_scalar(s, op) 

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

1490 

1491 @deprecated_method 

1492 def f2mul(self, *others, **raiser): 

1493 '''DEPRECATED on 2024.09.13, use method L{f2mul_<Fsum.f2mul_>}.''' 

1494 return self._fset(self.f2mul_(*others, **raiser)) 

1495 

1496 def f2mul_(self, *others, **nonfinites): # in .fmath.f2mul 

1497 '''Return C{B{self} * B{other} * B{other} ...} for all B{C{others}} using cascaded, 

1498 accurate multiplication like with L{f2product<Fsum.f2product>} set to C{True}. 

1499 

1500 @arg others: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all 

1501 positional. 

1502 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{False}, to override both 

1503 L{nonfinites<Fsum.nonfinites>} and the L{nonfiniterrors} 

1504 default (C{bool}). 

1505 

1506 @return: The cascaded I{TwoProduct} (L{Fsum} or C{float}). 

1507 

1508 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>} 

1509 ''' 

1510 return self._f2mul(self.f2mul_, *others, **nonfinites) 

1511 

1512 def _f2mul(self, where, *others, **nonfinites_raiser): 

1513 '''(INTERNAL) See methods C{fma} and C{f2mul_}. 

1514 ''' 

1515 f = self._copy_2(where) 

1516 ps = f._ps 

1517 if ps and others: 

1518 op = where.__name__ 

1519 try: 

1520 for other in others: # to pinpoint errors 

1521 for p in self._ps_other(op, other): 

1522 pfs = _2products(p, _2split3s(ps)) 

1523 ps[:] = f._ps_acc([], pfs, up=False) 

1524 f._update() 

1525 except TypeError as X: 

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

1527 except (OverflowError, ValueError) as X: 

1528 r = self._mul_reduce(sum(ps), other) # INF, NAN, NINF 

1529 r = self._nonfiniteX(X, op, r, **nonfinites_raiser) 

1530 f._fset(r) 

1531 return f 

1532 

1533 def fover(self, over, **raiser_RESIDUAL): 

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

1535 

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

1537 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

1538 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

1539 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

1540 

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

1542 

1543 @raise ResidualError: Non-zero, significant residual or invalid 

1544 B{C{RESIDUAL}}. 

1545 

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

1547 ''' 

1548 return float(self.fdiv(over, **raiser_RESIDUAL)._fprs) 

1549 

1550 fpow = __ipow__ 

1551 

1552 def _fpow(self, other, op, *mod, **raiser_RESIDUAL): 

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

1554 ''' 

1555 if mod: 

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

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

1558 elif self.is_integer(): 

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

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

1561 x, r = _2s_r(other) # C{int}, C{float} or other 

1562 f = self._Fsum_as(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \ 

1563 self._pow_2_3(i, x, other, op, **raiser_RESIDUAL) 

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

1565 f = self._pow(other, other, op, **raiser_RESIDUAL) 

1566 else: # pow(self, other) 

1567 f = self._pow(other, other, op, **raiser_RESIDUAL) 

1568 return self._fset(f) # n=max(len(self), 1) 

1569 

1570 def f2product(self, *two): 

1571 '''Get and set accurate I{TwoProduct} multiplication for this 

1572 L{Fsum}, overriding the L{f2product} default. 

1573 

1574 @arg two: If omitted, leave the override unchanged, if C{True}, 

1575 turn I{TwoProduct} on, if C{False} off, if C{None}e 

1576 remove th override (C{bool} or C{None}). 

1577 

1578 @return: The previous setting (C{bool} or C{None} if not set). 

1579 

1580 @see: Function L{f2product<fsums.f2product>}. 

1581 

1582 @note: Use C{f.f2product() or f2product()} to determine whether 

1583 multiplication is accurate for L{Fsum} C{f}. 

1584 ''' 

1585 if two: # delattrof(self, _f2product=None) 

1586 t = _xkwds_pop(self.__dict__, _f2product=None) 

1587 if two[0] is not None: 

1588 self._f2product = bool(two[0]) 

1589 else: # getattrof(self, _f2product=None) 

1590 t = _xkwds_get(self.__dict__, _f2product=None) 

1591 return t 

1592 

1593 @Property 

1594 def _fprs(self): 

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

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

1597 

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

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

1600 ''' 

1601 s, _ = self._fprs2 

1602 return s # ._fprs2.fsum 

1603 

1604 @_fprs.setter_ # PYCHOK setter_UNDERscore! 

1605 def _fprs(self, s): 

1606 '''(INTERNAL) Replace the C{_fprs} value. 

1607 ''' 

1608 return s 

1609 

1610 @Property 

1611 def _fprs2(self): 

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

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

1614 ''' 

1615 ps = self._ps 

1616 n = len(ps) 

1617 try: 

1618 if n > 2: 

1619 s = _psum(ps, **self._isfine) 

1620 if not _isfinite(s): 

1621 ps[:] = s, # collapse ps 

1622 return Fsum2Tuple(s, _NONFINITEr) 

1623 n = len(ps) 

1624# Fsum._ps_max = max(Fsum._ps_max, n) 

1625 if n > 2: 

1626 r = self._ps_1sum(s) 

1627 return Fsum2Tuple(*_s_r(s, r)) 

1628 if n > 1: # len(ps) == 2 

1629 s, r = _s_r(*_2sum(*ps, **self._isfine)) 

1630 ps[:] = (r, s) if r else (s,) 

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

1632 s = ps[0] 

1633 r = INT0 if _isfinite(s) else _NONFINITEr 

1634 else: # len(ps) == 0 

1635 s = _0_0 

1636 r = INT0 if _isfinite(s) else _NONFINITEr 

1637 ps[:] = s, 

1638 except (OverflowError, ValueError) as X: 

1639 op = _fset_op_ # INF, NAN, NINF 

1640 ps[:] = sum(ps), # collapse ps 

1641 s = self._nonfiniteX(X, op, ps[0]) 

1642 r = _NONFINITEr 

1643 # assert self._ps is ps 

1644 return Fsum2Tuple(s, r) 

1645 

1646 @_fprs2.setter_ # PYCHOK setter_UNDERscore! 

1647 def _fprs2(self, s_r): 

1648 '''(INTERNAL) Replace the C{_fprs2} value. 

1649 ''' 

1650 return Fsum2Tuple(s_r) 

1651 

1652 def fset_(self, *xs): 

1653 '''Apply C{B{self}.partials = Fsum(*B{xs}).partials}. 

1654 

1655 @arg xs: Optional, new values (each C{scalar} or 

1656 an L{Fsum} or L{Fsum2Tuple} instance), all 

1657 positional. 

1658 

1659 @return: This instance, replaced (C{Fsum}). 

1660 

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

1662 ''' 

1663 f = (xs[0] if xs else _0_0) if len(xs) < 2 else \ 

1664 Fsum(*xs, nonfinites=self.nonfinites()) # self._Fsum_as(*xs) 

1665 return self._fset(f, op=_fset_op_) 

1666 

1667 def _fset(self, other, n=0, up=True, **op): 

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

1669 ''' 

1670 if other is self: 

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

1672 elif _isFsum_2Tuple(other): 

1673 if op: # and not self.nonfinitesOK: 

1674 self._finite(other._fprs, **op) 

1675 self._ps[:] = other._ps 

1676 self._n = n or other._n 

1677 if up: # use or zap the C{Property_RO} values 

1678 Fsum._fint2._update_from(self, other) 

1679 Fsum._fprs ._update_from(self, other) 

1680 Fsum._fprs2._update_from(self, other) 

1681 elif isscalar(other): 

1682 s = float(self._finite(other, **op)) if op else other 

1683 self._ps[:] = s, 

1684 self._n = n or 1 

1685 if up: # Property _fint2, _fprs and _fprs2 all have 

1686 # @.setter_underscore and NOT @.setter because the 

1687 # latter's _fset zaps the value set by @.setter 

1688 self._fint2 = s 

1689 self._fprs = s 

1690 self._fprs2 = s, INT0 

1691 # assert self._fprs is s 

1692 else: 

1693 op = _xkwds_get1(op, op=_fset_op_) 

1694 raise self._Error(op, other, _TypeError) 

1695 return self 

1696 

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

1698 '''Subtract an iterable's items from this instance. 

1699 

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

1701 ''' 

1702 return self._facc_neg(xs) 

1703 

1704 def fsub_(self, *xs): 

1705 '''Subtract all positional items from this instance. 

1706 

1707 @see: Method L{Fsum.fadd_} for further details. 

1708 ''' 

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

1710 self._facc_neg(xs) # origin=1? 

1711 

1712 def _fsub(self, other, op): 

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

1714 ''' 

1715 if _isFsum_2Tuple(other): 

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

1717 self._fset(_0_0, n=len(self) * 2) 

1718 elif other._ps: 

1719 self._facc_scalar(other._ps_neg) 

1720 elif self._scalar(other, op): 

1721 self._facc_scalar_(-other) 

1722 return self 

1723 

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

1725 '''Add an iterable's items, summate and return the current 

1726 precision running sum. 

1727 

1728 @arg xs: Iterable of items to add (each item C{scalar}, 

1729 an L{Fsum} or L{Fsum2Tuple}). 

1730 

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

1732 

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

1734 

1735 @note: Accumulation can continue after summation. 

1736 ''' 

1737 return self._facc(xs)._fprs 

1738 

1739 def fsum_(self, *xs): 

1740 '''Add any positional items, summate and return the current 

1741 precision running sum. 

1742 

1743 @arg xs: Items to add (each C{scalar}, an L{Fsum} or 

1744 L{Fsum2Tuple}), all positional. 

1745 

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

1747 

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

1749 ''' 

1750 return self._facc_args(xs)._fprs 

1751 

1752 def Fsum_(self, *xs, **name): 

1753 '''Like method L{Fsum.fsum_} but returning a named L{Fsum}. 

1754 

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

1756 

1757 @return: Copy of this updated instance (L{Fsum}). 

1758 ''' 

1759 return self._facc_args(xs)._copy_2(self.Fsum_, **name) 

1760 

1761 def Fsum2Tuple_(self, *xs, **name): 

1762 '''Like method L{Fsum.fsum_} but returning a named L{Fsum2Tuple}. 

1763 

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

1765 

1766 @return: Precision running sum (L{Fsum2Tuple}). 

1767 ''' 

1768 return Fsum2Tuple(self._facc_args(xs)._nfprs2, **name) 

1769 

1770 @property_RO 

1771 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, in .fstats 

1772 return self # NOT @Property_RO, see .copy and ._copy_2 

1773 

1774 def _Fsum_as(self, *xs, **name_f2product_nonfinites_RESIDUAL): 

1775 '''(INTERNAL) Return an C{Fsum} with this C{Fsum}'s C{.f2product}, 

1776 C{.nonfinites} and C{.RESIDUAL} setting, optionally 

1777 overridden with C{name_f2product_nonfinites_RESIDUAL} and 

1778 with any C{xs} accumulated. 

1779 ''' 

1780 kwds = _xkwds_not(None, Fsum._RESIDUAL, f2product =self.f2product(), 

1781 nonfinites=self.nonfinites(), 

1782 RESIDUAL =self.RESIDUAL()) 

1783 if name_f2product_nonfinites_RESIDUAL: # overwrites 

1784 kwds.update(name_f2product_nonfinites_RESIDUAL) 

1785 f = Fsum(**kwds) 

1786 # assert all(v == self.__dict__[n] for n, v in f.__dict__.items()) 

1787 return f._fset(xs[0], op=_fset_op_) if len(xs) == 1 else ( 

1788 f._facc(xs, up=False) if xs else f) 

1789 

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

1791 '''Add an iterable's items, summate and return the 

1792 current precision running sum I{and} the C{residual}. 

1793 

1794 @arg xs: Iterable of items to add (each item C{scalar}, 

1795 an L{Fsum} or L{Fsum2Tuple}). 

1796 @kwarg name: Optional C{B{name}=NN} (C{str}). 

1797 

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

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

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

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

1802 to be I{exact}. 

1803 

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

1805 ''' 

1806 t = self._facc(xs)._fprs2 

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

1808 

1809 def fsum2_(self, *xs): 

1810 '''Add any positional items, summate and return the current 

1811 precision running sum and the I{differential}. 

1812 

1813 @arg xs: Values to add (each C{scalar}, an L{Fsum} or 

1814 L{Fsum2Tuple}), all positional. 

1815 

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

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

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

1819 

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

1821 ''' 

1822 return self._fsum2(xs, self._facc_args) 

1823 

1824 def _fsum2(self, xs, _facc, **facc_kwds): 

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

1826 ''' 

1827 p, q = self._fprs2 

1828 if xs: 

1829 s, r = _facc(xs, **facc_kwds)._fprs2 

1830 if _isfinite(s): # _fsum(_1primed((s, -p, r, -q)) 

1831 d, r = _2sum(s - p, r - q, _isfine=_isOK) 

1832 r, _ = _s_r(d, r) 

1833 return s, (r if _isfinite(r) else _NONFINITEr) 

1834 else: 

1835 return p, _0_0 

1836 

1837 def fsumf_(self, *xs): 

1838 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}}, each I{known to be} 

1839 C{scalar}, an L{Fsum} or L{Fsum2Tuple}. 

1840 ''' 

1841 return self._facc_scalarf(xs, which=self.fsumf_)._fprs # origin=1? 

1842 

1843 def Fsumf_(self, *xs): 

1844 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}}, each I{known to be} 

1845 C{scalar}, an L{Fsum} or L{Fsum2Tuple}. 

1846 ''' 

1847 return self._facc_scalarf(xs, which=self.Fsumf_)._copy_2(self.Fsumf_) # origin=1? 

1848 

1849 def fsum2f_(self, *xs): 

1850 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}}, each I{known to be} 

1851 C{scalar}, an L{Fsum} or L{Fsum2Tuple}. 

1852 ''' 

1853 return self._fsum2(xs, self._facc_scalarf, which=self.fsum2f_) # origin=1? 

1854 

1855# ftruediv = __itruediv__ # for naming consistency? 

1856 

1857 def _ftruediv(self, other, op, **raiser_RESIDUAL): 

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

1859 ''' 

1860 n = _1_0 

1861 if _isFsum_2Tuple(other): 

1862 if other is self or self == other: 

1863 return self._fset(n, n=len(self)) 

1864 d, r = other._fprs2 

1865 if r: 

1866 R = self._raiser(r, d, **raiser_RESIDUAL) 

1867 if R: 

1868 raise self._ResidualError(op, other, r, **R) 

1869 d, n = other.as_integer_ratio() 

1870 else: 

1871 d = self._scalar(other, op) 

1872 try: 

1873 s = n / d 

1874 except Exception as X: 

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

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

1877 return self._fset(f) 

1878 

1879 @property_RO 

1880 def imag(self): 

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

1882 

1883 @see: Property L{Fsum.real}. 

1884 ''' 

1885 return _0_0 

1886 

1887 def int_float(self, **raiser_RESIDUAL): 

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

1889 

1890 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

1891 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

1892 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

1893 

1894 @return: This C{int} sum if this instance C{is_integer} and 

1895 I{finite}, otherwise the C{float} sum if the residual 

1896 is zero or not significant. 

1897 

1898 @raise ResidualError: Non-zero, significant residual or invalid 

1899 B{C{RESIDUAL}}. 

1900 

1901 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.is_integer}, 

1902 L{Fsum.RESIDUAL} and property L{Fsum.as_iscalar}. 

1903 ''' 

1904 s, r = self._fint2 

1905 if r: 

1906 s, r = self._fprs2 

1907 if r: # PYCHOK no cover 

1908 R = self._raiser(r, s, **raiser_RESIDUAL) 

1909 if R: 

1910 t = _stresidual(_non_zero_, r, **R) 

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

1912 s = float(s) 

1913 return s 

1914 

1915 def is_exact(self): 

1916 '''Is this instance' running C{fsum} considered to be exact? 

1917 (C{bool}), C{True} only if the C{residual is }L{INT0}. 

1918 ''' 

1919 return self.residual is INT0 

1920 

1921 def is_finite(self): # in .constants 

1922 '''Is this instance C{finite}? (C{bool}). 

1923 

1924 @see: Function L{isfinite<pygeodesy.isfinite>}. 

1925 ''' 

1926 return _isfinite(sum(self._ps)) # == sum(self) 

1927 

1928 def is_integer(self): 

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

1930 

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

1932 ''' 

1933 s, r = self._fint2 

1934 return False if r else (_isfinite(s) and isint(s)) 

1935 

1936 def is_math_fma(self): 

1937 '''Is accurate L{f2product} multiplication based on Python's C{math.fma}? 

1938 

1939 @return: C{True} if accurate multiplication uses C{math.fma}, C{False} 

1940 an C{fma} implementation as C{math.fma} or C{None}, a previous 

1941 C{PyGeodesy} implementation. 

1942 ''' 

1943 return (_2split3s is _passarg) or (False if _2n_d is None else None) 

1944 

1945 def is_math_fsum(self): 

1946 '''Are the summation functions L{fsum}, L{fsum_}, L{fsumf_}, L{fsum1}, 

1947 L{fsum1_} and L{fsum1f_} based on Python's C{math.fsum}? 

1948 

1949 @return: C{True} if summation functions use C{math.fsum}, C{False} 

1950 otherwise. 

1951 ''' 

1952 return _sum is _fsum # _fsum.__module__ is fabs.__module__ 

1953 

1954 def is_scalar(self, **raiser_RESIDUAL): 

1955 '''Is this instance' running sum C{scalar} with C{0} residual or with 

1956 a residual I{ratio} not exceeding the RESIDUAL threshold? 

1957 

1958 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

1959 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

1960 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

1961 

1962 @return: C{True} if this instance' residual is C{0} or C{insignificant}, 

1963 i.e. its residual C{ratio} doesn't exceed the L{RESIDUAL 

1964 <Fsum.RESIDUAL>} threshold (C{bool}). 

1965 

1966 @raise ResidualError: Non-zero, significant residual or invalid 

1967 B{C{RESIDUAL}}. 

1968 

1969 @see: Methods L{Fsum.RESIDUAL} and L{Fsum.is_integer} and property 

1970 L{Fsum.as_iscalar}. 

1971 ''' 

1972 s, r = self._fprs2 

1973 return False if r and self._raiser(r, s, **raiser_RESIDUAL) else True 

1974 

1975 def _mul_Fsum(self, other, op): 

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

1977 ''' 

1978 # assert _isFsum_2Tuple(other) 

1979 if self._ps and other._ps: 

1980 try: 

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

1982 except Exception as X: 

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

1984 else: 

1985 f = _0_0 

1986 return f 

1987 

1988 def _mul_reduce(self, *others): 

1989 '''(INTERNAL) Like fmath.fprod for I{non-finite} C{other}s. 

1990 ''' 

1991 r = _1_0 

1992 for f in others: 

1993 r *= sum(f._ps) if _isFsum_2Tuple(f) else float(f) 

1994 return r 

1995 

1996 def _mul_scalar(self, factor, op): 

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

1998 ''' 

1999 # assert isscalar(factor) 

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

2001 f = self if factor == _1_0 else ( 

2002 self._neg if factor == _N_1_0 else 

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

2004 else: 

2005 f = _0_0 

2006 return f 

2007 

2008# @property_RO 

2009# def _n_d(self): 

2010# n, d = self.as_integer_ratio() 

2011# return n / d 

2012 

2013 @property_RO 

2014 def _neg(self): 

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

2016 ''' 

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

2018 

2019 @property_RO 

2020 def _nfprs2(self): 

2021 '''(INTERNAL) Handle I{non-finite} C{_fprs2}. 

2022 ''' 

2023 try: # to handle nonfiniterrors, etc. 

2024 t = self._fprs2 

2025 except (OverflowError, ValueError): 

2026 t = Fsum2Tuple(sum(self._ps), _NONFINITEr) 

2027 return t 

2028 

2029 def nonfinites(self, *OK): 

2030 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan} 

2031 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively 

2032 C{ValueError} exceptions, overriding the L{nonfiniterrors} default. 

2033 

2034 @arg OK: If omitted, leave the override unchanged, if C{True}, 

2035 I{non-finites} are C{OK}, if C{False} throw exceptions 

2036 or if C{None} remove the override (C{bool} or C{None}). 

2037 

2038 @return: The previous setting (C{bool} or C{None} if not set). 

2039 

2040 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}. 

2041 

2042 @note: Use property L{nonfinitesOK<Fsum.nonfinitesOK>} to determine 

2043 whether I{non-finites} are C{OK} for this L{Fsum} and by the 

2044 L{nonfiniterrors} default. 

2045 ''' 

2046 _ks = Fsum._nonfinites_isfine_kwds 

2047 if OK: # delattrof(self, _isfine=None) 

2048 k = _xkwds_pop(self.__dict__, _isfine=None) 

2049 if OK[0] is not None: 

2050 self._isfine = _ks[bool(OK[0])] 

2051 self._update() 

2052 else: # getattrof(self, _isfine=None) 

2053 k = _xkwds_get(self.__dict__, _isfine=None) 

2054 # dict(map(reversed, _ks.items())).get(k, None) 

2055 # raises a TypeError: unhashable type: 'dict' 

2056 return True if k is _ks[True] else ( 

2057 False if k is _ks[False] else None) 

2058 

2059 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK), 

2060 False: dict(_isfine=_isfinite)} 

2061 

2062 @property_RO 

2063 def nonfinitesOK(self): 

2064 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}). 

2065 ''' 

2066# nf = self.nonfinites() 

2067# if nf is None: 

2068# nf = not nonfiniterrors() 

2069 return _isOK_or_finite(INF, **self._isfine) 

2070 

2071 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None): 

2072 '''(INTERNAL) Handle a I{non-finite} exception. 

2073 ''' 

2074 if nonfinites is None: 

2075 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser) 

2076 if not nonfinites: 

2077 raise self._ErrorX(X, op, f) 

2078 return f 

2079 

2080 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL): 

2081 '''(INTERNAL) Re/set options from keyword arguments. 

2082 ''' 

2083 if f2product is not None: 

2084 self.f2product(f2product) 

2085 if nonfinites is not None: 

2086 self.nonfinites(nonfinites) 

2087 if name_RESIDUAL: # MUST be last 

2088 n, kwds = _name2__(**name_RESIDUAL) 

2089 if kwds: 

2090 R = Fsum._RESIDUAL 

2091 t = _threshold(R, **kwds) 

2092 if t != R: 

2093 self._RESIDUAL = t 

2094 if n: 

2095 self.name = n # self.rename(n) 

2096 

2097 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over 

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

2099 ''' 

2100 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL) 

2101 

2102 @property_RO 

2103 def partials(self): 

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

2105 ''' 

2106 return tuple(self._ps) 

2107 

2108 def pow(self, x, *mod, **raiser_RESIDUAL): 

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

2110 

2111 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

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

2114 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

2115 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

2116 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

2117 

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

2119 result (L{Fsum}). 

2120 

2121 @raise ResidualError: Non-zero, significant residual or invalid 

2122 B{C{RESIDUAL}}. 

2123 

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

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

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

2127 

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

2129 and L{Fsum.root}. 

2130 ''' 

2131 f = self._copy_2(self.pow) 

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

2133 

2134 def _pow(self, other, unused, op, **raiser_RESIDUAL): 

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

2136 ''' 

2137 if _isFsum_2Tuple(other): 

2138 f = self._pow_Fsum(other, op, **raiser_RESIDUAL) 

2139 elif self._scalar(other, op): 

2140 x = self._finite(other, op=op) 

2141 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

2142 else: 

2143 f = self._pow_0_1(0, other) 

2144 return f 

2145 

2146 def _pow_0_1(self, x, other): 

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

2148 ''' 

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

2150 

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

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

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

2154 ''' 

2155 

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

2157 m = mod[0] 

2158 # assert _isFsum_2Tuple(b) 

2159 

2160 def _s(s, r): 

2161 R = self._raiser(r, s, **raiser_RESIDUAL) 

2162 if R: 

2163 raise self._ResidualError(op, other, r, mod=m, **R) 

2164 return s 

2165 

2166 b = _s(*(b._fprs2 if m is None else b._fint2)) 

2167 x = _s(*_2s_r(x)) 

2168 

2169 try: 

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

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

2172 if iscomplex(s): 

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

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

2175 _ = _2finite(s, **self._isfine) # ignore float 

2176 return s 

2177 except Exception as X: 

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

2179 

2180 def _pow_Fsum(self, other, op, **raiser_RESIDUAL): 

2181 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}. 

2182 ''' 

2183 # assert _isFsum_2Tuple(other) 

2184 x, r = other._fprs2 

2185 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

2186 if f and r: 

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

2188 return f 

2189 

2190 def _pow_int(self, x, other, op, **raiser_RESIDUAL): 

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

2192 ''' 

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

2194 ps = self._ps 

2195 if len(ps) > 1: 

2196 _mul_Fsum = Fsum._mul_Fsum 

2197 if x > 4: 

2198 p = self 

2199 f = self if (x & 1) else self._Fsum_as(_1_0) 

2200 m = x >> 1 # // 2 

2201 while m: 

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

2203 if (m & 1): 

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

2205 m >>= 1 # //= 2 

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

2207 f = _mul_Fsum(self, self, op) 

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

2209 p = self if x < 4 else f 

2210 f = _mul_Fsum(f, p, op) 

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

2212 f = self._pow_0_1(x, other) 

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

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

2215 else: # PYCHOK no cover 

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

2217 f = 0 if x else 1 

2218 return f 

2219 

2220 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL): 

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

2222 ''' 

2223 s, r = self._fprs2 

2224 if r: 

2225 # assert s != 0 

2226 if isint(x, both=True): # self**int 

2227 x = int(x) 

2228 y = abs(x) 

2229 if y > 1: 

2230 f = self._pow_int(y, other, op, **raiser_RESIDUAL) 

2231 if x > 0: # i.e. > 1 

2232 return f # Fsum or scalar 

2233 # assert x < 0 # i.e. < -1 

2234 if _isFsum(f): 

2235 s, r = f._fprs2 

2236 if r: 

2237 return self._1_Over(f, op, **raiser_RESIDUAL) 

2238 else: # scalar 

2239 s = f 

2240 # use s**(-1) to get the CPython 

2241 # float_pow error iff s is zero 

2242 x = -1 

2243 elif x < 0: # self**(-1) 

2244 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self 

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

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

2247 else: # self**fractional 

2248 R = self._raiser(r, s, **raiser_RESIDUAL) 

2249 if R: 

2250 raise self._ResidualError(op, other, r, **R) 

2251 n, d = self.as_integer_ratio() 

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

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

2254 s = n / d 

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

2256 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL) 

2257 

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

2259 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}. 

2260 ''' 

2261 n = 0 

2262 _2s = _2sum 

2263 _fi = self._isfine 

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

2265 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine) 

2266 if x: 

2267 i = 0 

2268 for p in ps: 

2269 x, p = _2s(x, p, **_fi) 

2270 if p: 

2271 ps[i] = p 

2272 i += 1 

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

2274 n += 1 

2275 if n: 

2276 self._n += n 

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

2278 if up: 

2279 self._update() 

2280# x = sum(ps) 

2281# if not _isOK_or_finite(x, **fi): 

2282# ps[:] = x, # collapse ps 

2283 return ps 

2284 

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

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

2287 each scalar C{factor} and accumulate into an C{Fsum}. 

2288 ''' 

2289 def _psfs(ps, fs, _isfine=_isfinite): 

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

2291 ps, fs = fs, ps 

2292 if self._f2product: 

2293 fs, p = _2split3s(fs), fs 

2294 if len(ps) > 1 and fs is not p: 

2295 fs = tuple(fs) # several ps 

2296 _pfs = _2products 

2297 else: 

2298 def _pfs(p, fs): 

2299 return (p * f for f in fs) 

2300 

2301 for p in ps: 

2302 for f in _pfs(p, fs): 

2303 yield f if _isfine(f) else _nfError(f) 

2304 

2305 fs = _psfs(self._ps, factors, **self._isfine) 

2306 f = _Psum(self._ps_acc([], fs, up=False), name=op) 

2307 return f 

2308 

2309 @property_RO 

2310 def _ps_neg(self): 

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

2312 ''' 

2313 for p in self._ps: 

2314 yield -p 

2315 

2316 def _ps_other(self, op, other): 

2317 '''(INTERNAL) Yield C{other} as C{scalar}s. 

2318 ''' 

2319 if _isFsum_2Tuple(other): 

2320 for p in other._ps: 

2321 yield p 

2322 else: 

2323 yield self._scalar(other, op) 

2324 

2325 def _ps_1sum(self, *less): 

2326 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars. 

2327 ''' 

2328 def _1psls(ps, ls): 

2329 yield _1_0 

2330 for p in ps: 

2331 yield p 

2332 for p in ls: 

2333 yield -p 

2334 yield _N_1_0 

2335 

2336 return _fsum(_1psls(self._ps, less)) 

2337 

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

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

2340 I{and} is residual C{r} I{non-zero} or I{significant} (for a 

2341 negative respectively positive C{RESIDUAL} threshold)? 

2342 ''' 

2343 if r and raiser: 

2344 t = self._RESIDUAL 

2345 if RESIDUAL: 

2346 t = _threshold(t, **RESIDUAL) 

2347 if t < 0 or (s + r) != s: 

2348 q = (r / s) if s else s # == 0. 

2349 if fabs(q) > fabs(t): 

2350 return dict(ratio=q, R=t) 

2351 return {} 

2352 

2353 rdiv = __rtruediv__ 

2354 

2355 @property_RO 

2356 def real(self): 

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

2358 

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

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

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

2362 ''' 

2363 return float(self) 

2364 

2365 @property_RO 

2366 def residual(self): 

2367 '''Get this instance' residual or residue (C{float} or C{int}): 

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

2369 

2370 @note: The C{residual is INT0} iff the precision running 

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

2372 

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

2374 ''' 

2375 return self._fprs2.residual 

2376 

2377 def RESIDUAL(self, *threshold): 

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

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

2380 

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

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

2383 C{None}, restore the default set with env variable 

2384 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

2385 current setting. 

2386 

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

2388 

2389 @raise ResidualError: Invalid B{C{threshold}}. 

2390 

2391 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio} 

2392 C{residual / fsum} exceeds the given B{C{threshold}} and (2) 

2393 the C{residual} is non-zero and (3) is I{significant} vs the 

2394 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional 

2395 keyword argument C{raiser=False} is missing. Specify a 

2396 negative B{C{threshold}} for only non-zero C{residual} 

2397 testing without the I{significant} case. 

2398 ''' 

2399 r = self._RESIDUAL 

2400 if threshold: 

2401 t = threshold[0] 

2402 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ... 

2403 (_0_0 if t else _1_0) if isbool(t) else 

2404 _threshold(t)) # ... backward compatibility 

2405 return r 

2406 

2407 def _ResidualError(self, op, other, residual, **mod_R): 

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

2409 ''' 

2410 def _p(mod=None, R=0, **unused): # ratio=0 

2411 return (_non_zero_ if R < 0 else _significant_) \ 

2412 if mod is None else _integer_ 

2413 

2414 t = _stresidual(_p(**mod_R), residual, **mod_R) 

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

2416 

2417 def root(self, root, **raiser_RESIDUAL): 

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

2419 

2420 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2421 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any 

2422 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar} 

2423 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

2424 

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

2426 

2427 @raise ResidualError: Non-zero, significant residual or invalid 

2428 B{C{RESIDUAL}}. 

2429 

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

2431 ''' 

2432 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL) 

2433 f = self._copy_2(self.root) 

2434 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x) 

2435 

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

2437 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}. 

2438 ''' 

2439 if isscalar(other): 

2440 return other 

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

2442 

2443 def signOf(self, res=True): 

2444 '''Determine the sign of this instance. 

2445 

2446 @kwarg res: If C{True}, consider the residual, 

2447 otherwise ignore the latter (C{bool}). 

2448 

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

2450 ''' 

2451 s, r = self._nfprs2 

2452 r = (-r) if res else 0 

2453 return _signOf(s, r) 

2454 

2455 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature 

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

2457 

2458 @kwarg lenc_prec_sep_fmt: Optional keyword arguments 

2459 for method L{Fsum.toStr}. 

2460 

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

2462 ''' 

2463 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt)) 

2464 

2465 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature 

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

2467 

2468 @kwarg lenc: If C{True}, include the current C{[len]} of this 

2469 L{Fsum} enclosed in I{[brackets]} (C{bool}). 

2470 @kwarg prec_sep_fmt: Optional keyword arguments for method 

2471 L{Fsum2Tuple.toStr}. 

2472 

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

2474 ''' 

2475 p = self.classname 

2476 if lenc: 

2477 p = Fmt.SQUARE(p, len(self)) 

2478 n = _enquote(self.name, white=_UNDER_) 

2479 t = self._nfprs2.toStr(**prec_sep_fmt) 

2480 return NN(p, _SPACE_, n, t) 

2481 

2482 def _truediv(self, other, op, **raiser_RESIDUAL): 

2483 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}. 

2484 ''' 

2485 f = self._copy_2(self.__truediv__) 

2486 return f._ftruediv(other, op, **raiser_RESIDUAL) 

2487 

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

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

2490 ''' 

2491 if updated: 

2492 _pop = self.__dict__.pop 

2493 for p in _ROs: 

2494 _ = _pop(p, None) 

2495# Fsum._fint2._update(self) 

2496# Fsum._fprs ._update(self) 

2497# Fsum._fprs2._update(self) 

2498 return self # for .fset_ 

2499 

2500_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update 

2501 

2502if _NONFINITES == _std_: # PYCHOK no cover 

2503 _ = nonfiniterrors(False) 

2504 

2505 

2506def _Float_Int(arg, **name_Error): 

2507 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit. 

2508 ''' 

2509 U = Int if isint(arg) else Float 

2510 return U(arg, **name_Error) 

2511 

2512 

2513class DivMod2Tuple(_NamedTuple): 

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

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

2516 

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

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

2519 ''' 

2520 _Names_ = ('div', 'mod') 

2521 _Units_ = (_Float_Int, Fsum) 

2522 

2523 

2524class Fsum2Tuple(_NamedTuple): # in .fstats 

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

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

2527 item is C{float} or C{int}. 

2528 

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

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

2531 ''' 

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

2533 _Units_ = (_Float_Int, _Float_Int) 

2534 

2535 def __abs__(self): # in .fmath 

2536 return self._Fsum.__abs__() 

2537 

2538 def __bool__(self): # PYCHOK Python 3+ 

2539 return bool(self._Fsum) 

2540 

2541 def __eq__(self, other): 

2542 return self._other_op(other, self.__eq__) 

2543 

2544 def __float__(self): 

2545 return self._Fsum.__float__() 

2546 

2547 def __ge__(self, other): 

2548 return self._other_op(other, self.__ge__) 

2549 

2550 def __gt__(self, other): 

2551 return self._other_op(other, self.__gt__) 

2552 

2553 def __le__(self, other): 

2554 return self._other_op(other, self.__le__) 

2555 

2556 def __lt__(self, other): 

2557 return self._other_op(other, self.__lt__) 

2558 

2559 def __int__(self): 

2560 return self._Fsum.__int__() 

2561 

2562 def __ne__(self, other): 

2563 return self._other_op(other, self.__ne__) 

2564 

2565 def __neg__(self): 

2566 return self._Fsum.__neg__() 

2567 

2568 __nonzero__ = __bool__ # Python 2- 

2569 

2570 def __pos__(self): 

2571 return self._Fsum.__pos__() 

2572 

2573 def as_integer_ratio(self): 

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

2575 

2576 @see: Method L{Fsum.as_integer_ratio} for further details. 

2577 ''' 

2578 return self._Fsum.as_integer_ratio() 

2579 

2580 @property_RO 

2581 def _fint2(self): 

2582 return self._Fsum._fint2 

2583 

2584 @property_RO 

2585 def _fprs2(self): 

2586 return self._Fsum._fprs2 

2587 

2588 @Property_RO 

2589 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats 

2590 s, r = _s_r(*self) 

2591 ps = (r, s) if r else (s,) 

2592 return _Psum(ps, name=self.name) 

2593 

2594 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL): 

2595 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}. 

2596 ''' 

2597 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL) 

2598 

2599 def is_exact(self): 

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

2601 ''' 

2602 return self._Fsum.is_exact() 

2603 

2604 def is_finite(self): # in .constants 

2605 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}). 

2606 

2607 @see: Function L{isfinite<pygeodesy.isfinite>}. 

2608 ''' 

2609 return self._Fsum.is_finite() 

2610 

2611 def is_integer(self): 

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

2613 ''' 

2614 return self._Fsum.is_integer() 

2615 

2616 def _mul_scalar(self, other, op): # for Fsum._fmul 

2617 return self._Fsum._mul_scalar(other, op) 

2618 

2619 @property_RO 

2620 def _n(self): 

2621 return self._Fsum._n 

2622 

2623 def _other_op(self, other, which): 

2624 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum) 

2625 return getattr(C, which.__name__)(s, other) 

2626 

2627 @property_RO 

2628 def _ps(self): 

2629 return self._Fsum._ps 

2630 

2631 @property_RO 

2632 def _ps_neg(self): 

2633 return self._Fsum._ps_neg 

2634 

2635 def signOf(self, **res): 

2636 '''Like method L{Fsum.signOf}. 

2637 ''' 

2638 return self._Fsum.signOf(**res) 

2639 

2640 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature 

2641 '''Return this L{Fsum2Tuple} as string (C{str}). 

2642 

2643 @kwarg fmt: Optional C{float} format (C{letter}). 

2644 @kwarg prec_sep: Optional keyword arguments for function 

2645 L{fstr<streprs.fstr>}. 

2646 ''' 

2647 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep)) 

2648 

2649_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines 

2650 

2651 

2652class ResidualError(_ValueError): 

2653 '''Error raised for a division, power or root operation of 

2654 an L{Fsum} instance with a C{residual} I{ratio} exceeding 

2655 the L{RESIDUAL<Fsum.RESIDUAL>} threshold. 

2656 

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

2658 ''' 

2659 pass 

2660 

2661 

2662try: 

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

2664 

2665 # make sure _fsum works as expected (XXX check 

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

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

2668 del _fsum # nope, remove _fsum ... 

2669 raise ImportError() # ... use _fsum below 

2670 

2671 _sum = _fsum # in .elliptic 

2672except ImportError: 

2673 _sum = sum # in .elliptic 

2674 

2675 def _fsum(xs): 

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

2677 ''' 

2678 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True) 

2679 return float(F._facc(xs, up=False)) 

2680 

2681 

2682def fsum(xs, nonfinites=None, **floats): 

2683 '''Precision floating point summation from Python's C{math.fsum}. 

2684 

2685 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2686 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if 

2687 C{False} I{non-finites} raise an Overflow-/ValueError or if 

2688 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}). 

2689 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use 

2690 keyword argument C{B{nonfinites}=False} instead. 

2691 

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

2693 

2694 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow. 

2695 

2696 @raise TypeError: Invalid B{C{xs}} item. 

2697 

2698 @raise ValueError: Invalid or C{NAN} B{C{xs}} item. 

2699 

2700 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites}, 

2701 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}. 

2702 ''' 

2703 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0 

2704 

2705 

2706def fsum_(*xs, **nonfinites): 

2707 '''Precision floating point summation of all positional items. 

2708 

2709 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2710 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2711 

2712 @see: Function L{fsum<fsums.fsum>} for further details. 

2713 ''' 

2714 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1? 

2715 

2716 

2717def fsumf_(*xs): 

2718 '''Precision floating point summation of all positional items with I{non-finites} C{OK}. 

2719 

2720 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), 

2721 all positional. 

2722 

2723 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2724 ''' 

2725 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1? 

2726 

2727 

2728def fsum1(xs, **nonfinites): 

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

2730 

2731 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2732 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2733 

2734 @see: Function L{fsum<fsums.fsum>} for further details. 

2735 ''' 

2736 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0 

2737 

2738 

2739def fsum1_(*xs, **nonfinites): 

2740 '''Precision floating point summation of all positional items, 1-primed. 

2741 

2742 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2743 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2744 

2745 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2746 ''' 

2747 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1? 

2748 

2749 

2750def fsum1f_(*xs): 

2751 '''Precision floating point summation of all positional items, 1-primed and 

2752 with I{non-finites} C{OK}. 

2753 

2754 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2755 ''' 

2756 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0 

2757 

2758 

2759def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers. 

2760 _x_kwds = dict(_x= (_passarg if nfOK else _2finite), 

2761 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds 

2762 _x_kwds.update(kwds) 

2763 return _x_kwds 

2764 

2765 

2766def _X_ps(X): # default C{_X} handler 

2767 return X._ps # lambda X: X._ps 

2768 

2769 

2770def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc 

2771 origin=0, which=None, **_Cdot): 

2772 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s. 

2773 ''' 

2774 i, x = 0, xs 

2775 try: 

2776 for i, x in enumerate(_xiterable(xs)): 

2777 if isinstance(x, _Fsum_2Tuple_types): 

2778 for p in _X(x): 

2779 yield p if _isfine(p) else _nfError(p) 

2780 else: 

2781 f = _x(x) 

2782 yield f if _isfine(f) else _nfError(f) 

2783 

2784 except (OverflowError, TypeError, ValueError) as X: 

2785 t = _xsError(X, xs, i + origin, x) 

2786 if which: # prefix invokation 

2787 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot) 

2788 t = _COMMASPACE_(w, t) 

2789 raise _xError(X, t, txt=None) 

2790 

2791 

2792def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0 

2793 '''(INTERNAL) Precision summation of C{xs} with conditions. 

2794 ''' 

2795 if floats: # for backward compatibility 

2796 nonfinites = _xkwds_get1(floats, floats=nonfinites) 

2797 elif nonfinites is None: 

2798 nonfinites = not nonfiniterrors() 

2799 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) 

2800 return _fsum(_1primed(fs) if primed else fs) 

2801 

2802 

2803# delete all decorators, etc. 

2804del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \ 

2805 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \ 

2806 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _getenv, _std_ 

2807 

2808if __name__ == '__main__': 

2809 

2810 # usage: python3 -m pygeodesy.fsums 

2811 

2812 def _test(n): 

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

2814 from pygeodesy import frandoms, printf 

2815 

2816 printf(_fsum.__name__, end=_COMMASPACE_) 

2817 printf(_psum.__name__, end=_COMMASPACE_) 

2818 

2819 F = Fsum() 

2820 if F.is_math_fsum(): 

2821 for t in frandoms(n, seeded=True): 

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

2823 printf(_DOT_, end=NN) 

2824 printf(NN) 

2825 

2826 _test(128) 

2827 

2828# **) MIT License 

2829# 

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

2831# 

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

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

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

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

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

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

2838# 

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

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

2841# 

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

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

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

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

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

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

2848# OTHER DEALINGS IN THE SOFTWARE.