Coverage for pygeodesy/fsums.py: 94%

1097 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-22 18:16 -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, _getPYGEODESY, _MODS, _passarg 

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

53 _not_finite_, _SPACE_, _std_, _UNDER_ 

54# from pygeodesy.lazily import _ALL_LAZY # from .named 

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

56 _NotImplemented, _ALL_LAZY 

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.22' 

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 = _getPYGEODESY('FSUM_F2PRODUCT') 

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 = _getPYGEODESY('FSUM_NONFINITES') 

88_non_zero_ = 'non-zero' 

89_pow_op_ = _mul_op_ * 2 # _DSTAR_ 

90_RESIDUAL_0_0 = _getPYGEODESY('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 = _MODS.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# turned off, called by _deepcopy and _copy 

917# def __reduce__(self): # Python 3.8+ 

918# ''' Pickle, like std C{fractions.Fraction}, see U{__reduce__ 

919# <https://docs.Python.org/3/library/pickle.html#object.__reduce__>} 

920# ''' 

921# dict_ = self._Fsum_as().__dict__ # no __setstate__ 

922# return (self.__class__, self.partials, dict_) 

923 

924# def __repr__(self): 

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

926# ''' 

927# return self.toRepr(lenc=True) 

928 

929 def __rfloordiv__(self, other): 

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

931 

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

933 ''' 

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

935 return f._floordiv(self, _floordiv_op_) 

936 

937 def __rmatmul__(self, other): # PYCHOK no coveS 

938 '''Not implemented.''' 

939 return _NotImplemented(self, other) 

940 

941 def __rmod__(self, other): 

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

943 

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

945 ''' 

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

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

948 

949 def __rmul__(self, other): 

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

951 

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

953 ''' 

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

955 return f._fmul(self, _mul_op_) 

956 

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

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

959 

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

961 ''' 

962 f = self._copy_2(self.__round__) 

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

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

965 

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

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

968 

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

970 ''' 

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

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

973 

974 def __rsub__(self, other): 

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

976 

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

978 ''' 

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

980 return f._fsub(self, _sub_op_) 

981 

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

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

984 

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

986 ''' 

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

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

989 

990 def __str__(self): 

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

992 ''' 

993 return self.toStr(lenc=True) 

994 

995 def __sub__(self, other): 

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

997 

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

999 

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

1001 

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

1003 ''' 

1004 f = self._copy_2(self.__sub__) 

1005 return f._fsub(other, _sub_op_) 

1006 

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

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

1009 

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

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

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

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

1014 

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

1016 

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

1018 B{C{RESIDUAL}}. 

1019 

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

1021 ''' 

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

1023 

1024 __trunc__ = __int__ 

1025 

1026 if _MODS.sys_version_info2 < (3, 0): # PYCHOK no cover 

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

1028 __div__ = __truediv__ 

1029 __idiv__ = __itruediv__ 

1030 __long__ = __int__ 

1031 __nonzero__ = __bool__ 

1032 __rdiv__ = __rtruediv__ 

1033 

1034 def as_integer_ratio(self): 

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

1036 

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

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

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

1040 instance is. 

1041 

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

1043 Python 2.7+. 

1044 ''' 

1045 n, r = self._fint2 

1046 if r: 

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

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

1049 else: # PYCHOK no cover 

1050 d = 1 

1051 return n, d 

1052 

1053 @property_RO 

1054 def as_iscalar(self): 

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

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

1057 ''' 

1058 s, r = self._nfprs2 

1059 return self if r else s 

1060 

1061 @property_RO 

1062 def ceil(self): 

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

1064 C{float} in Python 2-). 

1065 

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

1067 

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

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

1070 ''' 

1071 s, r = self._fprs2 

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

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

1074 c += 1 

1075 return c # _ceil(self._n_d) 

1076 

1077 cmp = __cmp__ 

1078 

1079 def _cmp_0(self, other, op): 

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

1081 ''' 

1082 if _isFsum_2Tuple(other): 

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

1084 elif self._scalar(other, op): 

1085 s = self._ps_1sum(other) 

1086 else: 

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

1088 return s 

1089 

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

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

1092 

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

1094 

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

1096 ''' 

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

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

1099 if f._ps is self._ps: 

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

1101 if not deep: 

1102 f._n = 1 

1103 # assert f._f2product == self._f2product 

1104 # assert f._Fsum is f 

1105 # assert f._isfine is self._isfine 

1106 # assert f._RESIDUAL is self._RESIDUAL 

1107 return f 

1108 

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

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

1111 ''' 

1112 n = name or which.__name__ # _DUNDER_nameof 

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

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

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

1116 # assert f._n == self._n 

1117 # assert f._f2product == self._f2product 

1118 # assert f._Fsum is f 

1119 # assert f._isfine is self._isfine 

1120 # assert f._RESIDUAL is self._RESIDUAL 

1121 return f 

1122 

1123 def _copy_2r(self, other, which): 

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

1125 ''' 

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

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

1128 

1129 divmod = __divmod__ 

1130 

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

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

1133 ''' 

1134 # self.as_iscalar causes RecursionError for ._fprs2 errors 

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

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

1137 

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

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

1140 ''' 

1141 E, t = _xError2(X) 

1142 if mod: 

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

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

1145 

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

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

1148 ''' 

1149 E, t = _xError2(X) 

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

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

1152 

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

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

1155 ''' 

1156 if xs: 

1157 kwds = self._isfine 

1158 if _X_x_origin: 

1159 kwds = _xkwds(_X_x_origin, **kwds) 

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

1161 ps = self._ps 

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

1163# if len(ps) > 16: 

1164# _ = _psum(ps, **self._isfine) 

1165 return self 

1166 

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

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

1169 arguments in the caller of this method. 

1170 ''' 

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

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

