Coverage for pygeodesy/fsums.py: 95%

1092 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-29 12:40 -0400

1 

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

3 

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

5Python's C{math.fsum}, but enhanced with I{precision running} summation 

6plus optionally, accurate I{TwoProduct} multiplication. 

7 

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

9Python 3.13 and newer or an equivalent C{fma} implementation for 

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

11variable 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 _ # noqa: E702 ; 

41 

42from pygeodesy.basics import _gcd, 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, _envPYGEODESY, _passarg, typename # _sizeof 

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

53 _not_finite_, _SPACE_, _std_, _UNDER_ 

54# from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS # from .named 

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

56 _NotImplemented, _ALL_LAZY, _MODS 

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__ = '25.05.12' 

68 

69from pygeodesy.interns import ( 

70 _PLUS_ as _add_op_, # in .auxilats.auxAngle 

71 _DSLASH_ as _floordiv_op_, 

72 _EQUAL_ as _fset_op_, 

73 _RANGLE_ as _gt_op_, 

74 _LANGLE_ as _lt_op_, 

75 _PERCENT_ as _mod_op_, 

76 _STAR_ as _mul_op_, 

77 _NOTEQUAL_ as _ne_op_, 

78 _DSTAR_ as _pow_op_, 

79 _DASH_ as _sub_op_, # in .auxilats.auxAngle 

80 _SLASH_ as _truediv_op_ 

81) 

82_divmod_op_ = _floordiv_op_ + _mod_op_ 

83_F2PRODUCT = _envPYGEODESY('FSUM_F2PRODUCT') 

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

85_integer_ = 'integer' 

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

87_NONFINITEr = _0_0 # NOT INT0! 

88_NONFINITES = _envPYGEODESY('FSUM_NONFINITES') 

89_non_zero_ = 'non-zero' 

90_RESIDUAL_0_0 = _envPYGEODESY('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 C{x} 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 from pygeodesy.basics import _integer_ratio2 

136 

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

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

139 # the same accuracy, but ~14x slower 

140 (n, d), (nb, db), (nc, dc) = map(_integer_ratio2, a_b_c) 

141 # n, d = (n * nb * dc + d * db * nc), (d * db * dc) 

142 d *= db 

143 n *= nb * dc 

144 n += nc * d 

145 d *= dc 

146 try: 

147 n, d = _n_d2(n, d) 

148 r = float(n / d) 

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

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

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

152 else: 

153 _integer_ratio2 = None # redef, in Fsum.is_math_fma 

154 

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

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

157 # the same accuracy, but ~13x slower 

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

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

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

161 

162 def _fmaX(r, *a_b_c): # PYCHOK no cover 

163 # handle non-finite fma result as Python 3.13+ C-function U{math_fma_impl 

164 # <https://GitHub.com/python/cpython/blob/main/Modules/mathmodule.c#L2305>}: 

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

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

167 if isnan(r): 

168 def _x(x): 

169 return not isnan(x) 

170 else: # non-finite, non-NAN 

171 _x = _isfinite 

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

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

174 return r 

175 

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

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

178 # TwoProduct U{Algorithm 3.3<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}, also 

179 # in Python 3.13+ C{Modules/mathmodule.c} under #ifndef UNRELIABLE_FMA ... #else ... 

180 _, a, b = _2split3(x) 

181 for y, c, d in y3s: 

182 y *= x 

183 yield y 

184 if _isfinite(y): 

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

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

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

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

189 yield a * c - y 

190 yield b * c 

191 if d: 

192 yield a * d 

193 yield b * d 

194 for z in zs: 

195 yield z 

196 

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

198 

199 def _2split3(x): 

200 # Split U{Algorithm 3.2 

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

202 a = c = x * _2FACTOR 

203 a -= c - x 

204 b = x - a 

205 return x, a, b 

206 

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

208 return map(_2split3, xs) 

209 

210 

211def f2product(two=None): 

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

213 

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

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

216 

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

218 

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

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

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

222 equivalent, slower implementation when not available. 

223 ''' 

224 t = Fsum._f2product 

225 if two is not None: 

226 Fsum._f2product = bool(two) 

227 return t 

228 

229 

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

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

232 ''' 

233 return Fsum()._facc_xsum(xs, up=False) 

234 

235 

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

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

238 ''' 

239 return Fsum()._facc_xsum(_1primed(xs), origin=-1, up=False) 

240 

241 

242def _halfeven(s, r, p): 

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

244 ''' 

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

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

247 r *= 2 

248 t = s + r 

249 if r == (t - s): 

250 s = t 

251 return s 

252 

253 

254def _isFsum(x): # in .fmath 

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

256 ''' 

257 return isinstance(x, Fsum) 

258 

259 

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

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

262 ''' 

263 return isinstance(x, _Fsum_2Tuple_types) 

264 

265 

266def _isOK(unused): 

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

268 ''' 

269 return True 

270 

271 

272def _isOK_or_finite(x, _isfine=_isfinite): 

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

274 ''' 

275 # assert _isin(_isfine, _isOK, _isfinite) 

276 return _isfine(x) # C{bool} 

277 

278 

279def _n_d2(n, d): 

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

281 ''' 

282 try: 

283 c = _gcd(n, d) 

284 if c > 1: 

285 return (n // c), (d // c) 

286 except TypeError: # non-int float 

287 pass 

288 return n, d 

289 

290 

291def _nfError(x, *args): 

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

293 ''' 

294 E = _NonfiniteError(x) 

295 t = Fmt.PARENSPACED(_not_finite_, x) 

296 if args: # in _fmaX, _2sum 

297 return E(txt=t, *args) 

298 raise E(t, txt=None) 

299 

300 

301def _NonfiniteError(x): 

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

303 ''' 

304 return _OverflowError if isinf(x) else ( 

305 _ValueError if isnan(x) else _AssertionError) 

306 

307 

308def nonfiniterrors(raiser=None): 

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

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

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

312 

313 @kwarg raiser: If C{True}, throw exceptions, if C{False} handle 

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

315 the setting unchanged. 

316 

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

318 

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

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

321 ''' 

322 d = Fsum._isfine 

323 if raiser is not None: 

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

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

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

327 

328 

329def _1primed(xs): # in .fmath 

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

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

332 ''' 

333 yield _1_0 

334 for x in xs: 

335 yield x 

336 yield _N_1_0 

337 

338 

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

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

341 ''' 

342 # assert isinstance(ps, list) 

343 i = len(ps) - 1 

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

345 while i > 0: 

346 i -= 1 

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

348 if r: # sum(ps) became inexact 

349 if s: 

350 ps[i:] = r, s 

351 if i > 0: 

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

353 break # return s 

354 s = r # PYCHOK no cover 

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

356 i = 0 # collapse ps 

357 if ps: 

358 s += sum(ps) 

359 ps[i:] = s, 

360 return s 

361 

362 

363def _Psum(ps, **name_f2product_nonfinites_RESIDUAL): 

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

365 ''' 

366 F = Fsum(**name_f2product_nonfinites_RESIDUAL) 

367 if ps: 

368 F._ps[:] = ps 

369 F._n = len(F._ps) 

370 return F 

371 

372 

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

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

375 ''' 

376 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL) 

377 

378 

379def _residue(other): 

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

381 ''' 

382 try: 

383 r = other.residual 

384 except AttributeError: 

385 r = None # float, int, other 

386 return r 

387 

388 

389def _s_r2(s, r): 

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

391 ''' 

392 if _isfinite(s): 

393 if r: 

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

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

396 else: 

397 r = INT0 

398 else: 

399 r = _NONFINITEr 

400 return s, r 

401 

402 

403def _strcomplex(s, *args): 

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

405 ''' 

406 c = typename(_strcomplex)[4:] 

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

408 t = unstr(pow, *args) 

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

410 

411 

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

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

414 ''' 

415 p = typename(_stresidual)[3:] 

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

417 for n, v in itemsorted(mod_ratio): 

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

419 t = _COMMASPACE_(t, p) 

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

