Coverage for pygeodesy/fsums.py: 95%

1103 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-09-09 13:03 -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, isodd, isscalar, \ 

43 _signOf, itemsorted, signOf, _xiterable 

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

45 _N_1_0, _isfinite, _pos_self, Float, Int 

46from pygeodesy.errors import _AssertionError, _OverflowError, LenError, _TypeError, \ 

47 _ValueError, _xError, _xError2, _xkwds, _xkwds_get, \ 

48 _xkwds_get1, _xkwds_not, _xkwds_pop, _xsError 

49from pygeodesy.internals import _enquote, _envPYGEODESY, _passarg, typename # _sizeof 

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

51 _not_finite_, _SPACE_, _std_, _UNDER_ 

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

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

54 _NotImplemented, _ALL_LAZY, _MODS 

55from pygeodesy.props import _allPropertiesOf_n, deprecated_method, \ 

56 deprecated_property_RO, Property, \ 

57 Property_RO, property_RO 

58from pygeodesy.streprs import Fmt, fstr, unstr 

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

60 

61from math import fabs, isinf, isnan, \ 

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

63 

64__all__ = _ALL_LAZY.fsums 

65__version__ = '25.06.03' 

66 

67from pygeodesy.interns import ( 

68 _PLUS_ as _add_op_, # in .auxilats.auxAngle 

69 _DSLASH_ as _floordiv_op_, 

70 _EQUAL_ as _fset_op_, 

71 _RANGLE_ as _gt_op_, 

72 _LANGLE_ as _lt_op_, 

73 _PERCENT_ as _mod_op_, 

74 _STAR_ as _mul_op_, 

75 _NOTEQUAL_ as _ne_op_, 

76 _DSTAR_ as _pow_op_, 

77 _DASH_ as _sub_op_, # in .auxilats.auxAngle 

78 _SLASH_ as _truediv_op_ 

79) 

80_divmod_op_ = _floordiv_op_ + _mod_op_ 

81_F2PRODUCT = _envPYGEODESY('FSUM_F2PRODUCT') 

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

83_integer_ = 'integer' 

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

85_NONFINITEr = _0_0 # NOT INT0! 

86_NONFINITES = _envPYGEODESY('FSUM_NONFINITES') 

87_non_zero_ = 'non-zero' 

88_RESIDUAL_0_0 = _envPYGEODESY('FSUM_RESIDUAL', _0_0) 

89_significant_ = 'significant' 

90_threshold_ = 'threshold' 

91 

92 

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

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

95 ''' 

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

97 else _nfError(x)) 

98 

99 

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

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

102 ''' 

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

104 try: 

105 f = float(x) 

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

107 except Exception as X: 

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

109 

110 

111try: # MCCABE 26 

112 from math import fma as _fma 

113 

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

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

116 # TwoProductFMA U{Algorithm 3.5 

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

118 for y in ys: 

119 f = x * y 

120 yield f 

121 if _isfinite(f): 

122 f = _fma(x, y, -f) 

123 if f: 

124 yield 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 def __ceil__(self): # PYCHOK not special in Python 2- 

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

565 

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

567 

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

569 ''' 

570 return self.ceil 

571 

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

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

574 

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

576 

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

578 ''' 

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

580 return _signOf(s, 0) 

581 

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

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

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

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

586 

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

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

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

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

591 

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

593 B{C{RESIDUAL}}. 

594 

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

596 ''' 

597 f = self._copyd(self.__divmod__) 

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

599 

600 def __eq__(self, other): 

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

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

603 ''' 

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

605 

606 def __float__(self): 

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

608 

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

610 ''' 

611 return float(self._fprs) 

612 

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

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

615 

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

617 

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

619 ''' 

620 return self.floor 

621 

622 def __floordiv__(self, other): 

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

624 

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

626 

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

628 

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

630 ''' 

631 f = self._copyd(self.__floordiv__) 

632 return f._floordiv(other, _floordiv_op_) 

633 

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

635# '''Not implemented.''' 

636# return _NotImplemented(self, *other) 

637 

638 def __ge__(self, other): 

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

640 ''' 

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

642 

643 def __gt__(self, other): 

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

645 ''' 

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

647 

648 def __hash__(self): # PYCHOK no cover 

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

650 ''' 

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

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

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

654 

655 def __iadd__(self, other): 

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

657 

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

659 an iterable of several of the former. 

660 

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

662 

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

664 C{scalar} nor L{Fsum}. 

665 

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

667 ''' 

668 try: 

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

670 except TypeError: 

671 pass 

672 _xiterable(other) 

673 return self._facc(other) 

674 

675 def __ifloordiv__(self, other): 

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

677 

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

679 

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

681 

682 @raise ResidualError: Non-zero, significant residual 

683 in B{C{other}}. 

684 

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

686 

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

688 

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

690 

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

692 ''' 

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

694 

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

696 '''Not implemented.''' 

697 return _NotImplemented(self, other) 

698 

699 def __imod__(self, other): 

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

701 

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

703 

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

705 

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

707 ''' 

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

709 

710 def __imul__(self, other): 

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

712 

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

714 

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

716 

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

718 

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

720 

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

722 ''' 

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

724 

725 def __int__(self): 

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

727 

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

729 and L{Fsum.floor}. 

730 ''' 

731 i, _ = self._fint2 

732 return i 

733 

734 def __invert__(self): # PYCHOK no cover 

735 '''Not implemented.''' 

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

737 return _NotImplemented(self) 

738 

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

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

741 

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

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

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

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

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

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

748 

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

750 

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

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

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

754 

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

756 

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

758 is non-zero and significant and either 

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

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

761 C{None}. 

762 

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

764 invocation failed. 

765 

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

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

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

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

770 is given as C{0}. 

771 

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

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

774 ''' 

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

776 

777 def __isub__(self, other): 

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

779 

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

781 an iterable of several of the former. 

782 

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

784 

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

786 

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

788 ''' 

789 try: 

790 return self._fsub(other, _isub_op_) 

791 except TypeError: 

792 pass 

793 _xiterable(other) 

794 return self._facc_neg(other) 

795 

796 def __iter__(self): 

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

798 ''' 

799 return iter(self.partials) 

800 

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

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

803 

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

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

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

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

808 

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

810 

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

812 

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

814 B{C{RESIDUAL}}. 

815 

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