1173 

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

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

1176 ''' 

1177 def _N(X): 

1178 return X._ps_neg 

1179 

1180 def _n(x): 

1181 return -float(x) 

1182 

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

1184 

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

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

1187 ''' 

1188 def _Pow4(p): 

1189 r = 0 

1190 if _isFsum_2Tuple(p): 

1191 s, r = p._fprs2 

1192 if r: 

1193 m = Fsum._pow 

1194 else: # scalar 

1195 return _Pow4(s) 

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

1197 p = s = int(p) 

1198 m = Fsum._pow_int 

1199 else: 

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

1201 m = Fsum._pow_scalar 

1202 return m, p, s, r 

1203 

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

1205 if p: # and xs: 

1206 op = which.__name__ 

1207 _FsT = _Fsum_2Tuple_types 

1208 _pow = self._pow_2_3 

1209 

1210 def _P(X): 

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

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

1213 

1214 def _p(x): 

1215 x = float(x) 

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

1217 if f and r: 

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

1219 return f 

1220 

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

1222 else: 

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

1224 return f 

1225 

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

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

1228 ''' 

1229 if xs: 

1230 ps = self._ps 

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

1232 return self 

1233 

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

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

1236 ''' 

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

1238 

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

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

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

1242 ''' 

1243 _C = self.__class__ 

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

1245 **origin_which)) # PYCHOK yield 

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

1247 

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

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

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

1251# ''' 

1252# ps = self._ps 

1253# while len(ps) > 1: 

1254# p = ps.pop() 

1255# if p: 

1256# n = self._n 

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

1258# self._n = n 

1259# break 

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

1261 

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

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

1264 

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

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

1267 

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

1269 

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

1271 

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

1273 

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

1275 ''' 

1276 if _isFsum_2Tuple(xs): 

1277 self._facc_scalar(xs._ps) 

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

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

1280 self._facc_scalar_(x) 

1281 elif xs: # _xiterable(xs) 

1282 self._facc(xs) 

1283 return self 

1284 

1285 def fadd_(self, *xs): 

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

1287 

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

1289 or L{Fsum2Tuple}), all positional. 

1290 

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

1292 ''' 

1293 return self._facc_args(xs) 

1294 

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

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

1297 ''' 

1298 if _isFsum_2Tuple(other): 

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

1300 elif self._scalar(other, op): 

1301 self._facc_scalar_(other, **up) 

1302 return self 

1303 

1304 fcopy = copy # for backward compatibility 

1305 fdiv = __itruediv__ 

1306 fdivmod = __divmod__ 

1307 

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

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

1310 ''' 

1311 # result mostly follows CPython function U{float_divmod 

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

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

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

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

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

1317 

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

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

1320 self += other 

1321 q -= 1 

1322# t = self.signOf() 

1323# if t and t != s: 

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

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

1326 

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

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

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

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

1331 ''' 

1332 # assert _xiterablen(cs) 

1333 try: 

1334 n = len(cs) 

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

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

1337 H._mul_scalar 

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

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

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

1341 H._fadd(c, up=False) 

1342 else: # x == 0 

1343 H = cs[0] if n else 0 

1344 self._fadd(H) 

1345 except Exception as X: 

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

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

1348 return self 

1349 

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

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

1352 ''' 

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

1354 return other 

1355 E = _NonfiniteError(other) 

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

1357 

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

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

1360 

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

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

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

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

1365 

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

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

1368 

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

1370 B{C{RESIDUAL}}. 

1371 

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

1373 ''' 

1374 i, r = self._fint2 

1375 if r: 

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

1377 if R: 

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

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

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

1381 

1382 def fint2(self, **name): 

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

1384 I{integer} residual. 

1385 

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

1387 

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

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

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

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

1392 ''' 

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

1394 

1395 @Property 

1396 def _fint2(self): # see ._fset 

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

1398 ''' 

1399 s, r = self._nfprs2 

1400 if _isfinite(s): 

1401 i = int(s) 

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

1403 float(s - i)) or INT0 

1404 else: # INF, NAN, NINF 

1405 i = float(s) 

1406# r = _NONFINITEr 

1407 return i, r # Fsum2Tuple? 

1408 

1409 @_fint2.setter_ # PYCHOK setter_UNDERscore! 

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

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

1412 ''' 

1413 if _isfinite(s): 

1414 i = int(s) 

1415 r = (s - i) or INT0 

1416 else: # INF, NAN, NINF 

1417 i = float(s) 

1418 r = _NONFINITEr 

1419 return i, r # like _fint2.getter 

1420 

1421 @deprecated_property_RO 

1422 def float_int(self): # PYCHOK no cover 

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

1424 return self.int_float() # raiser=False 

1425 

1426 @property_RO 

1427 def floor(self): 

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

1429 C{float} in Python 2-). 

1430 

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

1432 

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

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

1435 ''' 

1436 s, r = self._fprs2 

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

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

1439 f -= 1 

1440 return f # _floor(self._n_d) 

1441 

1442# ffloordiv = __ifloordiv__ # for naming consistency? 

1443# floordiv = __floordiv__ # for naming consistency? 

1444 

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

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

1447 ''' 

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

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

1450 

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

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

1453 

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

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

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

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

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

1459 ''' 

1460 op = self.fma.__name__ 

1461 _fs = self._ps_other 

1462 try: 

1463 s, r = self._fprs2 

1464 if r: 

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

1466 f += other2 

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

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

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

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

1471 else: 

1472 f = _fma(s, other1, other2) 

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

1474 except TypeError as X: 

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

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

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

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

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

1480 return self._fset(f) 

1481 

1482 fmul = __imul__ 

1483 

1484 def _fmul(self, other, op): 

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

1486 ''' 