421 

422 

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

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

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

426 ''' 

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

428 

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

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

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

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

433 s = a + b 

434 if _isfinite(s): 

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

436 r = (b - s) + a 

437 else: 

438 r = (a - s) + b 

439 elif _isfine(s): 

440 r = _NONFINITEr 

441 else: # non-finite and not OK 

442 t = unstr(_2sum, a, b) 

443 raise _nfError(s, t) 

444 return s, r 

445 

446 

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

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

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

450 ''' 

451 if kwds: 

452 threshold = _xkwds_get1(kwds, RESIDUAL=threshold) 

453 try: 

454 return _2finite(threshold) # PYCHOK None 

455 except Exception as x: 

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

457 

458 

459def _2tuple2(other): 

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

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

462 ''' 

463 if _isFsum_2Tuple(other): 

464 s, r = other._fint2 

465 if r: 

466 s, r = other._nfprs2 

467 if r: # PYCHOK no cover 

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

469 else: 

470 r = 0 

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

472 if isint(s, both=True): 

473 s = int(s) 

474 return s, r 

475 

476 

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

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

479 

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

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

482 intermediate, I{running} summuation. 

483 

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

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

486 

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

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

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

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

491 exceptions by default. 

492 

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

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

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

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

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

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

499 

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

501 multiplication. 

502 

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

504 C{PYGEODESY_FSUM_NONFINITES} and C{PYGEODESY_FSUM_RESIDUAL}. 

505 ''' 

506 _f2product = _MODS.sys_version_info2 > (3, 12) or bool(_F2PRODUCT) 

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

508 _n = 0 

509# _ps = [] # partial sums 

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

511 _RESIDUAL = _threshold(_RESIDUAL_0_0) 

512 

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

514 '''New L{Fsum}. 

515 

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

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

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

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

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

521 L{Fsum}. 

522 

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

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

525 ''' 

526 if name_f2product_nonfinites_RESIDUAL: 

527 self._optionals(**name_f2product_nonfinites_RESIDUAL) 

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

529 if xs: 

530 self._facc_args(xs, up=False) 

531 

532 def __abs__(self): 

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

534 ''' 

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

536 return (-self) if s < 0 else self._copyd(self.__abs__) 

537 

538 def __add__(self, other): 

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

540 

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

542 

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

544 

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

546 ''' 

547 f = self._copyd(self.__add__) 

548 return f._fadd(other) 

549 

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

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

552 ''' 

553 s, r = self._nfprs2 

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

555 

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

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

558 ''' 

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

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

561 return self 

562 

563 

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

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

566 

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

568 

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

570 ''' 

571 return self.ceil 

572 

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

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

575 

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

577 

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

579 ''' 

580 s = self._cmp_0(other, typename(self.cmp)) 

581 return _signOf(s, 0) 

582 

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

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

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

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

587 