817 

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

819 

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

821 

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

823 ''' 

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

825 

826 def __le__(self, other): 

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

828 ''' 

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

830 

831 def __len__(self): 

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

833 ''' 

834 return self._n 

835 

836 def __lt__(self, other): 

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

838 ''' 

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

840 

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

842 '''Not implemented.''' 

843 return _NotImplemented(self, other) 

844 

845 def __mod__(self, other): 

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

847 

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

849 ''' 

850 f = self._copyd(self.__mod__) 

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

852 

853 def __mul__(self, other): 

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

855 

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

857 ''' 

858 f = self._copyd(self.__mul__) 

859 return f._fmul(other, _mul_op_) 

860 

861 def __ne__(self, other): 

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

863 ''' 

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

865 

866 def __neg__(self): 

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

868 ''' 

869 f = self._copyd(self.__neg__) 

870 return f._fset(self._neg) 

871 

872 def __pos__(self): 

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

874 ''' 

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

876 

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

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

879 

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

881 ''' 

882 f = self._copyd(self.__pow__) 

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

884 

885 def __radd__(self, other): 

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

887 

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

889 ''' 

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

891 return f._fadd(self) 

892 

893 def __rdivmod__(self, other): 

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

895 C{(quotient, remainder)}. 

896 

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

898 ''' 

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

900 return f._fdivmod2(self, _divmod_op_) 

901 

902# turned off, called by _deepcopy and _copy 

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

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

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

906# ''' 

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

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

909 

910# def __repr__(self): 

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

912# ''' 

913# return self.toRepr(lenc=True) 

914 

915 def __rfloordiv__(self, other): 

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

917 

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

919 ''' 

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

921 return f._floordiv(self, _floordiv_op_) 

922 

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

924 '''Not implemented.''' 

925 return _NotImplemented(self, other) 

926 

927 def __rmod__(self, other): 

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

929 

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

931 ''' 

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

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

934 

935 def __rmul__(self, other): 

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

937 

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

939 ''' 

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

941 return f._fmul(self, _mul_op_) 

942 

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

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

945 

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

947 ''' 

948 f = self._copyd(self.__round__) 

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

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

951 

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

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

954 

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

956 ''' 

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

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

959 

960 def __rsub__(self, other): 

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

962 

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

964 ''' 

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

966 return f._fsub(self, _sub_op_) 

967 

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

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

970 

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

972 ''' 

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

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

975 

976# def __sizeof__(self): 

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

978# ''' 

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

980 

981 def __str__(self): 

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

983 ''' 

984 return self.toStr(lenc=True) 

985 

986 def __sub__(self, other): 

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

988 

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

990 

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

992 

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

994 ''' 

995 f = self._copyd(self.__sub__) 

996 return f._fsub(other, _sub_op_) 

997 

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

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

1000 

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

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

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

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

1005 

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

1007 

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

1009 B{C{RESIDUAL}}. 

1010 

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

1012 ''' 

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

1014 

1015 __trunc__ = __int__ 

1016 

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

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

1019 __div__ = __truediv__ 

1020 __idiv__ = __itruediv__ 

1021 __long__ = __int__ 

1022 __nonzero__ = __bool__ 

1023 __rdiv__ = __rtruediv__ 

1024 

1025 def as_integer_ratio(self): 

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

1027 

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

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

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

1031 instance is. 

1032 

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

1034 Python 2.7+. 

1035 ''' 

1036 n, r = self._fint2 

1037 if r: 

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

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

1040 else: # PYCHOK no cover 

1041 d = 1 

1042 return n, d 

1043 

1044 @property_RO 

1045 def as_iscalar(self): 

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

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

1048 ''' 

1049 s, r = self._nfprs2 

1050 return self if r else s 

1051 

1052 @property_RO 

1053 def ceil(self): 

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

1055 C{float} in Python 2-). 

1056 

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

1058 

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

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

1061 ''' 

1062 s, r = self._fprs2 

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

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

1065 c += 1 

1066 return c # _ceil(self._n_d) 

1067 

1068 cmp = __cmp__ 

1069 

1070 def _cmp_0(self, other, op): 

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

1072 ''' 

1073 if _isFsum_2Tuple(other): 

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

1075 elif self._scalar(other, op): 

1076 s = self._ps_1sum(other) 

1077 else: 

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

1079 return s 

1080 

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

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

1083 

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

1085 

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

1087 ''' 

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

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

1090 if f._ps is self._ps: 

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

1092 if not deep: 

1093 f._n = 1 

1094 # assert f._f2product == self._f2product 

1095 # assert f._Fsum is f 

1096 # assert f._isfine is self._isfine 

1097 # assert f._RESIDUAL is self._RESIDUAL 

1098 return f 

1099 

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

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

1102 ''' 

1103 n = name or typename(which) 

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

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

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

1107 # assert f._n == self._n 

1108 # assert f._f2product == self._f2product 

1109 # assert f._Fsum is f 

1110 # assert f._isfine is self._isfine 

1111 # assert f._RESIDUAL is self._RESIDUAL 

1112 return f 

1113 

1114 divmod = __divmod__ 

1115 

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

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

1118 ''' 

1119 # self.as_iscalar causes RecursionError for ._fprs2 errors 

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

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

1122 

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

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

1125 ''' 

1126 E, t = _xError2(X) 

1127 if mod: 

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

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

1130 

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

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

1133 ''' 

1134 E, t = _xError2(X) 

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

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

1137 

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

1139 '''(INTERNAL) Accumulate more C{scalar}s, L{Fsum}s pr L{Fsum2Tuple}s. 

1140 ''' 

1141 if xs: 

1142 kwds = self._isfine 

1143 if _X_x_origin: 

1144 kwds = _xkwds(_X_x_origin, **kwds) 

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

1146 ps = self._ps 

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

1148# if len(ps) > 16: 

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

1150 return self 

1151 

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

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

1154 arguments in the caller of this method. 

1155 ''' 

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

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

1158 

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

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

1161 ''' 

1162 if n > 0: 

1163 _f = Fsum(**kwds) 

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

1165 return self 

1166 

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

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

1169 ''' 

1170 def _N(X): 

1171 return X._ps_neg 

1172 

1173 def _n(x): 

1174 return -float(x) 

1175 

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

1177 

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

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

1180 ''' 