1487 if _isFsum_2Tuple(other): 

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

1489 f = self._mul_Fsum(other, op) 

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

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

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

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

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

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

1496 else: 

1497 s = self._scalar(other, op) 

1498 f = self._mul_scalar(s, op) 

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

1500 

1501 @deprecated_method 

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

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

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

1505 

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

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

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

1509 

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

1511 positional. 

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

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

1514 default (C{bool}). 

1515 

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

1517 

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

1519 ''' 

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

1521 

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

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

1524 ''' 

1525 f = self._copy_2(where) 

1526 ps = f._ps 

1527 if ps and others: 

1528 op = where.__name__ 

1529 try: 

1530 for other in others: # to pinpoint errors 

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

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

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

1534 f._update() 

1535 except TypeError as X: 

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

1537 except (OverflowError, ValueError) as X: 

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

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

1540 f._fset(r) 

1541 return f 

1542 

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

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

1545 

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

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

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

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

1550 

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

1552 

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

1554 B{C{RESIDUAL}}. 

1555 

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

1557 ''' 

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

1559 

1560 fpow = __ipow__ 

1561 

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

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

1564 ''' 

1565 if mod: 

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

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

1568 elif self.is_integer(): 

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

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

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

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

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

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

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

1576 else: # pow(self, other) 

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

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

1579 

1580 def f2product(self, *two): 

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

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

1583 

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

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

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

1587 

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

1589 

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

1591 

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

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

1594 ''' 

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

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

1597 if two[0] is not None: 

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

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

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

1601 return t 

1602 

1603 @Property 

1604 def _fprs(self): 

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

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

1607 

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

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

1610 ''' 

1611 s, _ = self._fprs2 

1612 return s # ._fprs2.fsum 

1613 

1614 @_fprs.setter_ # PYCHOK setter_UNDERscore! 

1615 def _fprs(self, s): 

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

1617 ''' 

1618 return s 

1619 

1620 @Property 

1621 def _fprs2(self): 

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

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

1624 ''' 

1625 ps = self._ps 

1626 n = len(ps) 

1627 try: 

1628 if n > 2: 

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

1630 if not _isfinite(s): 

1631 ps[:] = s, # collapse ps 

1632 return Fsum2Tuple(s, _NONFINITEr) 

1633 n = len(ps) 

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

1635 if n > 2: 

1636 r = self._ps_1sum(s) 

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

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

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

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

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

1642 s = ps[0] 

1643 r = INT0 if _isfinite(s) else _NONFINITEr 

1644 else: # len(ps) == 0 

1645 s = _0_0 

1646 r = INT0 if _isfinite(s) else _NONFINITEr 

1647 ps[:] = s, 

1648 except (OverflowError, ValueError) as X: 

1649 op = _fset_op_ # INF, NAN, NINF 

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

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

1652 r = _NONFINITEr 

1653 # assert self._ps is ps 

1654 return Fsum2Tuple(s, r) 

1655 

1656 @_fprs2.setter_ # PYCHOK setter_UNDERscore! 

1657 def _fprs2(self, s_r): 

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

1659 ''' 

1660 return Fsum2Tuple(s_r) 

1661 

1662 def fset_(self, *xs): 

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

1664 

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

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

1667 positional. 

1668 

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

1670 

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

1672 ''' 

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

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

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

1676 

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

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

1679 ''' 

1680 if other is self: 

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

1682 elif _isFsum_2Tuple(other): 

1683 if op: # and not self.nonfinitesOK: 

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

1685 self._ps[:] = other._ps 

1686 self._n = n or other._n 

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

1688 Fsum._fint2._update_from(self, other) 

1689 Fsum._fprs ._update_from(self, other) 

1690 Fsum._fprs2._update_from(self, other) 

1691 elif isscalar(other): 

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

1693 self._ps[:] = s, 

1694 self._n = n or 1 

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

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

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

1698 self._fint2 = s 

1699 self._fprs = s 

1700 self._fprs2 = s, INT0 

1701 # assert self._fprs is s 

1702 else: 

1703 op = _xkwds_get1(op, op=_fset_op_) 

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

1705 return self 

1706 

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

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

1709 

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

1711 ''' 

1712 return self._facc_neg(xs) 

1713 

1714 def fsub_(self, *xs): 

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

1716 

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

1718 ''' 

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

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

1721 

1722 def _fsub(self, other, op): 

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

1724 ''' 

1725 if _isFsum_2Tuple(other): 

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

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

1728 elif other._ps: 

1729 self._facc_scalar(other._ps_neg) 

1730 elif self._scalar(other, op): 

1731 self._facc_scalar_(-other) 

1732 return self 

1733 

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

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

1736 precision running sum. 

1737 

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

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

1740 

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

1742 

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

1744 

1745 @note: Accumulation can continue after summation. 

1746 ''' 

1747 return self._facc(xs)._fprs 

1748 

1749 def fsum_(self, *xs): 

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

1751 precision running sum. 

1752 

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

1754 L{Fsum2Tuple}), all positional. 

1755 

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

1757 

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

1759 ''' 

1760 return self._facc_args(xs)._fprs 

1761 

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

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

1764 

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

1766 

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

1768 ''' 

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

1770 

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

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

1773 

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

1775 

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

1777 ''' 

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

1779 

1780 @property_RO 

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

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

1783 

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

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

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

1787 overridden with C{name_f2product_nonfinites_RESIDUAL} and 

1788 with any C{xs} accumulated. 