588 @arg other: Modulus (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

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

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

592 

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

594 B{C{RESIDUAL}}. 

595 

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

597 ''' 

598 f = self._copyd(self.__divmod__) 

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

600 

601 def __eq__(self, other): 

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

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

604 ''' 

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

606 

607 def __float__(self): 

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

609 

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

611 ''' 

612 return float(self._fprs) 

613 

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

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

616 

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

618 

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

620 ''' 

621 return self.floor 

622 

623 def __floordiv__(self, other): 

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

625 

626 @arg other: Divisor (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

627 

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

629 

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

631 ''' 

632 f = self._copyd(self.__floordiv__) 

633 return f._floordiv(other, _floordiv_op_) 

634 

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

636# '''Not implemented.''' 

637# return _NotImplemented(self, *other) 

638 

639 def __ge__(self, other): 

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

641 ''' 

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

643 

644 def __gt__(self, other): 

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

646 ''' 

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

648 

649 def __hash__(self): # PYCHOK no cover 

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

651 ''' 

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

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

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

655 

656 def __iadd__(self, other): 

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

658 

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

660 an iterable of several of the former. 

661 

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

663 

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

665 C{scalar} nor L{Fsum}. 

666 

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

668 ''' 

669 try: 

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

671 except TypeError: 

672 pass 

673 _xiterable(other) 

674 return self._facc(other) 

675 

676 def __ifloordiv__(self, other): 

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

678 

679 @arg other: Divisor (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

680 

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

682 

683 @raise ResidualError: Non-zero, significant residual 

684 in B{C{other}}. 

685 

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

687 

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

689 

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

691 

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

693 ''' 

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

695 

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

697 '''Not implemented.''' 

698 return _NotImplemented(self, other) 

699 

700 def __imod__(self, other): 

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

702 

703 @arg other: Modulus (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

704 

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

706 

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

708 ''' 

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

710 

711 def __imul__(self, other): 

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

713 

714 @arg other: Factor (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

715 

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

717 

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

719 

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

721 

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

723 ''' 

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

725 

726 def __int__(self): 

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

728 

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

730 and L{Fsum.floor}. 

731 ''' 

732 i, _ = self._fint2 

733 return i 

734 

735 def __invert__(self): # PYCHOK no cover 

736 '''Not implemented.''' 

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

738 return _NotImplemented(self) 

739 

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

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

742 

743 @arg other: Exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

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

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

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

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

749 

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

751 

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

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

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

755 

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

757 

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

759 is non-zero and significant and either 

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

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

762 C{None}. 

763 

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

765 invocation failed. 

766 

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

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

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

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

771 is given as C{0}. 

772 

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

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

775 ''' 

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

777 

778 def __isub__(self, other): 

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

780 

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

782 an iterable of several of the former. 

783 

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

785 

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

787 

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

789 ''' 

790 try: 

791 return self._fsub(other, _isub_op_) 

792 except TypeError: 

793 pass 

794 _xiterable(other) 

795 return self._facc_neg(other) 

796 

797 def __iter__(self): 

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

799 ''' 

800 return iter(self.partials) 

801 

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

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

804 

805 @arg other: Divisor (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

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

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

809 

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

811 

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

813 

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

815 B{C{RESIDUAL}}. 

816 

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

818 

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

820 

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

822 

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

824 ''' 

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

826 

827 def __le__(self, other): 

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

829 ''' 

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

831 

832 def __len__(self): 

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

834 ''' 

835 return self._n 

836 

837 def __lt__(self, other): 

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

839 ''' 

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

841 

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

843 '''Not implemented.''' 

844 return _NotImplemented(self, other) 

845 

846 def __mod__(self, other): 

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

848 

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

850 ''' 

851 f = self._copyd(self.__mod__) 

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

853 

854 def __mul__(self, other): 

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

856 

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

858 ''' 

859 f = self._copyd(self.__mul__) 

860 return f._fmul(other, _mul_op_) 

861 

862 def __ne__(self, other): 

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

864 ''' 

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

866 

867 def __neg__(self): 

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

869 ''' 

870 f = self._copyd(self.__neg__) 

871 return f._fset(self._neg) 

872 

873 def __pos__(self): 

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

875 ''' 

876 return self if _pos_self else self._copyd(self.__pos__) 

877 

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

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

880 

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

882 ''' 

883 f = self._copyd(self.__pow__) 

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

885 

886 def __radd__(self, other): 

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

888 

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

890 ''' 

891 f = self._rcopyd(other, self.__radd__) 

892 return f._fadd(self) 

893 

894 def __rdivmod__(self, other): 

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

896 C{(quotient, remainder)}. 

897 

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

899 ''' 

900 f = self._rcopyd(other, self.__rdivmod__) 

901 return f._fdivmod2(self, _divmod_op_) 

902 

903# turned off, called by _deepcopy and _copy 

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

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

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

907# ''' 

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

909# return (type(self), self.partials, dict_) 

910 

911# def __repr__(self): 

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

913# ''' 

914# return self.toRepr(lenc=True) 

915 

916 def __rfloordiv__(self, other): 

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

918 

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

920 ''' 

921 f = self._rcopyd(other, self.__rfloordiv__) 

922 return f._floordiv(self, _floordiv_op_) 

923 

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

925 '''Not implemented.''' 

926 return _NotImplemented(self, other) 

927 

928 def __rmod__(self, other): 

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

930 

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

932 ''' 

933 f = self._rcopyd(other, self.__rmod__) 

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

935 

936 def __rmul__(self, other): 

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

938 

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

940 ''' 

941 f = self._rcopyd(other, self.__rmul__) 

942 return f._fmul(self, _mul_op_) 

943 

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

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

946 

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

948 ''' 

949 f = self._copyd(self.__round__) 

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

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

952 

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

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

955 

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

957 ''' 

958 f = self._rcopyd(other, self.__rpow__) 

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

960 

961 def __rsub__(self, other): 

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

963 

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

965 ''' 

966 f = self._rcopyd(other, self.__rsub__) 

967 return f._fsub(self, _sub_op_) 

968 

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

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

971 

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

973 ''' 

974 f = self._rcopyd(other, self.__rtruediv__) 

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

976 

977# def __sizeof__(self): 

978# '''Return the size of this instance (C{int} bytes}). 

979# ''' 

980# return _sizeof(self._ps) + _sizeof(self._n) 

981 

982 def __str__(self): 

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

984 ''' 

985 return self.toStr(lenc=True) 

986 

987 def __sub__(self, other): 

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

989 

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

991 

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

993 

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

995 ''' 

996 f = self._copyd(self.__sub__) 

997 return f._fsub(other, _sub_op_) 

998 

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

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

1001 

1002 @arg other: Divisor (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

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

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

1006 

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

1008 

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

1010 B{C{RESIDUAL}}. 

1011 

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

1013 ''' 

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

1015 

1016 __trunc__ = __int__ 

1017 

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

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

1020 __div__ = __truediv__ 

1021 __idiv__ = __itruediv__ 

1022 __long__ = __int__ 

1023 __nonzero__ = __bool__ 

1024 __rdiv__ = __rtruediv__ 

1025 

1026 def as_integer_ratio(self): 

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

1028 

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

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

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

1032 instance is. 

1033 

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

1035 Python 2.7+. 

1036 ''' 

1037 n, r = self._fint2 

1038 if r: 

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

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

1041 else: # PYCHOK no cover 

1042 d = 1 

1043 return n, d 

1044 

1045 @property_RO 

1046 def as_iscalar(self): 

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

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

1049 ''' 

1050 s, r = self._nfprs2 

1051 return self if r else s 

1052 

1053 @property_RO 

1054 def ceil(self): 

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

1056 C{float} in Python 2-). 

1057 

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

1059 

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

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

1062 ''' 

1063 s, r = self._fprs2 

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

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

1066 c += 1 

1067 return c # _ceil(self._n_d) 

1068 

1069 cmp = __cmp__ 

1070 

1071 def _cmp_0(self, other, op): 

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

1073 ''' 

1074 if _isFsum_2Tuple(other): 

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

1076 elif self._scalar(other, op): 

1077 s = self._ps_1sum(other) 

1078 else: 

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

1080 return s 

1081 

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

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

1084 

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

1086 

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

1088 ''' 

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

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

1091 if f._ps is self._ps: 

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

1093 if not deep: 

1094 f._n = 1 

1095 # assert f._f2product == self._f2product 

1096 # assert f._Fsum is f 

1097 # assert f._isfine is self._isfine 

1098 # assert f._RESIDUAL is self._RESIDUAL 

1099 return f 

1100 

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

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

1103 ''' 

1104 n = name or typename(which) 

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

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

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

1108 # assert f._n == self._n 

1109 # assert f._f2product == self._f2product 

1110 # assert f._Fsum is f 

1111 # assert f._isfine is self._isfine 

1112 # assert f._RESIDUAL is self._RESIDUAL 

1113 return f 

1114 

1115 divmod = __divmod__ 

1116 

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

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

1119 ''' 

1120 # self.as_iscalar causes RecursionError for ._fprs2 errors 

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

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

1123 

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

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

1126 ''' 

1127 E, t = _xError2(X) 

1128 if mod: 

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

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

1131 

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

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

1134 ''' 

1135 E, t = _xError2(X) 

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

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

1138 

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

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

1141 ''' 

1142 if xs: 

1143 kwds = self._isfine 

1144 if _X_x_origin: 

1145 kwds = _xkwds(_X_x_origin, **kwds) 

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

1147 ps = self._ps 

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

1149# if len(ps) > 16: 

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

1151 return self 

1152 

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

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

1155 arguments in the caller of this method. 

1156 ''' 

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

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

1159 

1160 def _facc_dot(self, n, xs, ys, **kwds): # in .fmath 

1161 '''(INTERNAL) Accumulate C{fdot(B{xs}, *B{ys})}. 

1162 ''' 

1163 if n > 0: 

1164 _f = Fsum(**kwds) 

1165 self._facc(_f(x).fmul(y) for x, y in zip(xs, ys)) # PYCHOK attr? 

1166 return self 

1167 

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

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

1170 ''' 

1171 def _N(X): 

1172 return X._ps_neg 

1173 

1174 def _n(x): 

1175 return -float(x) 

1176 

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

1178 

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

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

1181 ''' 

1182 def _Pow4(p): 

1183 r = 0 

1184 if _isFsum_2Tuple(p): 

1185 s, r = p._fprs2 

1186 if r: 

1187 m = Fsum._pow 

1188 else: # scalar 

1189 return _Pow4(s) 

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

1191 p = s = int(p) 

1192 m = Fsum._pow_int 

1193 else: 

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

1195 m = Fsum._pow_scalar 

1196 return m, p, s, r 

1197 

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

1199 if p: # and xs: 

1200 op = typename(which) 

1201 _FsT = _Fsum_2Tuple_types 

1202 _pow = self._pow_2_3 

1203 

1204 def _P(X): 

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

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

1207 

1208 def _p(x): 

1209 x = float(x) 

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

1211 if f and r: 

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

1213 return f 

1214 

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

1216 else: 

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

1218 return f 

1219 

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

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

1222 ''' 

1223 if xs: 

1224 ps = self._ps 

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

1226 return self 

1227 

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

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

1230 ''' 

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

1232 

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

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

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

1236# ''' 

1237# ps = self._ps 

1238# while len(ps) > 1: 

1239# p = ps.pop() 

1240# if p: 

1241# n = self._n 

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

1243# self._n = n 

1244# break 

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

1246 

1247 def _facc_xsum(self, xs, up=True, **origin_which): 

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

1249 or L{Fsum2Tuple}, like function C{_xsum}. 

1250 ''' 

1251 fs = _xs(xs, **_x_isfine(self.nonfinitesOK, _Cdot=type(self), 

1252 **origin_which)) # PYCHOK yield 

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

1254 

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

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

1257 

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

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

1260 

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

1262 

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

1264 

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

1266 

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

1268 ''' 

1269 if _isFsum_2Tuple(xs): 

1270 self._facc_scalar(xs._ps) 

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

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

1273 self._facc_scalar_(x) 

1274 elif xs: # _xiterable(xs) 

1275 self._facc(xs) 

1276 return self 

1277 

1278 def fadd_(self, *xs): 

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

1280 

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

1282 or L{Fsum2Tuple}), all positional. 

1283 

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

1285 ''' 

1286 return self._facc_args(xs) 

1287 

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

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

1290 ''' 

1291 if _isFsum_2Tuple(other): 

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

1293 elif self._scalar(other, op): 

1294 self._facc_scalar_(other, **up) 

1295 return self 

1296 

1297 fcopy = copy # for backward compatibility 

1298 fdiv = __itruediv__ 

1299 fdivmod = __divmod__ 

1300 

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

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

1303 ''' 

1304 # result mostly follows CPython function U{float_divmod 

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

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

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

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

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

1310 

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

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

1313 self += other 

1314 q -= 1 

1315# t = self.signOf() 

1316# if t and t != s: 

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

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

1319 

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

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

1322 C{sum(c * B{x}**i for i, c in _e(cs))} where C{_e = 

1323 enumerate if B{incx} else _enumereverse}. 

1324 ''' 

1325 # assert _xiterablen(cs) 

1326 try: 

1327 n = len(cs) 

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

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

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

1331 H._mul_scalar 

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

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

1334 H._fadd(c, up=False) 

1335 else: # x == 0 

1336 H = cs[0] if n else 0 

1337 self._fadd(H) 

1338 except Exception as X: 

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

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

1341 return self 

1342 

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

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

1345 ''' 

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

1347 return other 

1348 E = _NonfiniteError(other) 

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

1350 

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

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

1353 

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

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

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

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

1358 

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

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

1361 

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

1363 B{C{RESIDUAL}}. 

1364 

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

1366 ''' 

1367 i, r = self._fint2 

1368 if r: 

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

1370 if R: 

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

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

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

1374 

1375 def fint2(self, **name): 

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

1377 I{integer} residual. 

1378 

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

1380 

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

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

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

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

1385 ''' 

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

1387 

1388 @Property 

1389 def _fint2(self): # see ._fset 

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

1391 ''' 

1392 s, r = self._nfprs2 

1393 if _isfinite(s): 

1394 i = int(s) 

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

1396 float(s - i)) or INT0 

1397 else: # INF, NAN, NINF 

1398 i = float(s) 

1399# r = _NONFINITEr 

1400 return i, r # Fsum2Tuple? 

1401 

1402 @_fint2.setter_ # PYCHOK setter_UNDERscore! 

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

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

1405 ''' 

1406 if _isfinite(s): 

1407 i = int(s) 

1408 r = (s - i) or INT0 

1409 else: # INF, NAN, NINF 

1410 i = float(s) 

1411 r = _NONFINITEr 

1412 return i, r # like _fint2.getter 

1413 

1414 @deprecated_property_RO 

1415 def float_int(self): # PYCHOK no cover 

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

1417 return self.int_float() # raiser=False 

1418 

1419 @property_RO 

1420 def floor(self): 

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

1422 C{float} in Python 2-). 

1423 

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

1425 

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

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

1428 ''' 

1429 s, r = self._fprs2 

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

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

1432 f -= 1 

1433 return f # _floor(self._n_d) 

1434 

1435# ffloordiv = __ifloordiv__ # for naming consistency? 

1436# floordiv = __floordiv__ # for naming consistency? 

1437 

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

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

1440 ''' 

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

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

1443 

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

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

1446 

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

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

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

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

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

1452 ''' 

1453 op = typename(self.fma) 

1454 _fs = self._ps_other 

1455 try: 

1456 s, r = self._fprs2 

1457 if r: 

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

1459 f += other2 

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

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

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

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

1464 else: 

1465 f = _fma(s, other1, other2) 

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

1467 except TypeError as X: 

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

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

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

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

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

1473 return self._fset(f) 

1474 

1475 fmul = __imul__ 

1476 

1477 def _fmul(self, other, op): 

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

1479 ''' 

1480 if _isFsum_2Tuple(other): 

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

1482 f = self._mul_Fsum(other, op) 

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

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

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

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

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

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

1489 else: 

1490 s = self._scalar(other, op) 

1491 f = self._mul_scalar(s, op) 

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

1493 

1494 @deprecated_method 

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

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

1497 return self._fset(self._f2mul(self.f2mul, others, **raiser)) 

1498 

1499 def f2mul_(self, *others, **f2product_nonfinites): # in .fmath.f2mul 

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

1501 accurate multiplication like with L{f2product<Fsum.f2product>}C{(B{True})}. 

1502 

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

1504 positional. 

1505 @kwarg f2product_nonfinites: Use C{B{f2product=False}} to override the default 

1506 C{True} and C{B{nonfinites}=True} or C{False}, to override 

1507 settings L{nonfinites<Fsum.nonfinites>} and L{nonfiniterrors}. 

1508 

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

1510 

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

1512 ''' 

1513 return self._f2mul(self.f2mul_, others, **f2product_nonfinites) 

1514 

1515 def _f2mul(self, where, others, f2product=True, **nonfinites_raiser): 

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

1517 ''' 

1518 n = typename(where) 

1519 f = _Psum(self._ps, f2product=f2product, name=n) 

1520 if others and f: 

1521 if f.f2product(): 

1522 def _pfs(f, ps): 

1523 return _2products(f, _2split3s(ps)) 

1524 else: 

1525 def _pfs(f, ps): # PYCHOK redef 

1526 return (f * p for p in ps) 

1527 

1528 op, ps = n, f._ps 

1529 try: # as if self.f2product(True) 

1530 for other in others: # to pinpoint errors 

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

1532 ps[:] = f._ps_acc([], _pfs(p, ps), update=False) 

1533 f._update() 

1534 except TypeError as X: 

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

1536 except (OverflowError, ValueError) as X: 

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

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

1539 f._fset(r) 

1540 return f 

1541 

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

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

1544 

1545 @arg over: Divisor (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

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

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

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

1549 

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

1551 

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

1553 B{C{RESIDUAL}}. 

1554 

1555 @see: Methods L{Fsum.fdiv}, L{Fsum.__itruediv__} and L{Fsum.fsum}. 

1556 ''' 

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

1558 

1559 fpow = __ipow__ 

1560 

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

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

1563 ''' 

1564 if mod: 

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

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

1567 elif self.is_integer(): 

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

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

1570 x, r = _2tuple2(other) # C{int}, C{float} or other 

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

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

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

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

1575 else: # pow(self, other) 

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

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

1578 

1579 def f2product(self, *two): 

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

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

1582 

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

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

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

1586 

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

1588 

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

1590 

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

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

1593 ''' 

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

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

1596 if two[0] is not None: 

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

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

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

1600 return t 

1601 

1602 @Property 

1603 def _fprs(self): 

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

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

1606 

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

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

1609 ''' 

1610 s, _ = self._fprs2 

1611 return s # ._fprs2.fsum 

1612 

1613 @_fprs.setter_ # PYCHOK setter_UNDERscore! 

1614 def _fprs(self, s): 

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

1616 ''' 

1617 return s 

1618 

1619 @Property 

1620 def _fprs2(self): 

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

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

1623 ''' 

1624 ps = self._ps 

1625 n = len(ps) 

1626 try: 

1627 if n > 2: 

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

1629 if not _isfinite(s): 

1630 ps[:] = s, # collapse ps 

1631 return Fsum2Tuple(s, _NONFINITEr) 

1632 n = len(ps) 

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

1634 if n > 2: 

1635 r = self._ps_1sum(s) 

1636 return Fsum2Tuple(*_s_r2(s, r)) 

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

1638 s, r = _s_r2(*_2sum(*ps, **self._isfine)) 

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

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

1641 s = ps[0] 

1642 r = INT0 if _isfinite(s) else _NONFINITEr 

1643 else: # len(ps) == 0 

1644 s = _0_0 

1645 r = INT0 if _isfinite(s) else _NONFINITEr 

1646 ps[:] = s, 

1647 except (OverflowError, ValueError) as X: 

1648 op = _fset_op_ # INF, NAN, NINF 

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

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

1651 r = _NONFINITEr 

1652 # assert self._ps is ps 

1653 return Fsum2Tuple(s, r) 

1654 

1655 @_fprs2.setter_ # PYCHOK setter_UNDERscore! 

1656 def _fprs2(self, s_r): 

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

1658 ''' 

1659 return Fsum2Tuple(s_r) 

1660 

1661 def fset_(self, *xs): 

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

1663 

1664 @arg xs: Optional, new values (each C{scalar} or an L{Fsum} 

1665 or L{Fsum2Tuple} instance), all positional. 

1666 

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

1668 

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

1670 ''' 

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

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

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

1674 

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

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

1677 ''' 

1678 if other is self: 

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

1680 elif _isFsum_2Tuple(other): 

1681 if op: # and not self.nonfinitesOK: 

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

1683 self._ps[:] = other._ps 

1684 self._n = n or other._n 

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

1686 Fsum._fint2._update_from(self, other) 

1687 Fsum._fprs ._update_from(self, other) 

1688 Fsum._fprs2._update_from(self, other) 

1689 elif isscalar(other): 

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

1691 self._ps[:] = s, 

1692 self._n = n or 1 

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

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

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

1696 self._fint2 = s 

1697 self._fprs = s 

1698 self._fprs2 = s, INT0 

1699 # assert self._fprs is s 

1700 else: 

1701 op = _xkwds_get1(op, op=_fset_op_) 

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

1703 return self 

1704 

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

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

1707 

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

1709 ''' 

1710 return self._facc_neg(xs) 

1711 

1712 def fsub_(self, *xs): 

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

1714 

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

1716 ''' 

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

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

1719 

1720 def _fsub(self, other, op): 

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

1722 ''' 

1723 if _isFsum_2Tuple(other): 

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

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

1726 elif other._ps: 

1727 self._facc_scalar(other._ps_neg) 

1728 elif self._scalar(other, op): 

1729 self._facc_scalar_(-other) 

1730 return self 

1731 

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

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

1734 precision running sum. 

1735 

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

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

1738 

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

1740 

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

1742 

1743 @note: Accumulation can continue after summation. 

1744 ''' 

1745 return self._facc(xs)._fprs 

1746 

1747 def fsum_(self, *xs): 

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

1749 precision running sum. 

1750 

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

1752 L{Fsum2Tuple}), all positional. 

1753 

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

1755 

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

1757 ''' 

1758 return self._facc_args(xs)._fprs 

1759 

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

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

1762 

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

1764 

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

1766 ''' 

1767 return self._facc_args(xs)._copyd(self.Fsum_, **name) 

1768 

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

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

1771 

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

1773 

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

1775 ''' 

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

1777 

1778 @property_RO 

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

1780 return self # NOT @Property_RO, see .copy and ._copyd 

1781 

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

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

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

1785 overridden with C{name_f2product_nonfinites_RESIDUAL} and 

1786 with any C{xs} accumulated. 

1787 ''' 

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

1789 nonfinites=self.nonfinites(), 

1790 RESIDUAL =self.RESIDUAL()) 