1181 def _Pow4(p): 

1182 r = 0 

1183 if _isFsum_2Tuple(p): 

1184 s, r = p._fprs2 

1185 if r: 

1186 m = Fsum._pow 

1187 else: # scalar 

1188 return _Pow4(s) 

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

1190 p = s = int(p) 

1191 m = Fsum._pow_int 

1192 else: 

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

1194 m = Fsum._pow_scalar 

1195 return m, p, s, r 

1196 

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

1198 if p: # and xs: 

1199 op = typename(which) 

1200 _FsT = _Fsum_2Tuple_types 

1201 _pow = self._pow_2_3 

1202 

1203 def _P(X): 

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

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

1206 

1207 def _p(x): 

1208 x = float(x) 

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

1210 if f and r: 

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

1212 return f 

1213 

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

1215 else: 

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

1217 return f 

1218 

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

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

1221 ''' 

1222 if xs: 

1223 ps = self._ps 

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

1225 return self 

1226 

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

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

1229 ''' 

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

1231 

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

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

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

1235# ''' 

1236# ps = self._ps 

1237# while len(ps) > 1: 

1238# p = ps.pop() 

1239# if p: 

1240# n = self._n 

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

1242# self._n = n 

1243# break 

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

1245 

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

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

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

1249 ''' 

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

1251 **origin_which)) # PYCHOK yield 

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

1253 

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

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

1256 

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

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

1259 

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

1261 

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

1263 

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

1265 

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

1267 ''' 

1268 if _isFsum_2Tuple(xs): 

1269 self._facc_scalar(xs._ps) 

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

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

1272 self._facc_scalar_(x) 

1273 elif xs: # _xiterable(xs) 

1274 self._facc(xs) 

1275 return self 

1276 

1277 def fadd_(self, *xs): 

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

1279 

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

1281 or L{Fsum2Tuple}), all positional. 

1282 

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

1284 ''' 

1285 return self._facc_args(xs) 

1286 

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

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

1289 ''' 

1290 if _isFsum_2Tuple(other): 

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

1292 elif self._scalar(other, op): 

1293 self._facc_scalar_(other, **up) 

1294 return self 

1295 

1296 fcopy = copy # for backward compatibility 

1297 fdiv = __itruediv__ 

1298 fdivmod = __divmod__ 

1299 

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

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

1302 ''' 

1303 # result mostly follows CPython function U{float_divmod 

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

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

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

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

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

1309 

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

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

1312 self += other 

1313 q -= 1 

1314# t = self.signOf() 

1315# if t and t != s: 

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

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

1318 

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

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

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

1322 enumerate if B{incx} else _enumereverse}. 

1323 ''' 

1324 # assert _xiterablen(cs) 

1325 try: 

1326 n = len(cs) 

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

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

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

1330 H._mul_scalar 

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

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

1333 H._fadd(c, up=False) 

1334 else: # x == 0 

1335 H = cs[0] if n else 0 

1336 self._fadd(H) 

1337 except Exception as X: 

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

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

1340 return self 

1341 

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

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

1344 ''' 

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

1346 return other 

1347 E = _NonfiniteError(other) 

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

1349 

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

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

1352 

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

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

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

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

1357 

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

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

1360 

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

1362 B{C{RESIDUAL}}. 

1363 

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

1365 ''' 

1366 i, r = self._fint2 

1367 if r: 

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

1369 if R: 

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

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

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

1373 

1374 def fint2(self, **name): 

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

1376 I{integer} residual. 

1377 

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

1379 

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

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

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

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

1384 ''' 

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

1386 

1387 @Property 

1388 def _fint2(self): # see ._fset 

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

1390 ''' 

1391 s, r = self._nfprs2 

1392 if _isfinite(s): 

1393 i = int(s) 

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

1395 float(s - i)) or INT0 

1396 else: # INF, NAN, NINF 

1397 i = float(s) 

1398# r = _NONFINITEr 

1399 return i, r # Fsum2Tuple? 

1400 

1401 @_fint2.setter_ # PYCHOK setter_UNDERscore! 

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

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

1404 ''' 

1405 if _isfinite(s): 

1406 i = int(s) 

1407 r = (s - i) or INT0 

1408 else: # INF, NAN, NINF 

1409 i = float(s) 

1410 r = _NONFINITEr 

1411 return i, r # like _fint2.getter 

1412 

1413 @deprecated_property_RO 

1414 def float_int(self): # PYCHOK no cover 

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

1416 return self.int_float() # raiser=False 

1417 

1418 @property_RO 

1419 def floor(self): 

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

1421 C{float} in Python 2-). 

1422 

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

1424 

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

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

1427 ''' 

1428 s, r = self._fprs2 

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

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

1431 f -= 1 

1432 return f # _floor(self._n_d) 

1433 

1434# ffloordiv = __ifloordiv__ # for naming consistency? 

1435# floordiv = __floordiv__ # for naming consistency? 

1436 

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

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

1439 ''' 

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

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

1442 

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

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

1445 

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

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

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

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

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

1451 ''' 

1452 op = typename(self.fma) 

1453 _fs = self._ps_other 

1454 try: 

1455 s, r = self._fprs2 

1456 if r: 

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

1458 f += other2 

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

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

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

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

1463 else: 

1464 f = _fma(s, other1, other2) 

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

1466 except TypeError as X: 

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

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

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

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

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

1472 return self._fset(f) 

1473 

1474 def fma_(self, *xys, **nonfinites): 

1475 '''Fused-multiply-accumulate C{for i in range(0, len(xys), B{2}): 

1476 self = }L{fma<pygeodesy.fmath.fma>}C{(xys[i], xys[i+1], self)}. 

1477 

1478 @arg xys: Pairwise multiplicand, multiplier (each C{scalar}, 

1479 an L{Fsum} or L{Fsum2Tuple}), all positional. 

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

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

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

1483 

1484 @note: Equivalent to L{fdot_<pygeodesy.fmath.fdot_>}C{(*xys, 

1485 start=self)}. 

1486 ''' 

1487 if xys: 

1488 n = len(xys) 

1489 if n < 2 or isodd(n): 

1490 raise LenError(self.fma_, xys=n) 

1491 f, _fmath_fma = self, _MODS.fmath.fma 

1492 for x, y in zip(xys[0::2], xys[1::2]): 