1789 ''' 

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

1791 nonfinites=self.nonfinites(), 

1792 RESIDUAL =self.RESIDUAL()) 

1793 if name_f2product_nonfinites_RESIDUAL: # overwrites 

1794 kwds.update(name_f2product_nonfinites_RESIDUAL) 

1795 f = Fsum(**kwds) 

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

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

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

1799 

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

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

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

1803 

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

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

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

1807 

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

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

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

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

1812 to be I{exact}. 

1813 

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

1815 ''' 

1816 t = self._facc(xs)._fprs2 

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

1818 

1819 def fsum2_(self, *xs): 

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

1821 precision running sum and the I{differential}. 

1822 

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

1824 L{Fsum2Tuple}), all positional. 

1825 

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

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

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

1829 

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

1831 ''' 

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

1833 

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

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

1836 ''' 

1837 p, q = self._fprs2 

1838 if xs: 

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

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

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

1842 r, _ = _s_r(d, r) 

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

1844 else: 

1845 return p, _0_0 

1846 

1847 def fsumf_(self, *xs): 

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

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

1850 ''' 

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

1852 

1853 def Fsumf_(self, *xs): 

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

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

1856 ''' 

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

1858 

1859 def fsum2f_(self, *xs): 

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

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

1862 ''' 

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

1864 

1865# ftruediv = __itruediv__ # for naming consistency? 

1866 

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

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

1869 ''' 

1870 n = _1_0 

1871 if _isFsum_2Tuple(other): 

1872 if other is self or self == other: 

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

1874 d, r = other._fprs2 

1875 if r: 

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

1877 if R: 

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

1879 d, n = other.as_integer_ratio() 

1880 else: 

1881 d = self._scalar(other, op) 

1882 try: 

1883 s = n / d 

1884 except Exception as X: 

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

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

1887 return self._fset(f) 

1888 

1889 @property_RO 

1890 def imag(self): 

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

1892 

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

1894 ''' 

1895 return _0_0 

1896 

1897 def int_float(self, **raiser_RESIDUAL): 

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

1899 

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

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

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

1903 

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

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

1906 is zero or not significant. 

1907 

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

1909 B{C{RESIDUAL}}. 

1910 

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

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

1913 ''' 

1914 s, r = self._fint2 

1915 if r: 

1916 s, r = self._fprs2 

1917 if r: # PYCHOK no cover 

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

1919 if R: 

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

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

1922 s = float(s) 

1923 return s 

1924 

1925 def is_exact(self): 

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

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

1928 ''' 

1929 return self.residual is INT0 

1930 

1931 def is_finite(self): # in .constants 

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

1933 

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

1935 ''' 

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

1937 

1938 def is_integer(self): 

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

1940 

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

1942 ''' 

1943 s, r = self._fint2 

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

1945 

1946 def is_math_fma(self): 

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

1948 

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

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

1951 C{PyGeodesy} implementation. 

1952 ''' 

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

1954 

1955 def is_math_fsum(self): 

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

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

1958 

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

1960 otherwise. 

1961 ''' 

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

1963 

1964 def is_scalar(self, **raiser_RESIDUAL): 

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

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

1967 

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

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

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

1971 

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

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

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

1975 

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

1977 B{C{RESIDUAL}}. 

1978 

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

1980 L{Fsum.as_iscalar}. 

1981 ''' 

1982 s, r = self._fprs2 

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

1984 

1985 def _mul_Fsum(self, other, op): 

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

1987 ''' 

1988 # assert _isFsum_2Tuple(other) 

1989 if self._ps and other._ps: 

1990 try: 

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

1992 except Exception as X: 

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

1994 else: 

1995 f = _0_0 

1996 return f 

1997 

1998 def _mul_reduce(self, *others): 

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

2000 ''' 

2001 r = _1_0 

2002 for f in others: 

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

2004 return r 

2005 

2006 def _mul_scalar(self, factor, op): 

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

2008 ''' 

2009 # assert isscalar(factor) 

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

2011 f = self if factor == _1_0 else ( 

2012 self._neg if factor == _N_1_0 else 

2013 self._ps_mul(op, factor).as_iscalar) 

2014 else: 

2015 f = _0_0 

2016 return f 

2017 

2018# @property_RO 

2019# def _n_d(self): 

2020# n, d = self.as_integer_ratio() 

2021# return n / d 

2022 

2023 @property_RO 

2024 def _neg(self): 

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

2026 ''' 

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

2028 

2029 @property_RO 

2030 def _nfprs2(self): 

2031 '''(INTERNAL) Handle I{non-finite} C{_fprs2}. 

2032 ''' 

2033 try: # to handle nonfiniterrors, etc. 

2034 t = self._fprs2 

2035 except (OverflowError, ValueError): 

2036 t = Fsum2Tuple(sum(self._ps), _NONFINITEr) 

2037 return t 

2038 

2039 def nonfinites(self, *OK): 

2040 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan} 

2041 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively 

2042 C{ValueError} exceptions, overriding the L{nonfiniterrors} default. 

2043 

2044 @arg OK: If omitted, leave the override unchanged, if C{True}, 

2045 I{non-finites} are C{OK}, if C{False} throw exceptions 

2046 or if C{None} remove the override (C{bool} or C{None}). 

2047 

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

2049 

2050 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}. 

2051 

2052 @note: Use property L{nonfinitesOK<Fsum.nonfinitesOK>} to determine 

2053 whether I{non-finites} are C{OK} for this L{Fsum} and by the 

2054 L{nonfiniterrors} default. 