1791 if name_f2product_nonfinites_RESIDUAL: # overwrites 

1792 kwds.update(name_f2product_nonfinites_RESIDUAL) 

1793 f = Fsum(**kwds) 

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

1795 return (f._facc(xs, up=False) if len(xs) > 1 else 

1796 f._fset(xs[0], op=_fset_op_)) if xs else f 

1797 

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

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

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

1801 

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

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

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

1805 

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

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

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

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

1810 to be I{exact}. 

1811 

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

1813 ''' 

1814 t = self._facc(xs)._fprs2 

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

1816 

1817 def fsum2_(self, *xs): 

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

1819 precision running sum and the I{differential}. 

1820 

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

1822 L{Fsum2Tuple}), all positional. 

1823 

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

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

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

1827 

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

1829 ''' 

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

1831 

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

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

1834 ''' 

1835 p, q = self._fprs2 

1836 if xs: 

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

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

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

1840 r, _ = _s_r2(d, r) 

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

1842 else: 

1843 return p, _0_0 

1844 

1845 def fsumf_(self, *xs): 

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

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

1848 ''' 

1849 return self._facc_xsum(xs, which=self.fsumf_)._fprs # origin=1? 

1850 

1851 def Fsumf_(self, *xs): 

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

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

1854 ''' 

1855 return self._facc_xsum(xs, which=self.Fsumf_)._copyd(self.Fsumf_) # origin=1? 

1856 

1857 def fsum2f_(self, *xs): 

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

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

1860 ''' 