1493 f = _fmath_fma(x, y, f, **nonfinites) 

1494 self._fset(f) 

1495 return self 

1496 

1497 fmul = __imul__ 

1498 

1499 def _fmul(self, other, op): 

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

1501 ''' 

1502 if _isFsum_2Tuple(other): 

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

1504 f = self._mul_Fsum(other, op) 

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

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

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

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

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

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

1511 else: 

1512 s = self._scalar(other, op) 

1513 f = self._mul_scalar(s, op) 

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

1515 

1516 @deprecated_method 

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

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

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

1520 

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

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

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

1524 

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

1526 positional. 

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

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

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

1530 

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

1532 

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

1534 ''' 

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

1536 

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

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

1539 ''' 

1540 n = typename(where) 

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

1542 if others and f: 

1543 if f.f2product(): 

1544 def _pfs(f, ps): 

1545 return _2products(f, _2split3s(ps)) 

1546 else: 

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

1548 return (f * p for p in ps) 

1549 

1550 op, ps = n, f._ps 

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

1552 for other in others: # to pinpoint errors 

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

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

1555 f._update() 

1556 except TypeError as X: 

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

1558 except (OverflowError, ValueError) as X: 

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

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

1561 f._fset(r) 

1562 return f 

1563 

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

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

1566 

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

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

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

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

1571 

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

1573 

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

1575 B{C{RESIDUAL}}. 

1576 

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

1578 ''' 

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

1580 

1581 fpow = __ipow__ 

1582 

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

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

1585 ''' 

1586 if mod: 

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

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

1589 elif self.is_integer(): 

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

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

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

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

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

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

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

1597 else: # pow(self, other) 

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

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

1600 

1601 def f2product(self, *two): 

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

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

1604 

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

1606 turn I{TwoProduct} on, if C{False} off, or if C{None} 

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

1608 

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

1610 

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

1612 

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

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

1615 ''' 

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

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

1618 if two[0] is not None: 

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

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

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

1622 return t 

1623 

1624 @Property 

1625 def _fprs(self): 

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

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

1628 

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

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

1631 ''' 

1632 s, _ = self._fprs2 

1633 return s # ._fprs2.fsum 

1634 

1635 @_fprs.setter_ # PYCHOK setter_UNDERscore! 

1636 def _fprs(self, s): 

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

1638 ''' 

1639 return s 

1640 

1641 @Property 

1642 def _fprs2(self): 

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

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

1645 ''' 

1646 ps = self._ps 

1647 n = len(ps) 

1648 try: 

1649 if n > 2: 

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

1651 if not _isfinite(s): 

1652 ps[:] = s, # collapse ps 

1653 return Fsum2Tuple(s, _NONFINITEr) 

1654 n = len(ps) 

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

1656 if n > 2: 

1657 r = self._ps_1sum(s) 

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

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

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

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

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

1663 s = ps[0] 

1664 r = INT0 if _isfinite(s) else _NONFINITEr 

1665 else: # len(ps) == 0 

1666 s = _0_0 

1667 r = INT0 if _isfinite(s) else _NONFINITEr 

1668 ps[:] = s, 

1669 except (OverflowError, ValueError) as X: 

1670 op = _fset_op_ # INF, NAN, NINF 

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

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

1673 r = _NONFINITEr 

1674 # assert self._ps is ps 

1675 return Fsum2Tuple(s, r) 

1676 

1677 @_fprs2.setter_ # PYCHOK setter_UNDERscore! 

1678 def _fprs2(self, s_r): 

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

1680 ''' 

1681 return Fsum2Tuple(s_r) 

1682 

1683 def fset_(self, *xs): 

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

1685 

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

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

1688 

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

1690 

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

1692 ''' 

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

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

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

1696 

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

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

1699 ''' 

1700 if other is self: 

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

1702 elif _isFsum_2Tuple(other): 

1703 if op: # and not self.nonfinitesOK: 

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

1705 self._ps[:] = other._ps 

1706 self._n = n or other._n 

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

1708 Fsum._fint2._update_from(self, other) 

1709 Fsum._fprs ._update_from(self, other) 

1710 Fsum._fprs2._update_from(self, other) 

1711 elif isscalar(other): 

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

1713 self._ps[:] = s, 

1714 self._n = n or 1 

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

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

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

1718 self._fint2 = s 

1719 self._fprs = s 

1720 self._fprs2 = s, INT0 

1721 # assert self._fprs is s 

1722 else: 

1723 op = _xkwds_get1(op, op=_fset_op_) 

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

1725 return self 

1726 

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

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

1729 

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

1731 ''' 

1732 return self._facc_neg(xs) 

1733 

1734 def fsub_(self, *xs): 

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

1736 

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

1738 ''' 

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

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

1741 

1742 def _fsub(self, other, op): 

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

1744 ''' 

1745 if _isFsum_2Tuple(other): 

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

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

1748 elif other._ps: 

1749 self._facc_scalar(other._ps_neg) 

1750 elif self._scalar(other, op): 

1751 self._facc_scalar_(-other) 

1752 return self 

1753 

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

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

1756 precision running sum. 

1757 

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

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

1760 

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

1762 

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

1764 

1765 @note: Accumulation can continue after summation. 

1766 ''' 

1767 return self._facc(xs)._fprs 

1768 

1769 def fsum_(self, *xs): 

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

1771 precision running sum. 

1772 

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

1774 L{Fsum2Tuple}), all positional. 

1775 

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

1777 

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

1779 ''' 

1780 return self._facc_args(xs)._fprs 

1781 

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

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

1784 

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

1786 

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

1788 ''' 

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

1790 

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

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

1793 

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

1795 

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

1797 ''' 

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

1799 

1800 @property_RO 

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

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

1803 

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

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

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

1807 overridden with C{name_f2product_nonfinites_RESIDUAL} and 

1808 with any C{xs} accumulated. 

1809 ''' 

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

1811 nonfinites=self.nonfinites(), 

1812 RESIDUAL =self.RESIDUAL()) 

1813 if name_f2product_nonfinites_RESIDUAL: # overwrites 

1814 kwds.update(name_f2product_nonfinites_RESIDUAL) 

1815 f = Fsum(**kwds) 

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

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

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

1819 

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

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

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

1823 

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

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

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

1827 

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

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

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

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

1832 to be I{exact}. 

1833 

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