2055 ''' 

2056 _ks = Fsum._nonfinites_isfine_kwds 

2057 if OK: # delattrof(self, _isfine=None) 

2058 k = _xkwds_pop(self.__dict__, _isfine=None) 

2059 if OK[0] is not None: 

2060 self._isfine = _ks[bool(OK[0])] 

2061 self._update() 

2062 else: # getattrof(self, _isfine=None) 

2063 k = _xkwds_get(self.__dict__, _isfine=None) 

2064 # dict(map(reversed, _ks.items())).get(k, None) 

2065 # raises a TypeError: unhashable type: 'dict' 

2066 return True if k is _ks[True] else ( 

2067 False if k is _ks[False] else None) 

2068 

2069 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK), 

2070 False: dict(_isfine=_isfinite)} 

2071 

2072 @property_RO 

2073 def nonfinitesOK(self): 

2074 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}). 

2075 ''' 

2076# nf = self.nonfinites() 

2077# if nf is None: 

2078# nf = not nonfiniterrors() 

2079 return _isOK_or_finite(INF, **self._isfine) 

2080 

2081 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None): 

2082 '''(INTERNAL) Handle a I{non-finite} exception. 

2083 ''' 

2084 if nonfinites is None: 

2085 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser) 

2086 if not nonfinites: 

2087 raise self._ErrorX(X, op, f) 

2088 return f 

2089 

2090 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL): 

2091 '''(INTERNAL) Re/set options from keyword arguments. 

2092 ''' 

2093 if f2product is not None: 

2094 self.f2product(f2product) 

2095 if nonfinites is not None: 

2096 self.nonfinites(nonfinites) 

2097 if name_RESIDUAL: # MUST be last 

2098 n, kwds = _name2__(**name_RESIDUAL) 

2099 if kwds: 

2100 R = Fsum._RESIDUAL 

2101 t = _threshold(R, **kwds) 

2102 if t != R: 

2103 self._RESIDUAL = t 

2104 if n: 

2105 self.name = n # self.rename(n) 

2106 

2107 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over 

2108 '''(INTERNAL) Return C{Fsum(1) / B{x}}. 

2109 ''' 

2110 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL) 

2111 

2112 @property_RO 

2113 def partials(self): 

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

2115 ''' 

2116 return tuple(self._ps) 

2117 

2118 def pow(self, x, *mod, **raiser_RESIDUAL): 

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

2120 

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

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

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

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

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

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

2127 

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

2129 result (L{Fsum}). 

2130 

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

2132 B{C{RESIDUAL}}. 

2133 

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

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

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

2137 

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

2139 and L{Fsum.root}. 

2140 ''' 

2141 f = self._copy_2(self.pow) 

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

2143 

2144 def _pow(self, other, unused, op, **raiser_RESIDUAL): 

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

2146 ''' 

2147 if _isFsum_2Tuple(other): 

2148 f = self._pow_Fsum(other, op, **raiser_RESIDUAL) 

2149 elif self._scalar(other, op): 

2150 x = self._finite(other, op=op) 

2151 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

2152 else: 

2153 f = self._pow_0_1(0, other) 

2154 return f 

2155 

2156 def _pow_0_1(self, x, other): 

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

2158 ''' 

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

2160 

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

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

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

2164 ''' 

2165 

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

2167 m = mod[0] 

2168 # assert _isFsum_2Tuple(b) 

2169 

2170 def _s(s, r): 

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

2172 if R: 

2173 raise self._ResidualError(op, other, r, mod=m, **R) 

2174 return s 

2175 

2176 b = _s(*(b._fprs2 if m is None else b._fint2)) 

2177 x = _s(*_2s_r(x)) 

2178 

2179 try: 

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

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

2182 if iscomplex(s): 

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

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

2185 _ = _2finite(s, **self._isfine) # ignore float 

2186 return s 

2187 except Exception as X: 

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

2189 

2190 def _pow_Fsum(self, other, op, **raiser_RESIDUAL): 

2191 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}. 

2192 ''' 

2193 # assert _isFsum_2Tuple(other) 

2194 x, r = other._fprs2 

2195 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

2196 if f and r: 

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

2198 return f 

2199 

2200 def _pow_int(self, x, other, op, **raiser_RESIDUAL): 

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

2202 ''' 

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

2204 ps = self._ps 

2205 if len(ps) > 1: 

2206 _mul_Fsum = Fsum._mul_Fsum 

2207 if x > 4: 

2208 p = self 

2209 f = self if (x & 1) else self._Fsum_as(_1_0) 

2210 m = x >> 1 # // 2 

2211 while m: 

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

2213 if (m & 1): 

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

2215 m >>= 1 # //= 2 

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

2217 f = _mul_Fsum(self, self, op) 

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

2219 p = self if x < 4 else f 

2220 f = _mul_Fsum(f, p, op) 

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

2222 f = self._pow_0_1(x, other) 

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

2224 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL) 

2225 else: # PYCHOK no cover 

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

2227 f = 0 if x else 1 

2228 return f 

2229 

2230 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL): 

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

2232 ''' 

2233 s, r = self._fprs2 

2234 if r: 

2235 # assert s != 0 

2236 if isint(x, both=True): # self**int 

2237 x = int(x) 

2238 y = abs(x) 

2239 if y > 1: 

2240 f = self._pow_int(y, other, op, **raiser_RESIDUAL) 

2241 if x > 0: # i.e. > 1 

2242 return f # Fsum or scalar 

2243 # assert x < 0 # i.e. < -1 

2244 if _isFsum(f): 

2245 s, r = f._fprs2 

2246 if r: 

2247 return self._1_Over(f, op, **raiser_RESIDUAL) 

2248 else: # scalar 

2249 s = f 

2250 # use s**(-1) to get the CPython 

2251 # float_pow error iff s is zero 

2252 x = -1 

2253 elif x < 0: # self**(-1) 

2254 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self 

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

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

2257 else: # self**fractional 

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

2259 if R: 

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

2261 n, d = self.as_integer_ratio() 

2262 if abs(n) > abs(d): 