1861 return self._fsum2(xs, self._facc_xsum, which=self.fsum2f_) # origin=1? 

1862 

1863# ftruediv = __itruediv__ # for naming consistency? 

1864 

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

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

1867 ''' 

1868 n = _1_0 

1869 if _isFsum_2Tuple(other): 

1870 if other is self or self == other: 

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

1872 d, r = other._fprs2 

1873 if r: 

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

1875 if R: 

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

1877 d, n = other.as_integer_ratio() 

1878 else: 

1879 d = self._scalar(other, op) 

1880 try: 

1881 s = n / d 

1882 except Exception as X: 

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

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

1885 return self._fset(f) 

1886 

1887 @property_RO 

1888 def imag(self): 

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

1890 

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

1892 ''' 

1893 return _0_0 

1894 

1895 def int_float(self, **raiser_RESIDUAL): 

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

1897 

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

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

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

1901 

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

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

1904 is zero or not significant. 

1905 

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

1907 B{C{RESIDUAL}}. 

1908 

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

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

1911 ''' 

1912 s, r = self._fint2 

1913 if r: 

1914 s, r = self._fprs2 

1915 if r: # PYCHOK no cover 

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

1917 if R: 

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

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

1920 s = float(s) 

1921 return s 

1922 

1923 def is_exact(self): 

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

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

1926 ''' 

1927 return self.residual is INT0 

1928 

1929 def is_finite(self): # in .constants 

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

1931 

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

1933 ''' 

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

1935 

1936 def is_integer(self): 

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

1938 

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

1940 ''' 

1941 s, r = self._fint2 

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

1943 

1944 def is_math_fma(self): 

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

1946 

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

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

1949 C{PyGeodesy} implementation. 

1950 ''' 

1951 return (_2split3s is _passarg) or (False if _integer_ratio2 is None else None) 

1952 

1953 def is_math_fsum(self): 

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

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

1956 

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

1958 otherwise. 

1959 ''' 

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

1961 

1962 def is_scalar(self, **raiser_RESIDUAL): 

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

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

1965 

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

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

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

1969 

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

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

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

1973 

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

1975 B{C{RESIDUAL}}. 

1976 

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

1978 L{Fsum.as_iscalar}. 

1979 ''' 

1980 s, r = self._fprs2 

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

1982 

1983 def _mul_Fsum(self, other, op): 

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

1985 ''' 

1986 # assert _isFsum_2Tuple(other) 

1987 if self._ps and other._ps: 

1988 try: 

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

1990 except Exception as X: 

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

1992 else: 

1993 f = _0_0 

1994 return f 

1995 

1996 def _mul_reduce(self, *others): 

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

1998 ''' 

1999 r = _1_0 

2000 for f in others: 

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

2002 return r 

2003 

2004 def _mul_scalar(self, factor, op): 

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

2006 ''' 

2007 # assert isscalar(factor) 

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