1835 ''' 

1836 t = self._facc(xs)._fprs2 

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

1838 

1839 def fsum2_(self, *xs): 

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

1841 precision running sum and the I{differential}. 

1842 

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

1844 L{Fsum2Tuple}), all positional. 

1845 

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

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

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

1849 

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

1851 ''' 

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

1853 

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

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

1856 ''' 

1857 p, q = self._fprs2 

1858 if xs: 

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

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

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

1862 r, _ = _s_r2(d, r) 

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

1864 else: 

1865 return p, _0_0 

1866 

1867 def fsumf_(self, *xs): 

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

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

1870 ''' 

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

1872 

1873 def Fsumf_(self, *xs): 

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

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

1876 ''' 

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

1878 

1879 def fsum2f_(self, *xs): 

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

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

1882 ''' 

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

1884 

1885# ftruediv = __itruediv__ # for naming consistency? 

1886 

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

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

1889 ''' 

1890 n = _1_0 

1891 if _isFsum_2Tuple(other): 

1892 if other is self or self == other: 

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

1894 d, r = other._fprs2 

1895 if r: 

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

1897 if R: 

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

1899 d, n = other.as_integer_ratio() 

1900 else: 

1901 d = self._scalar(other, op) 

1902 try: 

1903 s = n / d 

1904 except Exception as X: 

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

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

1907 return self._fset(f) 

1908 

1909 @property_RO 

1910 def imag(self): 

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

1912 

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

1914 ''' 

1915 return _0_0 

1916 

1917 def int_float(self, **raiser_RESIDUAL): 

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

1919 

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

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

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

1923 

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

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

1926 is zero or not significant. 

1927 

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

1929 B{C{RESIDUAL}}. 

1930 

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

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

1933 ''' 

1934 s, r = self._fint2 

1935 if r: 

1936 s, r = self._fprs2 

1937 if r: # PYCHOK no cover 

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

1939 if R: 

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

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

1942 s = float(s) 

1943 return s 

1944 

1945 def is_exact(self): 

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

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

1948 ''' 

1949 return self.residual is INT0 

1950 

1951 def is_finite(self): # in .constants 

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

1953 

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

1955 ''' 

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

1957 

1958 def is_integer(self): 

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

1960 

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

1962 ''' 

1963 s, r = self._fint2 

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

1965 

1966 def is_math_fma(self): 

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

1968 

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

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

1971 C{PyGeodesy} implementation. 

1972 ''' 

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

1974 

1975 def is_math_fsum(self): 

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

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

1978 

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

1980 otherwise. 

1981 ''' 

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

1983 

1984 def is_scalar(self, **raiser_RESIDUAL): 

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

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

1987 

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

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

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

1991 

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

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

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

1995 

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

1997 B{C{RESIDUAL}}. 

1998 

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

2000 L{Fsum.as_iscalar}. 

2001 ''' 

2002 s, r = self._fprs2 

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

2004 

2005 def _mul_Fsum(self, other, op): 

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

2007 ''' 

2008 # assert _isFsum_2Tuple(other) 

2009 if self._ps and other._ps: 

2010 try: 

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

2012 except Exception as X: 

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

2014 else: 

2015 f = _0_0 

2016 return f 

2017 

2018 def _mul_reduce(self, *others): 

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

2020 ''' 

2021 r = _1_0 

2022 for f in others: 

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

2024 return r 

2025 

2026 def _mul_scalar(self, factor, op): 

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

2028 ''' 

2029 # assert isscalar(factor) 

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