2263 n, d, x = d, n, (-x) 

2264 s = n / d 

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

2266 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL) 

2267 

2268 def _ps_acc(self, ps, xs, up=True, **unused): 

2269 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}. 

2270 ''' 

2271 n = 0 

2272 _2s = _2sum 

2273 _fi = self._isfine 

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

2275 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine) 

2276 if x: 

2277 i = 0 

2278 for p in ps: 

2279 x, p = _2s(x, p, **_fi) 

2280 if p: 

2281 ps[i] = p 

2282 i += 1 

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

2284 n += 1 

2285 if n: 

2286 self._n += n 

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

2288 if up: 

2289 self._update() 

2290# x = sum(ps) 

2291# if not _isOK_or_finite(x, **fi): 

2292# ps[:] = x, # collapse ps 

2293 return ps 

2294 

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

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

2297 each scalar C{factor} and accumulate into an C{Fsum}. 

2298 ''' 

2299 def _psfs(ps, fs, _isfine=_isfinite): 

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

2301 ps, fs = fs, ps 

2302 if self._f2product: 

2303 fs, p = _2split3s(fs), fs 

2304 if len(ps) > 1 and fs is not p: 

2305 fs = tuple(fs) # several ps 

2306 _pfs = _2products 

2307 else: 

2308 def _pfs(p, fs): 

2309 return (p * f for f in fs) 

2310 

2311 for p in ps: 

2312 for f in _pfs(p, fs): 

2313 yield f if _isfine(f) else _nfError(f) 

2314 

2315 fs = _psfs(self._ps, factors, **self._isfine) 

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

2317 return f 

2318 

2319 @property_RO 

2320 def _ps_neg(self): 

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

2322 ''' 

2323 for p in self._ps: 

2324 yield -p 

2325 

2326 def _ps_other(self, op, other): 

2327 '''(INTERNAL) Yield C{other} as C{scalar}s. 

2328 ''' 

2329 if _isFsum_2Tuple(other): 

2330 for p in other._ps: 

2331 yield p 

2332 else: 

2333 yield self._scalar(other, op) 

2334 

2335 def _ps_1sum(self, *less): 

2336 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars. 

2337 ''' 

2338 def _1psls(ps, ls): 

2339 yield _1_0 

2340 for p in ps: 

2341 yield p 

2342 for p in ls: 

2343 yield -p 

2344 yield _N_1_0 

2345 

2346 return _fsum(_1psls(self._ps, less)) 

2347 

2348 def _raiser(self, r, s, raiser=True, **RESIDUAL): 

2349 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold 

2350 I{and} is residual C{r} I{non-zero} or I{significant} (for a 

2351 negative respectively positive C{RESIDUAL} threshold)? 

2352 ''' 

2353 if r and raiser: 

2354 t = self._RESIDUAL 

2355 if RESIDUAL: 

2356 t = _threshold(t, **RESIDUAL) 

2357 if t < 0 or (s + r) != s: 

2358 q = (r / s) if s else s # == 0. 

2359 if fabs(q) > fabs(t): 

2360 return dict(ratio=q, R=t) 

2361 return {} 

2362 

2363 rdiv = __rtruediv__ 

2364 

2365 @property_RO 

2366 def real(self): 

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

2368 

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

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

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

2372 ''' 

2373 return float(self) 

2374 

2375 @property_RO 

2376 def residual(self): 

2377 '''Get this instance' residual or residue (C{float} or C{int}): 

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

2379 

2380 @note: The C{residual is INT0} iff the precision running 

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

2382 

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

2384 ''' 

2385 return self._fprs2.residual 

2386 

2387 def RESIDUAL(self, *threshold): 

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

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

2390 

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

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

2393 C{None}, restore the default set with env variable 

2394 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

2395 current setting. 

2396 

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

2398 

2399 @raise ResidualError: Invalid B{C{threshold}}. 

2400 

2401 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio} 

2402 C{residual / fsum} exceeds the given B{C{threshold}} and (2) 

2403 the C{residual} is non-zero and (3) is I{significant} vs the 

2404 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional 

2405 keyword argument C{raiser=False} is missing. Specify a 

2406 negative B{C{threshold}} for only non-zero C{residual} 

2407 testing without the I{significant} case. 

2408 ''' 

2409 r = self._RESIDUAL 

2410 if threshold: 

2411 t = threshold[0] 

2412 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ... 

2413 (_0_0 if t else _1_0) if isbool(t) else 

2414 _threshold(t)) # ... backward compatibility 

2415 return r 

2416 

2417 def _ResidualError(self, op, other, residual, **mod_R): 

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

2419 ''' 

2420 def _p(mod=None, R=0, **unused): # ratio=0 

2421 return (_non_zero_ if R < 0 else _significant_) \ 

2422 if mod is None else _integer_ 

2423 

2424 t = _stresidual(_p(**mod_R), residual, **mod_R) 

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

2426 

2427 def root(self, root, **raiser_RESIDUAL): 

2428 '''Return C{B{self}**(1 / B{root})} as L{Fsum}. 

2429 

2430 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

2432 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar} 

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

2434 

2435 @return: The C{self ** (1 / B{root})} result (L{Fsum}). 

2436 

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

2438 B{C{RESIDUAL}}. 

2439 

2440 @see: Method L{Fsum.pow}. 

2441 ''' 

2442 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL) 

2443 f = self._copy_2(self.root) 

2444 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x) 

2445 

2446 def _scalar(self, other, op, **txt): 

2447 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}. 

2448 ''' 

2449 if isscalar(other): 

2450 return other 

2451 raise self._Error(op, other, _TypeError, **txt) # _invalid_ 

2452 

2453 def signOf(self, res=True): 

2454 '''Determine the sign of this instance. 