2009 f = self if factor == _1_0 else ( 

2010 self._neg if factor == _N_1_0 else 

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

2012 else: 

2013 f = _0_0 

2014 return f 

2015 

2016# @property_RO 

2017# def _n_d(self): 

2018# n, d = self.as_integer_ratio() 

2019# return n / d 

2020 

2021 @property_RO 

2022 def _neg(self): 

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

2024 ''' 

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

2026 

2027 @property_RO 

2028 def _nfprs2(self): 

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

2030 ''' 

2031 try: # to handle nonfiniterrors, etc. 

2032 t = self._fprs2 

2033 except (OverflowError, ValueError): 

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

2035 return t 

2036 

2037 def nonfinites(self, *OK): 

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

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

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

2041 

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

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

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

2045 

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

2047 

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

2049 

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

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

2052 L{nonfiniterrors} default. 

2053 ''' 

2054 _ks = Fsum._nonfinites_isfine_kwds 

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

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

2057 if OK[0] is not None: 

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

2059 self._update() 

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

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

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

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

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

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

2066 

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

2068 False: dict(_isfine=_isfinite)} 

2069 

2070 @property_RO 

2071 def nonfinitesOK(self): 

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

2073 ''' 

2074# nf = self.nonfinites() 

2075# if nf is None: 

2076# nf = not nonfiniterrors() 

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

2078 

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

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

2081 ''' 

2082 if nonfinites is None: 

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

2084 if not nonfinites: 

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

2086 return f 

2087 

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

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

2090 ''' 

2091 if f2product is not None: 

2092 self.f2product(f2product) 

2093 if nonfinites is not None: 

2094 self.nonfinites(nonfinites) 

2095 if name_RESIDUAL: # MUST be last 

2096 n, kwds = _name2__(**name_RESIDUAL) 

2097 if kwds: 

2098 R = Fsum._RESIDUAL 

2099 t = _threshold(R, **kwds) 

2100 if t != R: 

2101 self._RESIDUAL = t 

2102 if n: 

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

2104 

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

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

2107 ''' 

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

2109 

2110 @property_RO 

2111 def partials(self): 

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

2113 ''' 

2114 return tuple(self._ps) 

2115 

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

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

2118 

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

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

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

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

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

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

2125 

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

2127 result (L{Fsum}). 

2128 

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

2130 B{C{RESIDUAL}}. 

2131 

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

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

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

2135 

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

2137 and L{Fsum.root}. 

2138 ''' 

2139 f = self._copyd(self.pow) 

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

2141 

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

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

2144 ''' 

2145 if _isFsum_2Tuple(other): 

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

2147 elif self._scalar(other, op): 

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

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

2150 else: 

2151 f = self._pow_0_1(0, other) 

2152 return f 

2153 

2154 def _pow_0_1(self, x, other): 

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

2156 ''' 

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

2158 

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

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

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

2162 ''' 

2163 

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

2165 m = mod[0] 

2166 # assert _isFsum_2Tuple(b) 

2167 

2168 def _s(s, r): 

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

2170 if R: 

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

2172 return s 

2173 

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

2175 x = _s(*_2tuple2(x)) 

2176 

2177 try: 

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

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

2180 if iscomplex(s): 

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

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

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

2184 return s 

2185 except Exception as X: 

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

2187 

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

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

2190 ''' 

2191 # assert _isFsum_2Tuple(other) 

2192 x, r = other._fprs2 

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

2194 if f and r: 

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

2196 return f 

2197 

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

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

2200 ''' 

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

2202 ps = self._ps 

2203 if len(ps) > 1: 

2204 _mul_Fsum = Fsum._mul_Fsum 

2205 if x > 4: 

2206 p = self 

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

2208 m = x >> 1 # // 2 

2209 while m: 

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

2211 if (m & 1): 

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

2213 m >>= 1 # //= 2 

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

2215 f = _mul_Fsum(self, self, op) 

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

2217 p = self if x < 4 else f 

2218 f = _mul_Fsum(f, p, op) 

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

2220 f = self._pow_0_1(x, other) 

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

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

2223 else: # PYCHOK no cover 

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

2225 f = 0 if x else 1 

2226 return f 

2227 

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

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

2230 ''' 

2231 s, r = self._fprs2 

2232 if r: 

2233 # assert s != 0 

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

2235 x = int(x) 

2236 y = abs(x) 

2237 if y > 1: 

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

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

2240 return f # Fsum or scalar 

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

2242 if _isFsum(f): 

2243 s, r = f._fprs2 

2244 if r: 

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

2246 else: # scalar 

2247 s = f 

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

2249 # float_pow error iff s is zero 

2250 x = -1 

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

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

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

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

2255 else: # self**fractional 

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

2257 if R: 

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

2259 n, d = self.as_integer_ratio() 

2260 if abs(n) > abs(d): 

2261 n, d, x = d, n, (-x) 

2262 s = n / d 

2263 # assert isscalar(s) and isscalar(x) 

2264 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL) 

2265 

2266 def _ps_acc(self, ps, xs, up=True, **unused): 

2267 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}. 

2268 ''' 

2269 n = 0 

2270 _2s = _2sum 

2271 _fi = self._isfine 

2272 for x in (tuple(xs) if xs is ps else xs): 

2273 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine) 

2274 if x: 

2275 i = 0 

2276 for p in ps: 

2277 x, p = _2s(x, p, **_fi) 

2278 if p: 

2279 ps[i] = p 

2280 i += 1 

2281 ps[i:] = (x,) if x else () 

2282 n += 1 

2283 if n: 

2284 self._n += n 

2285 # Fsum._ps_max = max(Fsum._ps_max, len(ps)) 

2286 if up: 

2287 self._update() 

2288# x = sum(ps) 

2289# if not _isOK_or_finite(x, **fi): 

2290# ps[:] = x, # collapse ps 

2291 return ps 

2292 

2293 def _ps_mul(self, op, *factors): 

2294 '''(INTERNAL) Multiply this instance' C{partials} with 

2295 each scalar C{factor} and accumulate into an C{Fsum}. 

2296 ''' 

2297 def _psfs(ps, fs, _isfine=_isfinite): 

2298 if len(ps) < len(fs): 

2299 ps, fs = fs, ps 

2300 if self._f2product: 

2301 fs, p = _2split3s(fs), fs 

2302 if len(ps) > 1 and fs is not p: 

2303 fs = tuple(fs) # several ps 

2304 _pfs = _2products 

2305 else: 

2306 def _pfs(p, fs): 

2307 return (p * f for f in fs) 

2308 

2309 for p in ps: 

2310 for x in _pfs(p, fs): 

2311 yield x if _isfine(x) else _nfError(x) 

2312 

2313 xs = _psfs(self._ps, factors, **self._isfine) 

2314 f = _Psum(self._ps_acc([], xs, up=False), name=op) 

2315 return f 

2316 

2317 @property_RO 

2318 def _ps_neg(self): 

2319 '''(INTERNAL) Yield the partials, I{negated}. 

2320 ''' 

2321 for p in self._ps: 

2322 yield -p 

2323 

2324 def _ps_other(self, op, other): 

2325 '''(INTERNAL) Yield C{other} as C{scalar}s. 

2326 ''' 

2327 if _isFsum_2Tuple(other): 

2328 for p in other._ps: 

2329 yield p 

2330 else: 

2331 yield self._scalar(other, op) 

2332 

2333 def _ps_1sum(self, *less): 

2334 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars. 

2335 ''' 

2336 def _1psls(ps, ls): 

2337 yield _1_0 

2338 for p in ps: 

2339 yield p 

2340 for p in ls: 

2341 yield -p 

2342 yield _N_1_0 

2343 

2344 return _fsum(_1psls(self._ps, less)) 

2345 

2346 def _raiser(self, r, s, raiser=True, **RESIDUAL): 

2347 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold 

2348 I{and} is residual C{r} I{non-zero} or I{significant} (for a 

2349 negative respectively positive C{RESIDUAL} threshold)? 

2350 ''' 

2351 if r and raiser: 

2352 t = self._RESIDUAL 

2353 if RESIDUAL: 

2354 t = _threshold(t, **RESIDUAL) 

2355 if t < 0 or (s + r) != s: 

2356 q = (r / s) if s else s # == 0. 

2357 if fabs(q) > fabs(t): 

2358 return dict(ratio=q, R=t) 

2359 return {} 

2360 

2361 def _rcopyd(self, other, which): 

2362 '''(INTERNAL) Copy for I{reverse-dyadic} operators. 

2363 ''' 

2364 return other._copyd(which) if _isFsum(other) else \ 

2365 self._copyd(which)._fset(other) 

2366 

2367 rdiv = __rtruediv__ 

2368 

2369 @property_RO 

2370 def real(self): 

2371 '''Get the C{real} part of this instance (C{float}). 

2372 

2373 @see: Methods L{Fsum.__float__} and L{Fsum.fsum} 

2374 and properties L{Fsum.ceil}, L{Fsum.floor}, 

2375 L{Fsum.imag} and L{Fsum.residual}. 

2376 ''' 

2377 return float(self) 

2378 

2379 @property_RO 

2380 def residual(self): 

2381 '''Get this instance' residual or residue (C{float} or C{int}): 

2382 the C{sum(partials)} less the precision running sum C{fsum}. 

2383 

2384 @note: The C{residual is INT0} iff the precision running 

2385 C{fsum} is considered to be I{exact}. 

2386 

2387 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}. 

2388 ''' 