2031 f = self if factor == _1_0 else ( 

2032 self._neg if factor == _N_1_0 else 

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

2034 else: 

2035 f = _0_0 

2036 return f 

2037 

2038# @property_RO 

2039# def _n_d(self): 

2040# n, d = self.as_integer_ratio() 

2041# return n / d 

2042 

2043 @property_RO 

2044 def _neg(self): 

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

2046 ''' 

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

2048 

2049 @property_RO 

2050 def _nfprs2(self): 

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

2052 ''' 

2053 try: # to handle nonfiniterrors, etc. 

2054 t = self._fprs2 

2055 except (OverflowError, ValueError): 

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

2057 return t 

2058 

2059 def nonfinites(self, *OK): 

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

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

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

2063 

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

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

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

2067 

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

2069 

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

2071 

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

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

2074 L{nonfiniterrors} default. 

2075 ''' 

2076 _ks = Fsum._nonfinites_isfine_kwds 

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

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

2079 if OK[0] is not None: 

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

2081 self._update() 

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

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

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

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

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

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

2088 

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

2090 False: dict(_isfine=_isfinite)} 

2091 

2092 @property_RO 

2093 def nonfinitesOK(self): 

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

2095 ''' 

2096# nf = self.nonfinites() 

2097# if nf is None: 

2098# nf = not nonfiniterrors() 

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

2100 

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

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

2103 ''' 

2104 if nonfinites is None: 

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

2106 if not nonfinites: 

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

2108 return f 

2109 

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

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

2112 ''' 

2113 if f2product is not None: 

2114 self.f2product(f2product) 

2115 if nonfinites is not None: 

2116 self.nonfinites(nonfinites) 

2117 if name_RESIDUAL: # MUST be last 

2118 n, kwds = _name2__(**name_RESIDUAL) 

2119 if kwds: 

2120 R = Fsum._RESIDUAL 

2121 t = _threshold(R, **kwds) 

2122 if t != R: 

2123 self._RESIDUAL = t 

2124 if n: 

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

2126 

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

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

2129 ''' 

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

2131 

2132 @property_RO 

2133 def partials(self): 

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

2135 ''' 

2136 return tuple(self._ps) 

2137 

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

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

2140 

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

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

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

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

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

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

2147 

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

2149 result (L{Fsum}). 

2150 

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

2152 B{C{RESIDUAL}}. 

2153 

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

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

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

2157 

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

2159 and L{Fsum.root}. 

2160 ''' 

2161 f = self._copyd(self.pow) 

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

2163 

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

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

2166 ''' 

2167 if _isFsum_2Tuple(other): 

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

2169 elif self._scalar(other, op): 

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

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

2172 else: 

2173 f = self._pow_0_1(0, other) 

2174 return f 

2175 

2176 def _pow_0_1(self, x, other): 

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

2178 ''' 

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

2180 

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

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

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

2184 ''' 

2185 

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

2187 m = mod[0] 

2188 # assert _isFsum_2Tuple(b) 

2189 

2190 def _s(s, r): 

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

2192 if R: 

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

2194 return s 

2195 

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

2197 x = _s(*_2tuple2(x)) 

2198 

2199 try: 

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

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

2202 if iscomplex(s): 

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

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

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

2206 return s 

2207 except Exception as X: 

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

2209 

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

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

2212 ''' 

2213 # assert _isFsum_2Tuple(other) 

2214 x, r = other._fprs2 

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

2216 if f and r: 

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

2218 return f 

2219 

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

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

2222 ''' 

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

2224 ps = self._ps 

2225 if len(ps) > 1: 

2226 _mul_Fsum = Fsum._mul_Fsum 

2227 if x > 4: 

2228 p = self 

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

2230 m = x >> 1 # // 2 

2231 while m: 

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

2233 if (m & 1): 

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

2235 m >>= 1 # //= 2 

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

2237 f = _mul_Fsum(self, self, op) 

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

2239 p = self if x < 4 else f 

2240 f = _mul_Fsum(f, p, op) 

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

2242 f = self._pow_0_1(x, other) 

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

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

2245 else: # PYCHOK no cover 

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

2247 f = 0 if x else 1 

2248 return f 

2249 

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

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

2252 ''' 

2253 s, r = self._fprs2 

2254 if r: 

2255 # assert s != 0 

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

2257 x = int(x) 

2258 y = abs(x) 

2259 if y > 1: 

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

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

2262 return f # Fsum or scalar 

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

2264 if _isFsum(f): 

2265 s, r = f._fprs2 

2266 if r: 

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

2268 else: # scalar 

2269 s = f 

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

2271 # float_pow error iff s is zero 

2272 x = -1 

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

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

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

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

2277 else: # self**fractional 

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

2279 if R: 

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

2281 n, d = self.as_integer_ratio() 

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

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

2284 s = n / d 

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

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

2287 

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

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

2290 ''' 

2291 n = 0 

2292 _2s = _2sum 

2293 _fi = self._isfine 

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

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

2296 if x: 

2297 i = 0 

2298 for p in ps: 

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

2300 if p: 

2301 ps[i] = p 

2302 i += 1 

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

2304 n += 1 

2305 if n: 

2306 self._n += n 

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

2308 if up: 

2309 self._update() 

2310# x = sum(ps) 

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

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

2313 return ps 

2314 

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

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

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

2318 ''' 

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

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

2321 ps, fs = fs, ps 

2322 if self._f2product: 

2323 fs, p = _2split3s(fs), fs 

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

2325 fs = tuple(fs) # several ps 

2326 _pfs = _2products 

2327 else: 

2328 def _pfs(p, fs): 

2329 return (p * f for f in fs) 

2330 

2331 for p in ps: 

2332 for x in _pfs(p, fs): 

2333 yield x if _isfine(x) else _nfError(x) 

2334 

2335 xs = _psfs(self._ps, factors, **self._isfine) 

2336 f = _Psum(self._ps_acc([], xs, up=False), name=op) 

2337 return f 

2338 

2339 @property_RO 

2340 def _ps_neg(self): 

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

2342 ''' 

2343 for p in self._ps: 

2344 yield -p 

2345 

2346 def _ps_other(self, op, other): 

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

2348 ''' 

2349 if _isFsum_2Tuple(other): 

2350 for p in other._ps: 

2351 yield p 

2352 else: 

2353 yield self._scalar(other, op) 

2354 

2355 def _ps_1sum(self, *less): 

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

2357 ''' 

2358 def _1psls(ps, ls): 

2359 yield _1_0 

2360 for p in ps: 

2361 yield p 

2362 for p in ls: 

2363 yield -p 

2364 yield _N_1_0 

2365 

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

2367 

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

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

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

2371 negative respectively positive C{RESIDUAL} threshold)? 

2372 ''' 

2373 if r and raiser: 

2374 t = self._RESIDUAL 

2375 if RESIDUAL: 

2376 t = _threshold(t, **RESIDUAL) 

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

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

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

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

2381 return {} 

2382 

2383 def _rcopyd(self, other, which): 

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

2385 ''' 

2386 return other._copyd(which) if _isFsum(other) else \ 

2387 self._copyd(which)._fset(other) 

2388 

2389 rdiv = __rtruediv__ 

2390 

2391 @property_RO 

2392 def real(self): 

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

2394 

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

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

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

2398 ''' 

2399 return float(self) 

2400 

2401 @property_RO 

2402 def residual(self): 

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

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

2405 

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

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

2408 

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

2410 ''' 

2411 return self._fprs2.residual 

2412 

2413 def RESIDUAL(self, *threshold): 

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

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

2416 

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

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

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

2420 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

2421 current setting. 

2422 

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

2424 

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

2426 

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

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

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

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

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

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

2433 testing without the I{significant} case. 

2434 ''' 

2435 r = self._RESIDUAL 

2436 if threshold: 

2437 t = threshold[0] 

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

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

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

2441 return r 

2442 

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

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

2445 ''' 

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

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

2448 if mod is None else _integer_ 

2449 

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

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

2452 

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

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

2455 

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

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

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

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

2460 

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

2462 

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

2464 B{C{RESIDUAL}}. 

2465 

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

2467 ''' 

2468 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL) 

2469 f = self._copyd(self.root) 

2470 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x) 

2471 

2472 def _scalar(self, other, op, **txt): 

2473 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}. 

2474 ''' 

2475 if isscalar(other): 

2476 return other 

2477 raise self._Error(op, other, _TypeError, **txt) # _invalid_ 

2478 

2479 def signOf(self, res=True): 

2480 '''Determine the sign of this instance. 

2481 

2482 @kwarg res: If C{True}, consider the residual, 

2483 otherwise ignore the latter (C{bool}). 

2484 

2485 @return: The sign (C{int}, -1, 0 or +1). 

2486 ''' 

2487 s, r = self._nfprs2 

2488 r = (-r) if res else 0 

2489 return _signOf(s, r) 

2490 

2491 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature 

2492 '''Return this C{Fsum} instance as representation. 

2493 

2494 @kwarg lenc_prec_sep_fmt: Optional keyword arguments 

2495 for method L{Fsum.toStr}. 

2496 

2497 @return: This instance (C{repr}). 

2498 ''' 