2455 

2456 @kwarg res: If C{True}, consider the residual, 

2457 otherwise ignore the latter (C{bool}). 

2458 

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

2460 ''' 

2461 s, r = self._nfprs2 

2462 r = (-r) if res else 0 

2463 return _signOf(s, r) 

2464 

2465 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature 

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

2467 

2468 @kwarg lenc_prec_sep_fmt: Optional keyword arguments 

2469 for method L{Fsum.toStr}. 

2470 

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

2472 ''' 

2473 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt)) 

2474 

2475 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature 

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

2477 

2478 @kwarg lenc: If C{True}, include the current C{[len]} of this 

2479 L{Fsum} enclosed in I{[brackets]} (C{bool}). 

2480 @kwarg prec_sep_fmt: Optional keyword arguments for method 

2481 L{Fsum2Tuple.toStr}. 

2482 

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

2484 ''' 

2485 p = self.classname 

2486 if lenc: 

2487 p = Fmt.SQUARE(p, len(self)) 

2488 n = _enquote(self.name, white=_UNDER_) 

2489 t = self._nfprs2.toStr(**prec_sep_fmt) 

2490 return NN(p, _SPACE_, n, t) 

2491 

2492 def _truediv(self, other, op, **raiser_RESIDUAL): 

2493 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}. 

2494 ''' 

2495 f = self._copy_2(self.__truediv__) 

2496 return f._ftruediv(other, op, **raiser_RESIDUAL) 

2497 

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

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

2500 ''' 

2501 if updated: 

2502 _pop = self.__dict__.pop 

2503 for p in _ROs: 

2504 _ = _pop(p, None) 

2505# Fsum._fint2._update(self) 

2506# Fsum._fprs ._update(self) 

2507# Fsum._fprs2._update(self) 

2508 return self # for .fset_ 

2509 

2510_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update 

2511 

2512if _NONFINITES == _std_: # PYCHOK no cover 

2513 _ = nonfiniterrors(False) 

2514 

2515 

2516def _Float_Int(arg, **name_Error): 

2517 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit. 

2518 ''' 

2519 U = Int if isint(arg) else Float 

2520 return U(arg, **name_Error) 

2521 

2522 

2523class DivMod2Tuple(_NamedTuple): 

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

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

2526 

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

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

2529 ''' 

2530 _Names_ = ('div', 'mod') 

2531 _Units_ = (_Float_Int, Fsum) 

2532 

2533 

2534class Fsum2Tuple(_NamedTuple): # in .fstats 

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

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

2537 item is C{float} or C{int}. 

2538 

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

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

2541 ''' 

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

2543 _Units_ = (_Float_Int, _Float_Int) 

2544 

2545 def __abs__(self): # in .fmath 

2546 return self._Fsum.__abs__() 

2547 

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

2549 return bool(self._Fsum) 

2550 

2551 def __eq__(self, other): 

2552 return self._other_op(other, self.__eq__) 

2553 

2554 def __float__(self): 

2555 return self._Fsum.__float__() 

2556 

2557 def __ge__(self, other): 

2558 return self._other_op(other, self.__ge__) 

2559 

2560 def __gt__(self, other): 

2561 return self._other_op(other, self.__gt__) 

2562 

2563 def __le__(self, other): 

2564 return self._other_op(other, self.__le__) 

2565 

2566 def __lt__(self, other): 

2567 return self._other_op(other, self.__lt__) 

2568 

2569 def __int__(self): 

2570 return self._Fsum.__int__() 

2571 

2572 def __ne__(self, other): 

2573 return self._other_op(other, self.__ne__) 

2574 

2575 def __neg__(self): 

2576 return self._Fsum.__neg__() 

2577 

2578 __nonzero__ = __bool__ # Python 2- 

2579 

2580 def __pos__(self): 

2581 return self._Fsum.__pos__() 

2582 

2583 def as_integer_ratio(self): 

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

2585 

2586 @see: Method L{Fsum.as_integer_ratio} for further details. 

2587 ''' 

2588 return self._Fsum.as_integer_ratio() 

2589 

2590 @property_RO 

2591 def _fint2(self): 

2592 return self._Fsum._fint2 

2593 

2594 @property_RO 

2595 def _fprs2(self): 

2596 return self._Fsum._fprs2 

2597 

2598 @Property_RO 

2599 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats 

2600 s, r = _s_r(*self) 

2601 ps = (r, s) if r else (s,) 

2602 return _Psum(ps, name=self.name) 

2603 

2604 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL): 

2605 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}. 

2606 ''' 

2607 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL) 

2608 

2609 def is_exact(self): 

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

2611 ''' 

2612 return self._Fsum.is_exact() 

2613 

2614 def is_finite(self): # in .constants 

2615 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}). 

2616 

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

2618 ''' 

2619 return self._Fsum.is_finite() 

2620 

2621 def is_integer(self): 

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

2623 ''' 

2624 return self._Fsum.is_integer() 

2625 

2626 def _mul_scalar(self, other, op): # for Fsum._fmul 

2627 return self._Fsum._mul_scalar(other, op) 

2628 

2629 @property_RO 

2630 def _n(self): 

2631 return self._Fsum._n 

2632 

2633 def _other_op(self, other, which): 

2634 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum) 

2635 return getattr(C, which.__name__)(s, other) 

2636 

2637 @property_RO 

2638 def _ps(self): 

2639 return self._Fsum._ps 

2640 

2641 @property_RO 

2642 def _ps_neg(self): 

2643 return self._Fsum._ps_neg 

2644 

2645 def signOf(self, **res): 

2646 '''Like method L{Fsum.signOf}. 