2389 return self._fprs2.residual 

2390 

2391 def RESIDUAL(self, *threshold): 

2392 '''Get and set this instance' I{ratio} for raising L{ResidualError}s, 

2393 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}. 

2394 

2395 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising 

2396 L{ResidualError}s in division and exponention, if 

2397 C{None}, restore the default set with env variable 

2398 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

2399 current setting. 

2400 

2401 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}. 

2402 

2403 @raise ResidualError: Invalid B{C{threshold}}. 

2404 

2405 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio} 

2406 C{residual / fsum} exceeds the given B{C{threshold}} and (2) 

2407 the C{residual} is non-zero and (3) is I{significant} vs the 

2408 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional 

2409 keyword argument C{raiser=False} is missing. Specify a 

2410 negative B{C{threshold}} for only non-zero C{residual} 

2411 testing without the I{significant} case. 

2412 ''' 

2413 r = self._RESIDUAL 

2414 if threshold: 

2415 t = threshold[0] 

2416 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ... 

2417 (_0_0 if t else _1_0) if isbool(t) else 

2418 _threshold(t)) # ... backward compatibility 

2419 return r 

2420 

2421 def _ResidualError(self, op, other, residual, **mod_R): 

2422 '''(INTERNAL) Non-zero B{C{residual}} etc. 

2423 ''' 

2424 def _p(mod=None, R=0, **unused): # ratio=0 

2425 return (_non_zero_ if R < 0 else _significant_) \ 

2426 if mod is None else _integer_ 

2427 

2428 t = _stresidual(_p(**mod_R), residual, **mod_R) 

2429 return self._Error(op, other, ResidualError, txt=t) 

2430 

2431 def root(self, root, **raiser_RESIDUAL): 

2432 '''Return C{B{self}**(1 / B{root})} as L{Fsum}. 

2433 

2434 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2435 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any 

2436 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar} 

2437 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

2438 

2439 @return: The C{self ** (1 / B{root})} result (L{Fsum}). 

2440 

2441 @raise ResidualError: Non-zero, significant residual or invalid 

2442 B{C{RESIDUAL}}. 

2443 

2444 @see: Method L{Fsum.pow}. 

2445 ''' 

2446 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL) 

2447 f = self._copyd(self.root) 

2448 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x) 

2449 

2450 def _scalar(self, other, op, **txt): 

2451 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}. 

2452 ''' 

2453 if isscalar(other): 

2454 return other 

2455 raise self._Error(op, other, _TypeError, **txt) # _invalid_ 

2456 

2457 def signOf(self, res=True): 

2458 '''Determine the sign of this instance. 

2459 

2460 @kwarg res: If C{True}, consider the residual, 

2461 otherwise ignore the latter (C{bool}). 

2462 

2463 @return: The sign (C{int}, -1, 0 or +1). 

2464 ''' 

2465 s, r = self._nfprs2 

2466 r = (-r) if res else 0 

2467 return _signOf(s, r) 

2468 

2469 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature 

2470 '''Return this C{Fsum} instance as representation. 

2471 

2472 @kwarg lenc_prec_sep_fmt: Optional keyword arguments 

2473 for method L{Fsum.toStr}. 

2474 

2475 @return: This instance (C{repr}). 

2476 ''' 

2477 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt)) 

2478 

2479 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature 

2480 '''Return this C{Fsum} instance as string. 

2481 

2482 @kwarg lenc: If C{True}, include the current C{[len]} of this 

2483 L{Fsum} enclosed in I{[brackets]} (C{bool}). 

2484 @kwarg prec_sep_fmt: Optional keyword arguments for method 

2485 L{Fsum2Tuple.toStr}. 

2486 

2487 @return: This instance (C{str}). 

2488 ''' 

2489 p = self.classname 

2490 if lenc: 

2491 p = Fmt.SQUARE(p, len(self)) 

2492 n = _enquote(self.name, white=_UNDER_) 

2493 t = self._nfprs2.toStr(**prec_sep_fmt) 

2494 return NN(p, _SPACE_, n, t) 

2495 

2496 def _truediv(self, other, op, **raiser_RESIDUAL): 

2497 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}. 

2498 ''' 

2499 f = self._copyd(self.__truediv__) 

2500 return f._ftruediv(other, op, **raiser_RESIDUAL) 

2501 

2502 def _update(self, updated=True): # see ._fset 

2503 '''(INTERNAL) Zap all cached C{Property_RO} values. 

2504 ''' 

2505 if updated: 

2506 _pop = self.__dict__.pop 

2507 for p in _ROs: 

2508 _ = _pop(p, None) 

2509# Fsum._fint2._update(self) 

2510# Fsum._fprs ._update(self) 

2511# Fsum._fprs2._update(self) 

2512 return self # for .fset_ 

2513 

2514_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update 

2515 

2516if _NONFINITES == _std_: # PYCHOK no cover 

2517 _ = nonfiniterrors(False) 

2518 

2519 

2520def _Float_Int(arg, **name_Error): 

2521 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit. 

2522 ''' 

2523 U = Int if isint(arg) else Float 

2524 return U(arg, **name_Error) 

2525 

2526 

2527class DivMod2Tuple(_NamedTuple): 

2528 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder 

2529 C{mod} results of a C{divmod} operation. 

2530 

2531 @note: Quotient C{div} an C{int} in Python 3+ but a C{float} 

2532 in Python 2-. Remainder C{mod} an L{Fsum} instance. 

2533 ''' 

2534 _Names_ = ('div', 'mod') 

2535 _Units_ = (_Float_Int, Fsum) 

2536 

2537 

2538class Fsum2Tuple(_NamedTuple): # in .fstats 

2539 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum} 

2540 and the C{residual}, the sum of the remaining partials. Each 

2541 item is C{float} or C{int}. 

2542 

2543 @note: If the C{residual is INT0}, the C{fsum} is considered 

2544 to be I{exact}, see method L{Fsum2Tuple.is_exact}. 

2545 ''' 

2546 _Names_ = ( typename(Fsum.fsum), Fsum.residual.name) 

2547 _Units_ = (_Float_Int, _Float_Int) 

2548 

2549 def __abs__(self): # in .fmath 

2550 return self._Fsum.__abs__() 

2551 

2552 def __bool__(self): # PYCHOK Python 3+ 

2553 return bool(self._Fsum) 

2554 

2555 def __eq__(self, other): 

2556 return self._other_op(other, self.__eq__) 

2557 

2558 def __float__(self): 

2559 return self._Fsum.__float__() 

2560 

2561 def __ge__(self, other): 

2562 return self._other_op(other, self.__ge__) 

2563 

2564 def __gt__(self, other): 

2565 return self._other_op(other, self.__gt__) 

2566 

2567 def __le__(self, other): 

2568 return self._other_op(other, self.__le__) 

2569 

2570 def __lt__(self, other): 

2571 return self._other_op(other, self.__lt__) 

2572 

2573 def __int__(self): 

2574 return self._Fsum.__int__() 

2575 

2576 def __ne__(self, other): 

2577 return self._other_op(other, self.__ne__) 

2578 

2579 def __neg__(self): 

2580 return self._Fsum.__neg__() 

2581 

2582 __nonzero__ = __bool__ # Python 2- 

2583 

2584 def __pos__(self): 

2585 return self._Fsum.__pos__() 

2586 

2587 def as_integer_ratio(self): 

2588 '''Return this instance as the ratio of 2 integers. 

2589 

2590 @see: Method L{Fsum.as_integer_ratio} for further details. 

2591 ''' 

2592 return self._Fsum.as_integer_ratio() 

2593 

2594 @property_RO 

2595 def _fint2(self): 

2596 return self._Fsum._fint2 

2597 

2598 @property_RO 

2599 def _fprs2(self): 

2600 return self._Fsum._fprs2 

2601 

2602 @Property_RO 

2603 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats 

2604 s, r = _s_r2(*self) 

2605 ps = (r, s) if r else (s,) 

2606 return _Psum(ps, name=self.name) 

2607 

2608 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL): 

2609 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}. 

2610 ''' 