2499 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt)) 

2500 

2501 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature 

2502 '''Return this C{Fsum} instance as string. 

2503 

2504 @kwarg lenc: If C{True}, include the current C{[len]} of this 

2505 L{Fsum} enclosed in I{[brackets]} (C{bool}). 

2506 @kwarg prec_sep_fmt: Optional keyword arguments for method 

2507 L{Fsum2Tuple.toStr}. 

2508 

2509 @return: This instance (C{str}). 

2510 ''' 

2511 p = self.classname 

2512 if lenc: 

2513 p = Fmt.SQUARE(p, len(self)) 

2514 n = _enquote(self.name, white=_UNDER_) 

2515 t = self._nfprs2.toStr(**prec_sep_fmt) 

2516 return NN(p, _SPACE_, n, t) 

2517 

2518 def _truediv(self, other, op, **raiser_RESIDUAL): 

2519 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}. 

2520 ''' 

2521 f = self._copyd(self.__truediv__) 

2522 return f._ftruediv(other, op, **raiser_RESIDUAL) 

2523 

2524 def _update(self, updated=True): # see ._fset 

2525 '''(INTERNAL) Zap all cached C{Property_RO} values. 

2526 ''' 

2527 if updated: 

2528 _pop = self.__dict__.pop 

2529 for p in _ROs: 

2530 _ = _pop(p, None) 

2531# Fsum._fint2._update(self) 

2532# Fsum._fprs ._update(self) 

2533# Fsum._fprs2._update(self) 

2534 return self # for .fset_ 

2535 

2536_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update 

2537 

2538if _NONFINITES == _std_: # PYCHOK no cover 

2539 _ = nonfiniterrors(False) 

2540 

2541 

2542def _Float_Int(arg, **name_Error): 

2543 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit. 

2544 ''' 

2545 U = Int if isint(arg) else Float 

2546 return U(arg, **name_Error) 

2547 

2548 

2549class DivMod2Tuple(_NamedTuple): 

2550 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder 

2551 C{mod} results of a C{divmod} operation. 

2552 

2553 @note: Quotient C{div} an C{int} in Python 3+ but a C{float} 

2554 in Python 2-. Remainder C{mod} an L{Fsum} instance. 

2555 ''' 

2556 _Names_ = ('div', 'mod') 

2557 _Units_ = (_Float_Int, Fsum) 

2558 

2559 

2560class Fsum2Tuple(_NamedTuple): # in .fstats 

2561 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum} 

2562 and the C{residual}, the sum of the remaining partials. Each 

2563 item is C{float} or C{int}. 

2564 

2565 @note: If the C{residual is INT0}, the C{fsum} is considered 

2566 to be I{exact}, see method L{Fsum2Tuple.is_exact}. 

2567 ''' 

2568 _Names_ = ( typename(Fsum.fsum), Fsum.residual.name) 

2569 _Units_ = (_Float_Int, _Float_Int) 

2570 

2571 def __abs__(self): # in .fmath 

2572 return self._Fsum.__abs__() 

2573 

2574 def __bool__(self): # PYCHOK Python 3+ 

2575 return bool(self._Fsum) 

2576 

2577 def __eq__(self, other): 

2578 return self._other_op(other, self.__eq__) 

2579 

2580 def __float__(self): 

2581 return self._Fsum.__float__() 

2582 

2583 def __ge__(self, other): 

2584 return self._other_op(other, self.__ge__) 

2585 

2586 def __gt__(self, other): 

2587 return self._other_op(other, self.__gt__) 

2588 

2589 def __le__(self, other): 

2590 return self._other_op(other, self.__le__) 

2591 

2592 def __lt__(self, other): 

2593 return self._other_op(other, self.__lt__) 

2594 

2595 def __int__(self): 

2596 return self._Fsum.__int__() 

2597 

2598 def __ne__(self, other): 

2599 return self._other_op(other, self.__ne__) 

2600 

2601 def __neg__(self): 

2602 return self._Fsum.__neg__() 

2603 

2604 __nonzero__ = __bool__ # Python 2- 

2605 

2606 def __pos__(self): 

2607 return self._Fsum.__pos__() 

2608 

2609 def as_integer_ratio(self): 

2610 '''Return this instance as the ratio of 2 integers. 

2611 

2612 @see: Method L{Fsum.as_integer_ratio} for further details. 

2613 ''' 

2614 return self._Fsum.as_integer_ratio() 

2615 

2616 @property_RO 

2617 def _fint2(self): 

2618 return self._Fsum._fint2 

2619 

2620 @property_RO 

2621 def _fprs2(self): 

2622 return self._Fsum._fprs2 

2623 

2624 @Property_RO 

2625 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats 

2626 s, r = _s_r2(*self) 

2627 ps = (r, s) if r else (s,) 

2628 return _Psum(ps, name=self.name) 

2629 

2630 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL): 

2631 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}. 

2632 ''' 

2633 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL) 

2634 

2635 def is_exact(self): 

2636 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}). 

2637 ''' 

2638 return self._Fsum.is_exact() 

2639 

2640 def is_finite(self): # in .constants 

2641 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}). 

2642 

2643 @see: Function L{isfinite<pygeodesy.isfinite>}. 

2644 ''' 

2645 return self._Fsum.is_finite() 

2646 

2647 def is_integer(self): 

2648 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}). 

2649 ''' 

2650 return self._Fsum.is_integer() 

2651 

2652 def _mul_scalar(self, other, op): # for Fsum._fmul 

2653 return self._Fsum._mul_scalar(other, op) 

2654 

2655 @property_RO 

2656 def _n(self): 

2657 return self._Fsum._n 

2658 

2659 def _other_op(self, other, which): 

2660 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum) 

2661 return getattr(C, typename(which))(s, other) 

2662 

2663 @property_RO 

2664 def _ps(self): 

2665 return self._Fsum._ps 

2666 

2667 @property_RO 

2668 def _ps_neg(self): 

2669 return self._Fsum._ps_neg 

2670 

2671 def signOf(self, **res): 

2672 '''Like method L{Fsum.signOf}. 

2673 ''' 

2674 return self._Fsum.signOf(**res) 

2675 

2676 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature 