2647 ''' 

2648 return self._Fsum.signOf(**res) 

2649 

2650 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature 

2651 '''Return this L{Fsum2Tuple} as string (C{str}). 

2652 

2653 @kwarg fmt: Optional C{float} format (C{letter}). 

2654 @kwarg prec_sep: Optional keyword arguments for function 

2655 L{fstr<streprs.fstr>}. 

2656 ''' 

2657 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep)) 

2658 

2659_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines 

2660 

2661 

2662class ResidualError(_ValueError): 

2663 '''Error raised for a division, power or root operation of 

2664 an L{Fsum} instance with a C{residual} I{ratio} exceeding 

2665 the L{RESIDUAL<Fsum.RESIDUAL>} threshold. 

2666 

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

2668 ''' 

2669 pass 

2670 

2671 

2672try: 

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

2674 

2675 # make sure _fsum works as expected (XXX check 

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

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

2678 del _fsum # nope, remove _fsum ... 

2679 raise ImportError() # ... use _fsum below 

2680 

2681 _sum = _fsum # in .elliptic 

2682except ImportError: 

2683 _sum = sum # in .elliptic 

2684 

2685 def _fsum(xs): 

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

2687 ''' 

2688 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True) 

2689 return float(F._facc(xs, up=False)) 

2690 

2691 

2692def fsum(xs, nonfinites=None, **floats): 

2693 '''Precision floating point summation from Python's C{math.fsum}. 

2694 

2695 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2696 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if 

2697 C{False} I{non-finites} raise an Overflow-/ValueError or if 

2698 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}). 

2699 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use 

2700 keyword argument C{B{nonfinites}=False} instead. 

2701 

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

2703 

2704 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow. 

2705 

2706 @raise TypeError: Invalid B{C{xs}} item. 

2707 

2708 @raise ValueError: Invalid or C{NAN} B{C{xs}} item. 

2709 

2710 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites}, 

2711 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}. 

2712 ''' 

2713 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0 

2714 

2715 

2716def fsum_(*xs, **nonfinites): 

2717 '''Precision floating point summation of all positional items. 

2718 

2719 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2720 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2721 

2722 @see: Function L{fsum<fsums.fsum>} for further details. 

2723 ''' 

2724 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1? 

2725 

2726 

2727def fsumf_(*xs): 

2728 '''Precision floating point summation of all positional items with I{non-finites} C{OK}. 

2729 

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

2731 all positional. 

2732 

2733 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2734 ''' 

2735 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1? 

2736 

2737 

2738def fsum1(xs, **nonfinites): 

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

2740 

2741 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2742 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2743 

2744 @see: Function L{fsum<fsums.fsum>} for further details. 

2745 ''' 

2746 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0 

2747 

2748 

2749def fsum1_(*xs, **nonfinites): 

2750 '''Precision floating point summation of all positional items, 1-primed. 

2751 

2752 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2753 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2754 

2755 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2756 ''' 

2757 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1? 

2758 

2759 

2760def fsum1f_(*xs): 

2761 '''Precision floating point summation of all positional items, 1-primed and 

2762 with I{non-finites} C{OK}. 

2763 

2764 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2765 ''' 

2766 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0 

2767 

2768 

2769def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers. 

2770 _x_kwds = dict(_x= (_passarg if nfOK else _2finite), 

2771 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds 

2772 _x_kwds.update(kwds) 

2773 return _x_kwds 

2774 

2775 

2776def _X_ps(X): # default C{_X} handler 

2777 return X._ps # lambda X: X._ps 

2778 

2779 

2780def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc 

2781 origin=0, which=None, **_Cdot): 

2782 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s. 

2783 ''' 

2784 i, x = 0, xs 

2785 try: 

2786 for i, x in enumerate(_xiterable(xs)): 

2787 if isinstance(x, _Fsum_2Tuple_types): 

2788 for p in _X(x): 

2789 yield p if _isfine(p) else _nfError(p) 

2790 else: 

2791 f = _x(x) 

2792 yield f if _isfine(f) else _nfError(f) 

2793 

2794 except (OverflowError, TypeError, ValueError) as X: 

2795 t = _xsError(X, xs, i + origin, x) 

2796 if which: # prefix invokation 

2797 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot) 

2798 t = _COMMASPACE_(w, t) 

2799 raise _xError(X, t, txt=None) 

2800 

2801 

2802def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0 

2803 '''(INTERNAL) Precision summation of C{xs} with conditions. 

2804 ''' 

2805 if floats: # for backward compatibility 

2806 nonfinites = _xkwds_get1(floats, floats=nonfinites) 

2807 elif nonfinites is None: 

2808 nonfinites = not nonfiniterrors() 

2809 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) 

2810 return _fsum(_1primed(fs) if primed else fs) 

2811 

2812 

2813# delete all decorators, etc. 

2814del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \ 

2815 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \ 

2816 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _getPYGEODESY, _std_ 

2817 

2818if __name__ == '__main__': 

2819 

2820 # usage: python3 -m pygeodesy.fsums 

2821 

2822 def _test(n): 

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

2824 from pygeodesy import frandoms, printf 

2825 

2826 printf(_fsum.__name__, end=_COMMASPACE_) 

2827 printf(_psum.__name__, end=_COMMASPACE_) 

2828 

2829 F = Fsum() 

2830 if F.is_math_fsum(): 

2831 for t in frandoms(n, seeded=True): 

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

2833 printf(_DOT_, end=NN) 

2834 printf(NN) 

2835 

2836 _test(128) 

2837 

2838# **) MIT License 

2839# 

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

2841# 

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

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

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

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

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

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

2848# 

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

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

2851# 

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

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

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

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

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

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

2858# OTHER DEALINGS IN THE SOFTWARE.