2611 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL) 

2612 

2613 def is_exact(self): 

2614 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}). 

2615 ''' 

2616 return self._Fsum.is_exact() 

2617 

2618 def is_finite(self): # in .constants 

2619 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}). 

2620 

2621 @see: Function L{isfinite<pygeodesy.isfinite>}. 

2622 ''' 

2623 return self._Fsum.is_finite() 

2624 

2625 def is_integer(self): 

2626 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}). 

2627 ''' 

2628 return self._Fsum.is_integer() 

2629 

2630 def _mul_scalar(self, other, op): # for Fsum._fmul 

2631 return self._Fsum._mul_scalar(other, op) 

2632 

2633 @property_RO 

2634 def _n(self): 

2635 return self._Fsum._n 

2636 

2637 def _other_op(self, other, which): 

2638 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum) 

2639 return getattr(C, typename(which))(s, other) 

2640 

2641 @property_RO 

2642 def _ps(self): 

2643 return self._Fsum._ps 

2644 

2645 @property_RO 

2646 def _ps_neg(self): 

2647 return self._Fsum._ps_neg 

2648 

2649 def signOf(self, **res): 

2650 '''Like method L{Fsum.signOf}. 

2651 ''' 

2652 return self._Fsum.signOf(**res) 

2653 

2654 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature 

2655 '''Return this L{Fsum2Tuple} as string (C{str}). 

2656 

2657 @kwarg fmt: Optional C{float} format (C{letter}). 

2658 @kwarg prec_sep: Optional keyword arguments for function 

2659 L{fstr<streprs.fstr>}. 

2660 ''' 

2661 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep)) 

2662 

2663_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines 

2664 

2665 

2666class ResidualError(_ValueError): 

2667 '''Error raised for a division, power or root operation of 

2668 an L{Fsum} instance with a C{residual} I{ratio} exceeding 

2669 the L{RESIDUAL<Fsum.RESIDUAL>} threshold. 

2670 

2671 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}. 

2672 ''' 

2673 pass 

2674 

2675 

2676try: 

2677 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+ 

2678 

2679 # make sure _fsum works as expected (XXX check 

2680 # float.__getformat__('float')[:4] == 'IEEE'?) 

2681 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover 

2682 del _fsum # nope, remove _fsum ... 

2683 raise ImportError() # ... use _fsum below 

2684 

2685 _sum = _fsum # in .elliptic 

2686except ImportError: 

2687 _sum = sum # in .elliptic 

2688 

2689 def _fsum(xs): 

2690 '''(INTERNAL) Precision summation, Python 2.5-. 

2691 ''' 

2692 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True) 

2693 return float(F._facc(xs, up=False)) 

2694 

2695 

2696def fsum(xs, nonfinites=None, **floats): 

2697 '''Precision floating point summation from Python's C{math.fsum}. 

2698 

2699 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2700 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if 

2701 C{False} I{non-finites} raise an Overflow-/ValueError or if 

2702 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}). 

2703 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use 

2704 keyword argument C{B{nonfinites}=False} instead. 

2705 

2706 @return: Precision C{fsum} (C{float}). 

2707 

2708 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow. 

2709 

2710 @raise TypeError: Invalid B{C{xs}} item. 

2711 

2712 @raise ValueError: Invalid or C{NAN} B{C{xs}} item. 

2713 

2714 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites}, 

2715 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}. 

2716 ''' 

2717 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0 

2718 

2719 

2720def fsum_(*xs, **nonfinites): 

2721 '''Precision floating point summation of all positional items. 

2722 

2723 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2724 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2725 

2726 @see: Function L{fsum<fsums.fsum>} for further details. 

2727 ''' 

2728 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1? 

2729 

2730 

2731def fsumf_(*xs): 

2732 '''Precision floating point summation of all positional items with I{non-finites} C{OK}. 

2733 

2734 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), 

2735 all positional. 

2736 

2737 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2738 ''' 

2739 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1? 

2740 

2741 

2742def fsum1(xs, **nonfinites): 

2743 '''Precision floating point summation, 1-primed. 

2744 

2745 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2746 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2747 

2748 @see: Function L{fsum<fsums.fsum>} for further details. 

2749 ''' 

2750 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0 

2751 

2752 

2753def fsum1_(*xs, **nonfinites): 

2754 '''Precision floating point summation of all positional items, 1-primed. 

2755 

2756 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2757 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2758 

2759 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2760 ''' 

2761 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1? 

2762 

2763 

2764def fsum1f_(*xs): 

2765 '''Precision floating point summation of all positional items, 1-primed and 

2766 with I{non-finites} C{OK}. 

2767 

2768 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2769 ''' 

2770 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0 

2771 

2772 

2773def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers. 

2774 _x_kwds = dict(_x= (_passarg if nfOK else _2finite), 

2775 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds 

2776 _x_kwds.update(kwds) 

2777 return _x_kwds 

2778 

2779 

2780def _X_ps(X): # default C{_X} handler 

2781 return X._ps # lambda X: X._ps 

2782 

2783 

2784def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc 

2785 origin=0, which=None, **_Cdot): 

2786 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s. 

2787 ''' 

2788 i, x = 0, xs 

2789 try: 

2790 for i, x in enumerate(_xiterable(xs)): 

2791 if _isFsum_2Tuple(x): 

2792 for p in _X(x): 

2793 yield p if _isfine(p) else _nfError(p) 

2794 else: 

2795 f = _x(x) 

2796 yield f if _isfine(f) else _nfError(f) 

2797 

2798 except (OverflowError, TypeError, ValueError) as X: 

2799 t = _xsError(X, xs, i + origin, x) 

2800 if which: # prefix invokation 

2801 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot) 

2802 t = _COMMASPACE_(w, t) 

2803 raise _xError(X, t, txt=None) 

2804 

2805 

2806def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0 

2807 '''(INTERNAL) Precision summation of C{xs} with conditions. 

2808 ''' 

2809 if floats: # for backward compatibility 

2810 nonfinites = _xkwds_get1(floats, floats=nonfinites) 

2811 elif nonfinites is None: 

2812 nonfinites = not nonfiniterrors() 

2813 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) # PYCHOK yield 

2814 return _fsum(_1primed(fs) if primed else fs) 

2815 

2816 

2817# delete all decorators, etc. 

2818del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \ 

2819 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \ 

2820 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _envPYGEODESY, _std_ 

2821 

2822if __name__ == _DMAIN_: 

2823 

2824 # usage: python3 -m pygeodesy.fsums 

2825 

2826 def _test(n): 

2827 # copied from Hettinger, see L{Fsum} reference 

2828 from pygeodesy import frandoms, printf 

2829 

2830 printf(typename(_fsum), end=_COMMASPACE_) 

2831 printf(typename(_psum), end=_COMMASPACE_) 

2832 

2833 F = Fsum() 

2834 if F.is_math_fsum(): 

2835 for t in frandoms(n, seeded=True): 

2836 assert float(F.fset_(*t)) == _fsum(t) 

2837 printf(_DOT_, end=NN) 

2838 printf(NN) 

2839 

2840 _test(128) 

2841 

2842# **) MIT License 

2843# 

2844# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

2845# 

2846# Permission is hereby granted, free of charge, to any person obtaining a 

2847# copy of this software and associated documentation files (the "Software"), 

2848# to deal in the Software without restriction, including without limitation 

2849# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

2850# and/or sell copies of the Software, and to permit persons to whom the 

2851# Software is furnished to do so, subject to the following conditions: 

2852# 

2853# The above copyright notice and this permission notice shall be included 

2854# in all copies or substantial portions of the Software. 

2855# 

2856# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

2857# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

2858# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

2859# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

2860# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

2861# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

2862# OTHER DEALINGS IN THE SOFTWARE.