2677 '''Return this L{Fsum2Tuple} as string (C{str}). 

2678 

2679 @kwarg fmt: Optional C{float} format (C{letter}). 

2680 @kwarg prec_sep: Optional keyword arguments for function 

2681 L{fstr<streprs.fstr>}. 

2682 ''' 

2683 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep)) 

2684 

2685_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines 

2686 

2687 

2688class ResidualError(_ValueError): 

2689 '''Error raised for a division, power or root operation of 

2690 an L{Fsum} instance with a C{residual} I{ratio} exceeding 

2691 the L{RESIDUAL<Fsum.RESIDUAL>} threshold. 

2692 

2693 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}. 

2694 ''' 

2695 pass 

2696 

2697 

2698try: 

2699 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+ 

2700 

2701 # make sure _fsum works as expected (XXX check 

2702 # float.__getformat__('float')[:4] == 'IEEE'?) 

2703 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover 

2704 del _fsum # nope, remove _fsum ... 

2705 raise ImportError() # ... use _fsum below 

2706 

2707 _sum = _fsum 

2708except ImportError: 

2709 _sum = sum 

2710 

2711 def _fsum(xs): # in .elliptic 

2712 '''(INTERNAL) Precision summation, Python 2.5-. 

2713 ''' 

2714 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True) 

2715 return float(F._facc(xs, up=False)) 

2716 

2717 

2718def fsum(xs, nonfinites=None, **floats): 

2719 '''Precision floating point summation from Python's C{math.fsum}. 

2720 

2721 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2722 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if 

2723 C{False} I{non-finites} raise an Overflow-/ValueError or if 

2724 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}). 

2725 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use 

2726 keyword argument C{B{nonfinites}=False} instead. 

2727 

2728 @return: Precision C{fsum} (C{float}). 

2729 

2730 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow. 

2731 

2732 @raise TypeError: Invalid B{C{xs}} item. 

2733 

2734 @raise ValueError: Invalid or C{NAN} B{C{xs}} item. 

2735 

2736 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites}, 

2737 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}. 

2738 ''' 

2739 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0 

2740 

2741 

2742def fsum_(*xs, **nonfinites): 

2743 '''Precision floating point summation of all positional items. 

2744 

2745 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

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(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1? 

2751 

2752 

2753def fsumf_(*xs): 

2754 '''Precision floating point summation of all positional items with I{non-finites} C{OK}. 

2755 

2756 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), 

2757 all positional. 

2758 

2759 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2760 ''' 

2761 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1? 

2762 

2763 

2764def fsum1(xs, **nonfinites): 

2765 '''Precision floating point summation, 1-primed. 

2766 

2767 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2768 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2769 

2770 @see: Function L{fsum<fsums.fsum>} for further details. 

2771 ''' 

2772 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0 

2773 

2774 

2775def fsum1_(*xs, **nonfinites): 

2776 '''Precision floating point summation of all positional items, 1-primed. 

2777 

2778 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2779 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2780 

2781 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2782 ''' 

2783 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1? 

2784 

2785 

2786def fsum1f_(*xs): 

2787 '''Precision floating point summation of all positional items, 1-primed and 

2788 with I{non-finites} C{OK}. 

2789 

2790 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2791 ''' 

2792 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0 

2793 

2794 

2795def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers. 

2796 _x_kwds = dict(_x= (_passarg if nfOK else _2finite), 

2797 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds 

2798 _x_kwds.update(kwds) 

2799 return _x_kwds 

2800 

2801 

2802def _X_ps(X): # default C{_X} handler 

2803 return X._ps # lambda X: X._ps 

2804 

2805 

2806def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc 

2807 origin=0, which=None, **_Cdot): 

2808 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s. 

2809 ''' 

2810 i, x = 0, xs 

2811 try: 

2812 for i, x in enumerate(_xiterable(xs)): 

2813 if _isFsum_2Tuple(x): 

2814 for p in _X(x): 

2815 yield p if _isfine(p) else _nfError(p) 

2816 else: 

2817 f = _x(x) 

2818 yield f if _isfine(f) else _nfError(f) 

2819 

2820 except (OverflowError, TypeError, ValueError) as X: 

2821 t = _xsError(X, xs, i + origin, x) 

2822 if which: # prefix invokation 

2823 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot) 

2824 t = _COMMASPACE_(w, t) 

2825 raise _xError(X, t, txt=None) 

2826 

2827 

2828def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0 

2829 '''(INTERNAL) Precision summation of C{xs} with conditions. 

2830 ''' 

2831 if floats: # for backward compatibility 

2832 nonfinites = _xkwds_get1(floats, floats=nonfinites) 

2833 elif nonfinites is None: 

2834 nonfinites = not nonfiniterrors() 

2835 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) # PYCHOK yield 

2836 return _fsum(_1primed(fs) if primed else fs) 

2837 

2838 

2839# delete all decorators, etc. 

2840del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \ 

2841 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \ 

2842 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _envPYGEODESY, _std_ 

2843 

2844if __name__ == _DMAIN_: 

2845 

2846 # usage: python3 -m pygeodesy.fsums 

2847 

2848 def _test(n): 

2849 # copied from Hettinger, see L{Fsum} reference 

2850 from pygeodesy import frandoms, printf 

2851 

2852 printf(typename(_fsum), end=_COMMASPACE_) 

2853 printf(typename(_psum), end=_COMMASPACE_) 

2854 

2855 F = Fsum() 

2856 if F.is_math_fsum(): 

2857 for t in frandoms(n, seeded=True): 

2858 assert float(F.fset_(*t)) == _fsum(t) 

2859 printf(_DOT_, end=NN) 

2860 printf(NN) 

2861 

2862 _test(128) 

2863 

2864# **) MIT License 

2865# 

2866# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

2867# 

2868# Permission is hereby granted, free of charge, to any person obtaining a 

2869# copy of this software and associated documentation files (the "Software"), 

2870# to deal in the Software without restriction, including without limitation 

2871# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

2872# and/or sell copies of the Software, and to permit persons to whom the 

2873# Software is furnished to do so, subject to the following conditions: 

2874# 

2875# The above copyright notice and this permission notice shall be included 

2876# in all copies or substantial portions of the Software. 

2877# 

2878# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

2879# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

2880# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

2881# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

2882# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

2883# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

2884# OTHER DEALINGS IN THE SOFTWARE.