Coverage for pygeodesy/fsums.py: 95%

1107 statements  

« prev     ^ index     » next       coverage.py v7.10.7, created at 2026-03-25 15:01 -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 Python 

93.13 and newer or an equivalent C{fma} implementation for Python 3.12 and 

10older. Set env variable C{PYGEODESY_FSUM_F2PRODUCT} to C{"std"} or any 

11non-empty string or invoke function C{pygeodesy.f2product(True)} to enable 

12accurate multiplication. With C{"std"} the C{fma} implemention follows 

13the C{math.fma} function, otherwise the implementation of the C{PyGeodesy 

1424.09.09} release. 

15 

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

17zero C{residue} aka C{residual}, 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 L{Fsum} is an I{exact float} or I{exact integer}. 

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, Property, \ 

56 deprecated_property_RO, Property_RO, property_RO 

57from pygeodesy.streprs import Fmt, fstr, unstr 

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

59 

60from math import fabs, isinf, isnan, \ 

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

62 

63__all__ = _ALL_LAZY.fsums 

64__version__ = '26.02.02' 

65 

66from pygeodesy.interns import ( 

67 _PLUS_ as _add_op_, # in .auxilats.auxAngle 

68 _DSLASH_ as _floordiv_op_, 

69 _EQUAL_ as _fset_op_, 

70 _RANGLE_ as _gt_op_, 

71 _LANGLE_ as _lt_op_, 

72 _PERCENT_ as _mod_op_, 

73 _STAR_ as _mul_op_, 

74 _NOTEQUAL_ as _ne_op_, 

75 _DSTAR_ as _pow_op_, 

76 _DASH_ as _sub_op_, # in .auxilats.auxAngle 

77 _SLASH_ as _truediv_op_ 

78) 

79_divmod_op_ = _floordiv_op_ + _mod_op_ 

80_F2PRODUCT = _envPYGEODESY('FSUM_F2PRODUCT') 

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

82_integer_ = 'integer' 

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

84_NONFINITEr = _0_0 # NOT INT0! 

85_NONFINITES = _envPYGEODESY('FSUM_NONFINITES') 

86_non_zero_ = 'non-zero' 

87_RESIDUAL_0_0 = _envPYGEODESY('FSUM_RESIDUAL', _0_0) 

88_significant_ = 'significant' 

89_threshold_ = 'threshold' 

90 

91 

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

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

94 ''' 

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

96 else _nfError(x)) 

97 

98 

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

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

101 ''' 

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

103 try: 

104 f = float(x) 

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

106 except Exception as X: 

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

108 

109 

110try: # MCCABE 26 

111 from math import fma as _fma 

112 

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

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

115 # TwoProductFMA U{Algorithm 3.5 

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

117 for y in ys: 

118 f = x * y 

119 yield f 

120 if _isfinite(f): 

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

122 if f: 

123 yield f 

124 for z in zs: 

125 yield z 

126 

127# _2split3 = \ 

128 _2split3s = _passarg # in Fsum.is_math_fma 

129 

130except ImportError: # PYCHOK DSPACE! Python 3.12- 

131 

132 if _F2PRODUCT and _F2PRODUCT != _std_: 

133 # backward to PyGeodesy 24.09.09, with _fmaX 

134 from pygeodesy.basics import _integer_ratio2 

135 

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

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

138 # the same accuracy, but ~14x slower 

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

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

141 d *= db 

142 n *= nb * dc 

143 n += nc * d 

144 d *= dc 

145 try: 

146 n, d = _n_d2(n, d) 

147 r = float(n / d) 

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

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

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

151 else: 

152 _integer_ratio2 = None # redef, in Fsum.is_math_fma 

153 

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

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

156 # the same accuracy, but ~13x slower 

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

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

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

160 

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

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

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

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

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

166 if isnan(r): 

167 def _x(x): 

168 return not isnan(x) 

169 else: # non-finite, non-NAN 

170 _x = _isfinite 

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

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

173 return r 

174 

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

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

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

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

179 _, a, b = _2split3(x) 

180 for y, c, d in y3s: 

181 y *= x 

182 yield y 

183 if _isfinite(y): 

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

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

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

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

188 yield a * c - y 

189 yield b * c 

190 if d: 

191 yield a * d 

192 yield b * d 

193 for z in zs: 

194 yield z 

195 

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

197 

198 def _2split3(x): 

199 # Split U{Algorithm 3.2<https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} 

200 a = c = x * _2FACTOR 

201 a -= c - x 

202 b = x - a 

203 return x, a, b 

204 

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

206 return map(_2split3, xs) 

207 

208 

209def f2product(two=None): 

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

211 

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

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

214 

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

216 

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

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

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

220 equivalent, slower implementation when not available. 

221 ''' 

222 t = Fsum._f2product 

223 if two is not None: 

224 Fsum._f2product = bool(two) 

225 return t 

226 

227 

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

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

230 ''' 

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

232 

233 

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

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

236 ''' 

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

238 

239 

240def _halfeven(s, r, p): 

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

242 ''' 

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

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

245 r *= 2 

246 t = s + r 

247 if r == (t - s): 

248 s = t 

249 return s 

250 

251 

252def _isFsum(x): # in .fmath 

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

254 ''' 

255 return isinstance(x, Fsum) 

256 

257 

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

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

260 ''' 

261 return isinstance(x, _Fsum_2Tuple_types) 

262 

263 

264def _isOK(unused): 

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

266 ''' 

267 return True 

268 

269 

270def _isOK_or_finite(x, _isfine=_isfinite): 

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

272 ''' 

273 # assert _isin(_isfine, _isOK, _isfinite) 

274 return _isfine(x) # C{bool} 

275 

276 

277def _n_d2(n, d): 

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

279 ''' 

280 try: 

281 c = _gcd(n, d) 

282 if c > 1: 

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

284 except TypeError: # non-int float 

285 pass 

286 return n, d 

287 

288 

289def _nfError(x, *args): 

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

291 ''' 

292 E = _NonfiniteError(x) 

293 t = Fmt.PARENSPACED(_not_finite_, x) 

294 if args: # in _fmaX, _2sum 

295 return E(txt=t, *args) 

296 raise E(t, txt=None) 

297 

298 

299def _NonfiniteError(x): 

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

301 ''' 

302 return _OverflowError if isinf(x) else ( 

303 _ValueError if isnan(x) else _AssertionError) 

304 

305 

306def nonfiniterrors(raiser=None): 

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

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

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

310 

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

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

313 the setting unchanged. 

314 

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

316 

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

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

319 ''' 

320 d = Fsum._isfine 

321 if raiser is not None: 

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

323 return (False if d is _nonfinites_isfine_kwds[True] else 

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

325 

326 

327# def _nsum(xs): 

328# '''(INTERNAL) U{Neumaier summation 

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

330# see IV. Verbessertes Kahan-Babuška-Verfahren. 

331# ''' 

332# s = r = _0_0 

333# for x in map(float, xs): 

334# t = s + x 

335# if fabs(x) <= fabs(s): 

336# r += (s - t) + x 

337# else: 

338# r += (x - t) + s 

339# s = t 

340# return s + r 

341 

342 

343def _1primed(xs, *ys): # in .fmath 

344 '''(INTERNAL) 1-Primed summation of iterable C{xs} less any C{ys} 

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

346 ''' 

347 yield _1_0 

348 for x in xs: 

349 yield x 

350 for y in ys: 

351 yield -y 

352 yield _N_1_0 

353 

354 

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

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

357 ''' 

358 # assert isinstance(ps, list) 

359 i = len(ps) - 1 

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

361 while i > 0: 

362 i -= 1 

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

364 if r: # sum(ps) became inexact 

365 if s: 

366 ps[i:] = r, s 

367 if i > 0: 

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

369 break # return s 

370 s = r # PYCHOK no cover 

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

372 i = 0 # collapse ps 

373 if ps: 

374 s += sum(ps) 

375 ps[i:] = s, 

376 return s 

377 

378 

379def _Psum(ps, **name_f2product_nonfinites_RESIDUAL): 

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

381 ''' 

382 F = Fsum(**name_f2product_nonfinites_RESIDUAL) 

383 if ps: 

384 F._ps[:] = ps 

385 F._n = len(F._ps) 

386 return F 

387 

388 

389def _Psum_(*ps, **name_f2product_nonfinites_RESIDUAL): 

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

391 ''' 

392 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL) 

393 

394 

395def _residue(other): 

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

397 ''' 

398 try: 

399 r = other.residual 

400 except AttributeError: 

401 r = None # float, int, other 

402 return r 

403 

404 

405def _s_r2(s, r): 

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

407 ''' 

408 if _isfinite(s): 

409 if r: 

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

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

412 else: 

413 r = INT0 

414 else: 

415 r = _NONFINITEr 

416 return s, r 

417 

418 

419def _strcomplex(s, *args): 

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

421 ''' 

422 c = typename(_strcomplex)[4:] 

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

424 t = unstr(pow, *args) 

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

426 

427 

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

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

430 ''' 

431 p = typename(_stresidual)[3:] 

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

433 for n, v in itemsorted(mod_ratio): 

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

435 t = _COMMASPACE_(t, p) 

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

437 

438 

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

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

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

442 ''' 

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

444 

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

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

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

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

449 s = a + b 

450 if _isfinite(s): 

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

452 r = (b - s) + a 

453 else: 

454 r = (a - s) + b 

455 elif _isfine(s): 

456 r = _NONFINITEr 

457 else: # non-finite and not OK 

458 t = unstr(_2sum, a, b) 

459 raise _nfError(s, t) 

460 return s, r 

461 

462 

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

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

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

466 ''' 

467 if kwds: 

468 threshold = _xkwds_get1(kwds, RESIDUAL=threshold) 

469 try: 

470 return _2finite(threshold) # PYCHOK None 

471 except Exception as x: 

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

473 

474 

475def _2tuple2(other): 

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

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

478 ''' 

479 if _isFsum_2Tuple(other): 

480 s, r = other._fint2 

481 if r: 

482 s, r = other._nfprs2 

483 if r: # PYCHOK no cover 

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

485 else: 

486 r = 0 

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

488 if isint(s, both=True): 

489 s = int(s) 

490 return s, r 

491 

492 

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

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

495 

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

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

498 intermediate, I{running} summuation. 

499 

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

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

502 

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

504 determined globally by function L{nonfiniterrors<fsums.nonfiniterrors>} or 

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

506 overruling the global setting. For backward compatibility, I{non-finites} 

507 raise exceptions by default. 

508 

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

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

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

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

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

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

515 

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

517 multiplication. 

518 

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

520 C{PYGEODESY_FSUM_NONFINITES} and C{PYGEODESY_FSUM_RESIDUAL}. 

521 ''' 

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

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

524 _n = 0 

525# _ps = [] # partial sums 

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

527 _RESIDUAL = _threshold(_RESIDUAL_0_0) 

528 

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

530 '''New L{Fsum}. 

531 

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

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

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

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

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

537 L{Fsum}. 

538 

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

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

541 ''' 

542 if name_f2product_nonfinites_RESIDUAL: 

543 self._optionals(**name_f2product_nonfinites_RESIDUAL) 

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

545 if xs: 

546 self._facc_args(xs, up=False) 

547 

548 def __abs__(self): 

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

550 ''' 

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

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

553 

554 def __add__(self, other): 

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

556 

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

558 

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

560 

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

562 ''' 

563 f = self._copyd(self.__add__) 

564 return f._fadd(other) 

565 

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

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

568 ''' 

569 s, r = self._nfprs2 

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

571 

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

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

574 ''' 

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

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

577 return self 

578 

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

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

581 

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

583 

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

585 ''' 

586 return self.ceil 

587 

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

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

590 

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

592 

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

594 ''' 

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

596 return _signOf(s, 0) 

597 

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

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

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

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

602 

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

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

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

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

607 

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

609 B{C{RESIDUAL}}. 

610 

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

612 ''' 

613 f = self._copyd(self.__divmod__) 

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

615 

616 def __eq__(self, other): 

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

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

619 ''' 

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

621 

622 def __float__(self): 

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

624 

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

626 ''' 

627 return float(self._fprs) 

628 

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

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

631 

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

633 

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

635 ''' 

636 return self.floor 

637 

638 def __floordiv__(self, other): 

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

640 

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

642 

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

644 

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

646 ''' 

647 f = self._copyd(self.__floordiv__) 

648 return f._floordiv(other, _floordiv_op_) 

649 

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

651# '''Not implemented.''' 

652# return _NotImplemented(self, *other) 

653 

654 def __ge__(self, other): 

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

656 ''' 

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

658 

659 def __gt__(self, other): 

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

661 ''' 

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

663 

664 def __hash__(self): # PYCHOK no cover 

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

666 ''' 

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

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

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

670 

671 def __iadd__(self, other): 

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

673 

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

675 an iterable of several of the former. 

676 

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

678 

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

680 C{scalar} nor L{Fsum}. 

681 

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

683 ''' 

684 try: 

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

686 except TypeError: 

687 pass 

688 _xiterable(other) 

689 return self._facc(other) 

690 

691 def __ifloordiv__(self, other): 

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

693 

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

695 

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

697 

698 @raise ResidualError: Non-zero, significant residual 

699 in B{C{other}}. 

700 

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

702 

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

704 

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

706 

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

708 ''' 

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

710 

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

712 '''Not implemented.''' 

713 return _NotImplemented(self, other) 

714 

715 def __imod__(self, other): 

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

717 

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

719 

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

721 

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

723 ''' 

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

725 

726 def __imul__(self, other): 

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

728 

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

730 

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

732 

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

734 

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

736 

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

738 ''' 

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

740 

741 def __int__(self): 

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

743 

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

745 and L{Fsum.floor}. 

746 ''' 

747 i, _ = self._fint2 

748 return i 

749 

750 def __invert__(self): # PYCHOK no cover 

751 '''Not implemented.''' 

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

753 return _NotImplemented(self) 

754 

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

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

757 

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

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

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

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

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

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

764 

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

766 

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

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

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

770 

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

772 

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

774 is non-zero and significant and either 

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

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

777 C{None}. 

778 

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

780 invocation failed. 

781 

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

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

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

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

786 is given as C{0}. 

787 

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

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

790 ''' 

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

792 

793 def __isub__(self, other): 

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

795 

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

797 an iterable of several of the former. 

798 

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

800 

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

802 

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

804 ''' 

805 try: 

806 return self._fsub(other, _isub_op_) 

807 except TypeError: 

808 pass 

809 _xiterable(other) 

810 return self._facc_neg(other) 

811 

812 def __iter__(self): 

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

814 ''' 

815 return iter(self.partials) 

816 

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

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

819 

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

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

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

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

824 

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

826 

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

828 

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

830 B{C{RESIDUAL}}. 

831 

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

833 

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

835 

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

837 

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

839 ''' 

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

841 

842 def __le__(self, other): 

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

844 ''' 

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

846 

847 def __len__(self): 

848 '''Return the number of (non-zero) values accumulated (C{int}). 

849 ''' 

850 return self._n 

851 

852 def __lt__(self, other): 

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

854 ''' 

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

856 

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

858 '''Not implemented.''' 

859 return _NotImplemented(self, other) 

860 

861 def __mod__(self, other): 

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

863 

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

865 ''' 

866 f = self._copyd(self.__mod__) 

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

868 

869 def __mul__(self, other): 

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

871 

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

873 ''' 

874 f = self._copyd(self.__mul__) 

875 return f._fmul(other, _mul_op_) 

876 

877 def __ne__(self, other): 

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

879 ''' 

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

881 

882 def __neg__(self): 

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

884 ''' 

885 f = self._copyd(self.__neg__) 

886 return f._fset(self._neg) 

887 

888 def __pos__(self): 

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

890 ''' 

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

892 

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

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

895 

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

897 ''' 

898 f = self._copyd(self.__pow__) 

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

900 

901 def __radd__(self, other): 

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

903 

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

905 ''' 

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

907 return f._fadd(self) 

908 

909 def __rdivmod__(self, other): 

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

911 C{(quotient, remainder)}. 

912 

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

914 ''' 

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

916 return f._fdivmod2(self, _divmod_op_) 

917 

918# turned off, called by _deepcopy and _copy 

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

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

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

922# ''' 

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

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

925 

926# def __repr__(self): 

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

928# ''' 

929# return self.toRepr(lenc=True) 

930 

931 def __rfloordiv__(self, other): 

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

933 

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

935 ''' 

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

937 return f._floordiv(self, _floordiv_op_) 

938 

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

940 '''Not implemented.''' 

941 return _NotImplemented(self, other) 

942 

943 def __rmod__(self, other): 

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

945 

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

947 ''' 

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

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

950 

951 def __rmul__(self, other): 

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

953 

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

955 ''' 

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

957 return f._fmul(self, _mul_op_) 

958 

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

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

961 

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

963 ''' 

964 f = self._copyd(self.__round__) 

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

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

967 

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

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

970 

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

972 ''' 

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

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

975 

976 def __rsub__(self, other): 

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

978 

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

980 ''' 

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

982 return f._fsub(self, _sub_op_) 

983 

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

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

986 

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

988 ''' 

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

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

991 

992# def __sizeof__(self): 

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

994# ''' 

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

996 

997 def __str__(self): 

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

999 ''' 

1000 return self.toStr(lenc=True) 

1001 

1002 def __sub__(self, other): 

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

1004 

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

1006 

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

1008 

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

1010 ''' 

1011 f = self._copyd(self.__sub__) 

1012 return f._fsub(other, _sub_op_) 

1013 

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

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

1016 

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

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

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

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

1021 

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

1023 

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

1025 B{C{RESIDUAL}}. 

1026 

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

1028 ''' 

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

1030 

1031 __trunc__ = __int__ 

1032 

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

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

1035 __div__ = __truediv__ 

1036 __idiv__ = __itruediv__ 

1037 __long__ = __int__ 

1038 __nonzero__ = __bool__ 

1039 __rdiv__ = __rtruediv__ 

1040 

1041 def as_integer_ratio(self): 

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

1043 

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

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

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

1047 instance is. 

1048 

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

1050 Python 2.7+. 

1051 ''' 

1052 n, r = self._fint2 

1053 if r: 

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

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

1056 else: # PYCHOK no cover 

1057 d = 1 

1058 return n, d 

1059 

1060 @property_RO 

1061 def as_iscalar(self): 

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

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

1064 ''' 

1065 s, r = self._nfprs2 

1066 return self if r else s 

1067 

1068 @property_RO 

1069 def ceil(self): 

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

1071 C{float} in Python 2-). 

1072 

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

1074 

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

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

1077 ''' 

1078 s, r = self._fprs2 

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

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

1081 c += 1 

1082 return c # _ceil(self._n_d) 

1083 

1084 cmp = __cmp__ 

1085 

1086 def _cmp_0(self, other, op): 

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

1088 ''' 

1089 if _isFsum_2Tuple(other): 

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

1091 elif self._scalar(other, op): 

1092 s = self._ps_1sum(other) 

1093 else: 

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

1095 return s 

1096 

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

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

1099 

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

1101 

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

1103 ''' 

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

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

1106 if f._ps is self._ps: 

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

1108 if not deep: 

1109 f._n = 1 

1110 # assert f._f2product == self._f2product 

1111 # assert f._Fsum is f 

1112 # assert f._isfine is self._isfine 

1113 # assert f._RESIDUAL is self._RESIDUAL 

1114 return f 

1115 

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

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

1118 ''' 

1119 n = name or typename(which) 

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

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

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

1123 # assert f._n == self._n 

1124 # assert f._f2product == self._f2product 

1125 # assert f._Fsum is f 

1126 # assert f._isfine is self._isfine 

1127 # assert f._RESIDUAL is self._RESIDUAL 

1128 return f 

1129 

1130 divmod = __divmod__ 

1131 

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

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

1134 ''' 

1135 # self.as_iscalar causes RecursionError for ._fprs2 errors 

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

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

1138 

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

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

1141 ''' 

1142 E, t = _xError2(X) 

1143 if mod: 

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

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

1146 

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

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

1149 ''' 

1150 E, t = _xError2(X) 

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

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

1153 

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

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

1156 ''' 

1157 if xs: 

1158 kwds = self._isfine 

1159 if _X_x_origin: 

1160 kwds = _xkwds(_X_x_origin, **kwds) 

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

1162 ps = self._ps 

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

1164# if len(ps) > 16: 

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

1166 return self 

1167 

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

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

1170 arguments in the caller of this method. 

1171 ''' 

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

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

1174 

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

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

1177 ''' 

1178 if n > 0: 

1179 _f = Fsum(**kwds) 

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

1181 return self 

1182 

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

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

1185 ''' 

1186 def _N(X): 

1187 return X._ps_neg 

1188 

1189 def _n(x): 

1190 return -float(x) 

1191 

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

1193 

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

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

1196 ''' 

1197 def _Pow4(p): 

1198 r = 0 

1199 if _isFsum_2Tuple(p): 

1200 s, r = p._fprs2 

1201 if r: 

1202 m = Fsum._pow 

1203 else: # scalar 

1204 return _Pow4(s) 

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

1206 p = s = int(p) 

1207 m = Fsum._pow_int 

1208 else: 

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

1210 m = Fsum._pow_scalar 

1211 return m, p, s, r 

1212 

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

1214 if p: # and xs: 

1215 op = typename(which) 

1216 _FsT = _Fsum_2Tuple_types 

1217 _pow = self._pow_2_3 

1218 

1219 def _P(X): 

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

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

1222 

1223 def _p(x): 

1224 x = float(x) 

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

1226 if f and r: 

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

1228 return f 

1229 

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

1231 else: 

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

1233 return f 

1234 

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

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

1237 ''' 

1238 if xs: 

1239 ps = self._ps 

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

1241 return self 

1242 

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

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

1245 ''' 

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

1247 

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

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

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

1251# ''' 

1252# ps = self._ps 

1253# while len(ps) > 1: 

1254# p = ps.pop() 

1255# if p: 

1256# n = self._n 

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

1258# self._n = n 

1259# break 

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

1261 

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

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

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

1265 ''' 

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

1267 **origin_which)) # PYCHOK yield 

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

1269 

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

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

1272 

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

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

1275 

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

1277 

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

1279 

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

1281 

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

1283 ''' 

1284 if _isFsum_2Tuple(xs): 

1285 self._facc_scalar(xs._ps) 

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

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

1288 self._facc_scalar_(x) 

1289 elif xs: # _xiterable(xs) 

1290 self._facc(xs) 

1291 return self 

1292 

1293 def fadd_(self, *xs): 

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

1295 

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

1297 or L{Fsum2Tuple}), all positional. 

1298 

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

1300 ''' 

1301 return self._facc_args(xs) 

1302 

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

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

1305 ''' 

1306 if _isFsum_2Tuple(other): 

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

1308 elif self._scalar(other, op): 

1309 self._facc_scalar_(other, **up) 

1310 return self 

1311 

1312 fcopy = copy # for backward compatibility 

1313 fdiv = __itruediv__ 

1314 fdivmod = __divmod__ 

1315 

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

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

1318 ''' 

1319 # result mostly follows CPython function U{float_divmod 

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

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

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

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

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

1325 

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

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

1328 self += other 

1329 q -= 1 

1330# t = self.signOf() 

1331# if t and t != s: 

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

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

1334 

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

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

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

1338 enumerate if B{incx} else _enumereverse}. 

1339 ''' 

1340 # assert _xiterablen(cs) 

1341 try: 

1342 n = len(cs) 

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

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

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

1346 H._mul_scalar 

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

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

1349 H._fadd(c, up=False) 

1350 else: # x == 0 

1351 H = cs[0] if n else 0 

1352 return self._fadd(H) 

1353 except Exception as X: 

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

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

1356 

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

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

1359 ''' 

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

1361 return other 

1362 E = _NonfiniteError(other) 

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

1364 

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

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

1367 

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

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

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

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

1372 

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

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

1375 

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

1377 B{C{RESIDUAL}}. 

1378 

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

1380 ''' 

1381 i, r = self._fint2 

1382 if r: 

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

1384 if R: 

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

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

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

1388 

1389 def fint2(self, **name): 

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

1391 I{integer} residual. 

1392 

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

1394 

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

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

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

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

1399 ''' 

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

1401 

1402 @Property 

1403 def _fint2(self): # see ._fset 

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

1405 ''' 

1406 s, r = self._nfprs2 

1407 if _isfinite(s): 

1408 i = int(s) 

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

1410 float(s - i)) or INT0 

1411 else: # INF, NAN, NINF 

1412 i = float(s) 

1413# r = _NONFINITEr 

1414 return i, r # Fsum2Tuple? 

1415 

1416 @_fint2.setter_ # PYCHOK setter_UNDERscore! 

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

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

1419 ''' 

1420 if _isfinite(s): 

1421 i = int(s) 

1422 r = (s - i) or INT0 

1423 else: # INF, NAN, NINF 

1424 i = float(s) 

1425 r = _NONFINITEr 

1426 return i, r # like _fint2.getter 

1427 

1428 @deprecated_property_RO 

1429 def float_int(self): # PYCHOK no cover 

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

1431 return self.int_float() # raiser=False 

1432 

1433 @property_RO 

1434 def floor(self): 

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

1436 C{float} in Python 2-). 

1437 

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

1439 

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

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

1442 ''' 

1443 s, r = self._fprs2 

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

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

1446 f -= 1 

1447 return f # _floor(self._n_d) 

1448 

1449# ffloordiv = __ifloordiv__ # for naming consistency? 

1450# floordiv = __floordiv__ # for naming consistency? 

1451 

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

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

1454 ''' 

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

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

1457 

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

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

1460 

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

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

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

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

1465 the L{nonfiniterrors} default (C{bool}). 

1466 ''' 

1467 f = self._fma(other1, other2, **nonfinites) 

1468 return self._fset(f) 

1469 

1470 def _fma(self, other1, other2, **nonfinites): # in .elliptic 

1471 '''(INTERNAL) Return C{self * B{other1} + B{other2}}. 

1472 ''' 

1473 op = typename(self.fma) 

1474 _fs = self._ps_other 

1475 try: 

1476 s, r = self._fprs2 

1477 if r: 

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

1479 f += other2 

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

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

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

1483 f = Fsum(fs, name=op, **nonfinites) 

1484 else: 

1485 f = _fma(s, other1, other2) 

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

1487 except TypeError as X: 

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

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

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

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

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

1493 return f 

1494 

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

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

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

1498 

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

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

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

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

1503 the L{nonfiniterrors} default (C{bool}). 

1504 

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

1506 start=self)}. 

1507 ''' 

1508 if xys: 

1509 n = len(xys) 

1510 if n < 2 or isodd(n): 

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

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

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

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

1515 self._fset(f) 

1516 return self 

1517 

1518 fmul = __imul__ 

1519 

1520 def _fmul(self, other, op): 

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

1522 ''' 

1523 if _isFsum_2Tuple(other): 

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

1525 f = self._mul_Fsum(other, op) 

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

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

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

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

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

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

1532 else: 

1533 s = self._scalar(other, op) 

1534 f = self._mul_scalar(s, op) 

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

1536 

1537 @deprecated_method 

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

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

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

1541 

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

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

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

1545 

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

1547 positional. 

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

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

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

1551 

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

1553 

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

1555 ''' 

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

1557 

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

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

1560 ''' 

1561 n = typename(where) 

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

1563 if others and f: 

1564 if f.f2product(): 

1565 def _pfs(f, ps): 

1566 return _2products(f, _2split3s(ps)) 

1567 else: 

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

1569 return (f * p for p in ps) 

1570 

1571 op, ps = n, f._ps 

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

1573 for other in others: # to pinpoint errors 

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

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

1576 f._update() 

1577 except TypeError as X: 

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

1579 except (OverflowError, ValueError) as X: 

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

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

1582 f._fset(r) 

1583 return f 

1584 

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

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

1587 

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

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

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

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

1592 

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

1594 

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

1596 B{C{RESIDUAL}}. 

1597 

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

1599 ''' 

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

1601 

1602 fpow = __ipow__ 

1603 

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

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

1606 ''' 

1607 if mod: 

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

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

1610 elif self.is_integer(): 

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

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

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

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

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

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

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

1618 else: # pow(self, other) 

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

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

1621 

1622 def f2product(self, *two): 

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

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

1625 

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

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

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

1629 

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

1631 

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

1633 

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

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

1636 ''' 

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

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

1639 self._optionals(f2product=two[0]) 

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

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

1642 return t 

1643 

1644 @Property 

1645 def _fprs(self): 

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

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

1648 

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

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

1651 ''' 

1652 s, _ = self._fprs2 

1653 return s # ._fprs2.fsum 

1654 

1655 @_fprs.setter_ # PYCHOK setter_UNDERscore! 

1656 def _fprs(self, s): 

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

1658 ''' 

1659 return s 

1660 

1661 @Property 

1662 def _fprs2(self): 

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

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

1665 ''' 

1666 ps = self._ps 

1667 n = len(ps) 

1668 try: 

1669 if n > 2: 

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

1671 if not _isfinite(s): 

1672 ps[:] = s, # collapse ps 

1673 return Fsum2Tuple(s, _NONFINITEr) 

1674 n = len(ps) 

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

1676 if n > 2: 

1677 r = self._ps_1sum(s) 

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

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

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

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

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

1683 s = ps[0] 

1684 r = INT0 if _isfinite(s) else _NONFINITEr 

1685 else: # len(ps) == 0 

1686 s = _0_0 

1687 r = INT0 if _isfinite(s) else _NONFINITEr 

1688 ps[:] = s, 

1689 except (OverflowError, ValueError) as X: 

1690 op = _fset_op_ # INF, NAN, NINF 

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

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

1693 r = _NONFINITEr 

1694 # assert self._ps is ps 

1695 return Fsum2Tuple(s, r) 

1696 

1697 @_fprs2.setter_ # PYCHOK setter_UNDERscore! 

1698 def _fprs2(self, s_r): 

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

1700 ''' 

1701 return Fsum2Tuple(s_r) 

1702 

1703 def fset_(self, *xs): 

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

1705 

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

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

1708 

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

1710 

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

1712 ''' 

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

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

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

1716 

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

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

1719 ''' 

1720 if other is self: 

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

1722 elif _isFsum_2Tuple(other): 

1723 if op: # and not self.nonfinitesOK: 

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

1725 self._ps[:] = other._ps 

1726 self._n = n or other._n 

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

1728 Fsum._fint2._update_from(self, other) 

1729 Fsum._fprs ._update_from(self, other) 

1730 Fsum._fprs2._update_from(self, other) 

1731 elif isscalar(other): 

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

1733 self._ps[:] = s, 

1734 self._n = n or 1 

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

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

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

1738 self._fint2 = s 

1739 self._fprs = s 

1740 self._fprs2 = s, INT0 

1741 # assert self._fprs is s 

1742 else: 

1743 op = _xkwds_get1(op, op=_fset_op_) 

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

1745 return self 

1746 

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

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

1749 

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

1751 ''' 

1752 return self._facc_neg(xs) 

1753 

1754 def fsub_(self, *xs): 

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

1756 

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

1758 ''' 

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

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

1761 

1762 def _fsub(self, other, op): 

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

1764 ''' 

1765 if _isFsum_2Tuple(other): 

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

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

1768 elif other._ps: 

1769 self._facc_scalar(other._ps_neg) 

1770 elif self._scalar(other, op): 

1771 self._facc_scalar_(-other) 

1772 return self 

1773 

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

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

1776 precision running sum. 

1777 

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

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

1780 

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

1782 

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

1784 

1785 @note: Accumulation can continue after summation. 

1786 ''' 

1787 return self._facc(xs)._fprs 

1788 

1789 def fsum_(self, *xs): 

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

1791 precision running sum. 

1792 

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

1794 L{Fsum2Tuple}), all positional. 

1795 

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

1797 

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

1799 ''' 

1800 return self._facc_args(xs)._fprs 

1801 

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

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

1804 

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

1806 

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

1808 ''' 

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

1810 

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

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

1813 

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

1815 

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

1817 ''' 

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

1819 

1820 @property_RO 

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

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

1823 

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

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

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

1827 overridden with C{name_f2product_nonfinites_RESIDUAL} and 

1828 with any C{xs} accumulated. 

1829 ''' 

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

1831 nonfinites=self.nonfinites(), 

1832 RESIDUAL =self.RESIDUAL()) 

1833 if name_f2product_nonfinites_RESIDUAL: # overwrites 

1834 kwds.update(name_f2product_nonfinites_RESIDUAL) 

1835 f = Fsum(**kwds) 

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

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

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

1839 

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

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

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

1843 

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

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

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

1847 

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

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

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

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

1852 to be I{exact}. 

1853 

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

1855 ''' 

1856 t = self._facc(xs)._fprs2 

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

1858 

1859 def fsum2_(self, *xs): 

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

1861 precision running sum and the I{differential}. 

1862 

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

1864 L{Fsum2Tuple}), all positional. 

1865 

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

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

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

1869 

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

1871 ''' 

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

1873 

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

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

1876 ''' 

1877 p, q = self._fprs2 

1878 if xs: 

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

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

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

1882 r, _ = _s_r2(d, r) 

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

1884 else: 

1885 return p, _0_0 

1886 

1887 def fsumf_(self, *xs): 

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

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

1890 ''' 

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

1892 

1893 def Fsumf_(self, *xs): 

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

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

1896 ''' 

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

1898 

1899 def fsum2f_(self, *xs): 

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

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

1902 ''' 

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

1904 

1905# ftruediv = __itruediv__ # for naming consistency? 

1906 

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

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

1909 ''' 

1910 n = _1_0 

1911 if _isFsum_2Tuple(other): 

1912 if other is self or self == other: 

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

1914 d, r = other._fprs2 

1915 if r: 

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

1917 if R: 

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

1919 d, n = other.as_integer_ratio() 

1920 else: 

1921 d = self._scalar(other, op) 

1922 try: 

1923 s = n / d 

1924 except Exception as X: 

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

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

1927 return self._fset(f) 

1928 

1929 @property_RO 

1930 def imag(self): 

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

1932 

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

1934 ''' 

1935 return _0_0 

1936 

1937 def int_float(self, **raiser_RESIDUAL): 

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

1939 

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

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

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

1943 

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

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

1946 is zero or not significant. 

1947 

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

1949 B{C{RESIDUAL}}. 

1950 

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

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

1953 ''' 

1954 s, r = self._fint2 

1955 if r: 

1956 s, r = self._fprs2 

1957 if r: # PYCHOK no cover 

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

1959 if R: 

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

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

1962 s = float(s) 

1963 return s 

1964 

1965 def is_exact(self): 

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

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

1968 ''' 

1969 return self.residual is INT0 

1970 

1971 def is_finite(self): # in .constants 

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

1973 

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

1975 ''' 

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

1977 

1978 def is_integer(self): 

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

1980 

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

1982 ''' 

1983 s, r = self._fint2 

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

1985 

1986 def is_math_fma(self): 

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

1988 

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

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

1991 C{PyGeodesy} implementation. 

1992 ''' 

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

1994 

1995 def is_math_fsum(self): 

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

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

1998 

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

2000 otherwise. 

2001 ''' 

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

2003 

2004 def is_scalar(self, **raiser_RESIDUAL): 

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

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

2007 

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

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

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

2011 

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

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

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

2015 

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

2017 B{C{RESIDUAL}}. 

2018 

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

2020 L{Fsum.as_iscalar}. 

2021 ''' 

2022 s, r = self._fprs2 

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

2024 

2025 def _mul_Fsum(self, other, op): 

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

2027 ''' 

2028 # assert _isFsum_2Tuple(other) 

2029 if self._ps and other._ps: 

2030 try: 

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

2032 except Exception as X: 

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

2034 else: 

2035 f = _0_0 

2036 return f 

2037 

2038 def _mul_reduce(self, *others): 

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

2040 ''' 

2041 r = _1_0 

2042 for f in others: 

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

2044 return r 

2045 

2046 def _mul_scalar(self, factor, op): 

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

2048 ''' 

2049 # assert isscalar(factor) 

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

2051 f = self if factor == _1_0 else ( 

2052 self._neg if factor == _N_1_0 else 

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

2054 else: 

2055 f = _0_0 

2056 return f 

2057 

2058# @property_RO 

2059# def _n_d(self): 

2060# n, d = self.as_integer_ratio() 

2061# return n / d 

2062 

2063 @property_RO 

2064 def _neg(self): 

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

2066 ''' 

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

2068 

2069 @property_RO 

2070 def _nfprs2(self): 

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

2072 ''' 

2073 try: # to handle nonfiniterrors, etc. 

2074 t = self._fprs2 

2075 except (OverflowError, ValueError): 

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

2077 return t 

2078 

2079 def nonfinites(self, *OK): 

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

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

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

2083 

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

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

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

2087 

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

2089 

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

2091 

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

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

2094 L{nonfiniterrors} default. 

2095 ''' 

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

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

2098 self._optionals(nonfinites=OK[0]) 

2099 self._update() 

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

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

2102 _ks = _nonfinites_isfine_kwds 

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

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

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

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

2107 

2108 @property_RO 

2109 def nonfinitesOK(self): 

2110 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}). 

2111 ''' 

2112# nf = self.nonfinites() 

2113# if nf is None: 

2114# nf = not nonfiniterrors() 

2115 return _isOK_or_finite(INF, **self._isfine) 

2116 

2117 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None): 

2118 '''(INTERNAL) Handle a I{non-finite} exception. 

2119 ''' 

2120 if nonfinites is None: 

2121 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser) 

2122 if not nonfinites: 

2123 raise self._ErrorX(X, op, f) 

2124 return f 

2125 

2126 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL): 

2127 '''(INTERNAL) Re/set options from keyword arguments. 

2128 ''' 

2129 if f2product is not None: 

2130 self._f2product = bool(f2product) 

2131 if nonfinites is not None: 

2132 self._isfine = _nonfinites_isfine_kwds[bool(nonfinites)] 

2133 if name_RESIDUAL: # MUST be last 

2134 n, kwds = _name2__(**name_RESIDUAL) 

2135 if kwds: 

2136 R = Fsum._RESIDUAL 

2137 t = _threshold(R, **kwds) 

2138 if t != R: 

2139 self._RESIDUAL = t 

2140 if n: 

2141 self.name = n # self.rename(n) 

2142 

2143 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over 

2144 '''(INTERNAL) Return C{Fsum(1) / B{x}}. 

2145 ''' 

2146 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL) 

2147 

2148 @property_RO 

2149 def partials(self): 

2150 '''Get this instance' current, partial sums (C{tuple} of C{float}s). 

2151 ''' 

2152 return tuple(self._ps) 

2153 

2154 def pow(self, x, *mod, **raiser_RESIDUAL): 

2155 '''Return C{B{self}**B{x}} as L{Fsum}. 

2156 

2157 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2158 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument 

2159 C{pow(B{self}, B{other}, B{mod})} version. 

2160 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore 

2161 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar} 

2162 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

2163 

2164 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})} 

2165 result (L{Fsum}). 

2166 

2167 @raise ResidualError: Non-zero, significant residual or invalid 

2168 B{C{RESIDUAL}}. 

2169 

2170 @note: If B{C{mod}} is given and C{None}, the result will be an 

2171 C{integer} L{Fsum} provided this instance C{is_integer} 

2172 or set to C{integer} by an L{Fsum.fint} call. 

2173 

2174 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer} 

2175 and L{Fsum.root}. 

2176 ''' 

2177 f = self._copyd(self.pow) 

2178 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod) 

2179 

2180 def _pow(self, other, unused, op, **raiser_RESIDUAL): 

2181 '''Return C{B{self} ** B{other}}. 

2182 ''' 

2183 if _isFsum_2Tuple(other): 

2184 f = self._pow_Fsum(other, op, **raiser_RESIDUAL) 

2185 elif self._scalar(other, op): 

2186 x = self._finite(other, op=op) 

2187 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

2188 else: 

2189 f = self._pow_0_1(0, other) 

2190 return f 

2191 

2192 def _pow_0_1(self, x, other): 

2193 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}. 

2194 ''' 

2195 return self if x else (1 if isint(other) and self.is_integer() else _1_0) 

2196 

2197 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL): 

2198 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b}, 

2199 B{x}, int B{mod} or C{None})}, embellishing errors. 

2200 ''' 

2201 

2202 if mod: # b, x, mod all C{int}, unless C{mod} is C{None} 

2203 m = mod[0] 

2204 # assert _isFsum_2Tuple(b) 

2205 

2206 def _s(s, r): 

2207 R = self._raiser(r, s, **raiser_RESIDUAL) 

2208 if R: 

2209 raise self._ResidualError(op, other, r, mod=m, **R) 

2210 return s 

2211 

2212 b = _s(*(b._fprs2 if m is None else b._fint2)) 

2213 x = _s(*_2tuple2(x)) 

2214 

2215 try: 

2216 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3) 

2217 s = pow(b, x, *mod) 

2218 if iscomplex(s): 

2219 # neg**frac == complex in Python 3+, but ValueError in 2- 

2220 raise ValueError(_strcomplex(s, b, x, *mod)) 

2221 _ = _2finite(s, **self._isfine) # ignore float 

2222 return s 

2223 except Exception as X: 

2224 raise self._ErrorX(X, op, other, *mod) 

2225 

2226 def _pow_Fsum(self, other, op, **raiser_RESIDUAL): 

2227 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}. 

2228 ''' 

2229 # assert _isFsum_2Tuple(other) 

2230 x, r = other._fprs2 

2231 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL) 

2232 if f and r: 

2233 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL) 

2234 return f 

2235 

2236 def _pow_int(self, x, other, op, **raiser_RESIDUAL): 

2237 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}. 

2238 ''' 

2239 # assert isint(x) and x >= 0 

2240 ps = self._ps 

2241 if len(ps) > 1: 

2242 _mul_Fsum = Fsum._mul_Fsum 

2243 if x > 4: 

2244 p = self 

2245 f = self if (x & 1) else self._Fsum_as(_1_0) 

2246 m = x >> 1 # // 2 

2247 while m: 

2248 p = _mul_Fsum(p, p, op) # p **= 2 

2249 if (m & 1): 

2250 f = _mul_Fsum(f, p, op) # f *= p 

2251 m >>= 1 # //= 2 

2252 elif x > 1: # self**2, 3, or 4 

2253 f = _mul_Fsum(self, self, op) 

2254 if x > 2: # self**3 or 4 

2255 p = self if x < 4 else f 

2256 f = _mul_Fsum(f, p, op) 

2257 else: # self**1 or self**0 == 1 or _1_0 

2258 f = self._pow_0_1(x, other) 

2259 elif ps: # self._ps[0]**x 

2260 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL) 

2261 else: # PYCHOK no cover 

2262 # 0**pos_int == 0, but 0**0 == 1 

2263 f = 0 if x else 1 

2264 return f 

2265 

2266 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL): 

2267 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}. 

2268 ''' 

2269 s, r = self._fprs2 

2270 if r: 

2271 # assert s != 0 

2272 if isint(x, both=True): # self**int 

2273 x = int(x) 

2274 y = abs(x) 

2275 if y > 1: 

2276 f = self._pow_int(y, other, op, **raiser_RESIDUAL) 

2277 if x > 0: # i.e. > 1 

2278 return f # Fsum or scalar 

2279 # assert x < 0 # i.e. < -1 

2280 if _isFsum(f): 

2281 s, r = f._fprs2 

2282 if r: 

2283 return self._1_Over(f, op, **raiser_RESIDUAL) 

2284 else: # scalar 

2285 s = f 

2286 # use s**(-1) to get the CPython 

2287 # float_pow error iff s is zero 

2288 x = -1 

2289 elif x < 0: # self**(-1) 

2290 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self 

2291 else: # self**1 or self**0 

2292 return self._pow_0_1(x, other) # self, 1 or 1.0 

2293 else: # self**fractional 

2294 R = self._raiser(r, s, **raiser_RESIDUAL) 

2295 if R: 

2296 raise self._ResidualError(op, other, r, **R) 

2297 n, d = self.as_integer_ratio() 

2298 if abs(n) > abs(d): 

2299 n, d, x = d, n, (-x) 

2300 s = n / d 

2301 # assert isscalar(s) and isscalar(x) 

2302 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL) 

2303 

2304 def _ps_acc(self, ps, xs, up=True, **unused): # in .geoids._Dotf and ._Hornerf 

2305 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}. 

2306 ''' 

2307 n = 0 

2308 _2s = _2sum 

2309 _fi = self._isfine 

2310 for x in (tuple(xs) if xs is ps else xs): 

2311 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine) 

2312 if x: 

2313 i = 0 

2314 for p in ps: 

2315 x, p = _2s(x, p, **_fi) 

2316 if p: 

2317 ps[i] = p 

2318 i += 1 

2319 ps[i:] = (x,) if x else () 

2320 n += 1 

2321 if n: 

2322 self._n += n 

2323 # Fsum._ps_max = max(Fsum._ps_max, len(ps)) 

2324 if up: 

2325 self._update() 

2326# x = sum(ps) 

2327# if not _isOK_or_finite(x, **fi): 

2328# ps[:] = x, # collapse ps 

2329 return ps 

2330 

2331 def _ps_mul(self, op, *factors): 

2332 '''(INTERNAL) Multiply this instance' C{partials} with 

2333 each scalar C{factor} and accumulate into an C{Fsum}. 

2334 ''' 

2335 def _psfs(ps, fs, _isfine=_isfinite): 

2336 if len(ps) < len(fs): 

2337 ps, fs = fs, ps 

2338 if self._f2product: 

2339 fs, p = _2split3s(fs), fs 

2340 if len(ps) > 1 and fs is not p: 

2341 fs = tuple(fs) # several ps 

2342 _pfs = _2products 

2343 else: 

2344 def _pfs(p, fs): 

2345 return (p * f for f in fs) 

2346 

2347 for p in ps: 

2348 for x in _pfs(p, fs): 

2349 yield x if _isfine(x) else _nfError(x) 

2350 

2351 xs = _psfs(self._ps, factors, **self._isfine) 

2352 f = _Psum(self._ps_acc([], xs, up=False), name=op) 

2353 return f 

2354 

2355 @property_RO 

2356 def _ps_neg(self): 

2357 '''(INTERNAL) Yield the partials, I{negated}. 

2358 ''' 

2359 for p in self._ps: 

2360 yield -p 

2361 

2362 def _ps_other(self, op, other): 

2363 '''(INTERNAL) Yield C{other} as C{scalar}s. 

2364 ''' 

2365 if _isFsum_2Tuple(other): 

2366 for p in other._ps: 

2367 yield p 

2368 else: 

2369 yield self._scalar(other, op) 

2370 

2371 def _ps_1sum(self, *less): 

2372 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars. 

2373 ''' 

2374 return _fsum(_1primed(self._ps, *less)) 

2375 

2376 def _raiser(self, r, s, raiser=True, **RESIDUAL): 

2377 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold 

2378 I{and} is residual C{r} I{non-zero} or I{significant} (for a 

2379 negative respectively positive C{RESIDUAL} threshold)? 

2380 ''' 

2381 if r and raiser: 

2382 t = self._RESIDUAL 

2383 if RESIDUAL: 

2384 t = _threshold(t, **RESIDUAL) 

2385 if t < 0 or (s + r) != s: 

2386 q = (r / s) if s else s # == 0. 

2387 if fabs(q) > fabs(t): 

2388 return dict(ratio=q, R=t) 

2389 return {} 

2390 

2391 def _rcopyd(self, other, which): 

2392 '''(INTERNAL) Copy for I{reverse-dyadic} operators. 

2393 ''' 

2394 return other._copyd(which) if _isFsum(other) else \ 

2395 self._copyd(which)._fset(other) 

2396 

2397 rdiv = __rtruediv__ 

2398 

2399 @property_RO 

2400 def real(self): 

2401 '''Get the C{real} part of this instance (C{float}). 

2402 

2403 @see: Methods L{Fsum.__float__} and L{Fsum.fsum} 

2404 and properties L{Fsum.ceil}, L{Fsum.floor}, 

2405 L{Fsum.imag} and L{Fsum.residual}. 

2406 ''' 

2407 return float(self) 

2408 

2409 @property_RO 

2410 def residual(self): 

2411 '''Get this instance' residual or residue (C{float} or C{int}): 

2412 the C{sum(partials)} less the precision running sum C{fsum}. 

2413 

2414 @note: The C{residual is INT0} iff the precision running 

2415 C{fsum} is considered to be I{exact}. 

2416 

2417 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}. 

2418 ''' 

2419 return self._fprs2.residual 

2420 

2421 def RESIDUAL(self, *threshold): 

2422 '''Get and set this instance' I{ratio} for raising L{ResidualError}s, 

2423 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}. 

2424 

2425 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising 

2426 L{ResidualError}s in division and exponention, if 

2427 C{None}, restore the default set with env variable 

2428 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the 

2429 current setting. 

2430 

2431 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}. 

2432 

2433 @raise ResidualError: Invalid B{C{threshold}}. 

2434 

2435 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio} 

2436 C{residual / fsum} exceeds the given B{C{threshold}} and (2) 

2437 the C{residual} is non-zero and (3) is I{significant} vs the 

2438 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional 

2439 keyword argument C{raiser=False} is missing. Specify a 

2440 negative B{C{threshold}} for only non-zero C{residual} 

2441 testing without the I{significant} case. 

2442 ''' 

2443 r = self._RESIDUAL 

2444 if threshold: 

2445 t = threshold[0] 

2446 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ... 

2447 (_0_0 if t else _1_0) if isbool(t) else 

2448 _threshold(t)) # ... backward compatibility 

2449 return r 

2450 

2451 def _ResidualError(self, op, other, residual, **mod_R): 

2452 '''(INTERNAL) Non-zero B{C{residual}} etc. 

2453 ''' 

2454 def _p(mod=None, R=0, **unused): # ratio=0 

2455 return (_non_zero_ if R < 0 else _significant_) \ 

2456 if mod is None else _integer_ 

2457 

2458 t = _stresidual(_p(**mod_R), residual, **mod_R) 

2459 return self._Error(op, other, ResidualError, txt=t) 

2460 

2461 def root(self, root, **raiser_RESIDUAL): 

2462 '''Return C{B{self}**(1 / B{root})} as L{Fsum}. 

2463 

2464 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2465 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any 

2466 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar} 

2467 to override the current L{RESIDUAL<Fsum.RESIDUAL>}. 

2468 

2469 @return: The C{self ** (1 / B{root})} result (L{Fsum}). 

2470 

2471 @raise ResidualError: Non-zero, significant residual or invalid 

2472 B{C{RESIDUAL}}. 

2473 

2474 @see: Method L{Fsum.pow}. 

2475 ''' 

2476 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL) 

2477 f = self._copyd(self.root) 

2478 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x) 

2479 

2480 def _scalar(self, other, op, **txt): 

2481 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}. 

2482 ''' 

2483 if isscalar(other): 

2484 return other 

2485 raise self._Error(op, other, _TypeError, **txt) # _invalid_ 

2486 

2487 def signOf(self, res=True): 

2488 '''Determine the sign of this instance. 

2489 

2490 @kwarg res: If C{True}, consider the residual, 

2491 otherwise ignore the latter (C{bool}). 

2492 

2493 @return: The sign (C{int}, -1, 0 or +1). 

2494 ''' 

2495 s, r = self._nfprs2 

2496 r = (-r) if res else 0 

2497 return _signOf(s, r) 

2498 

2499 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature 

2500 '''Return this C{Fsum} instance as representation. 

2501 

2502 @kwarg lenc_prec_sep_fmt: Optional keyword arguments 

2503 for method L{Fsum.toStr}. 

2504 

2505 @return: This instance (C{repr}). 

2506 ''' 

2507 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt)) 

2508 

2509 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature 

2510 '''Return this C{Fsum} instance as string. 

2511 

2512 @kwarg lenc: If C{True}, include the current C{[len]} of this 

2513 L{Fsum} enclosed in I{[brackets]} (C{bool}). 

2514 @kwarg prec_sep_fmt: Optional keyword arguments for method 

2515 L{Fsum2Tuple.toStr}. 

2516 

2517 @return: This instance (C{str}). 

2518 ''' 

2519 p = self.classname 

2520 if lenc: 

2521 p = Fmt.SQUARE(p, len(self)) 

2522 n = _enquote(self.name, white=_UNDER_) 

2523 t = self._nfprs2.toStr(**prec_sep_fmt) 

2524 return NN(p, _SPACE_, n, t) 

2525 

2526 def _truediv(self, other, op, **raiser_RESIDUAL): 

2527 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}. 

2528 ''' 

2529 f = self._copyd(self.__truediv__) 

2530 return f._ftruediv(other, op, **raiser_RESIDUAL) 

2531 

2532 def _update(self, updated=True): # see ._fset 

2533 '''(INTERNAL) Zap all cached C{Property_RO} values. 

2534 ''' 

2535 if updated: 

2536 _pop = self.__dict__.pop 

2537 for p in _ROs: 

2538 _ = _pop(p, None) 

2539# Fsum._fint2._update(self) 

2540# Fsum._fprs ._update(self) 

2541# Fsum._fprs2._update(self) 

2542 return self # for .fset_ 

2543 

2544_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update 

2545 

2546_nonfinites_isfine_kwds = {True: dict(_isfine=_isOK), 

2547 False: dict(_isfine=_isfinite)} 

2548if _NONFINITES == _std_: # PYCHOK no cover 

2549 _ = nonfiniterrors(False) 

2550 

2551 

2552def _Float_Int(arg, **name_Error): 

2553 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit. 

2554 ''' 

2555 U = Int if isint(arg) else Float 

2556 return U(arg, **name_Error) 

2557 

2558 

2559class DivMod2Tuple(_NamedTuple): 

2560 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder 

2561 C{mod} results of a C{divmod} operation. 

2562 

2563 @note: Quotient C{div} an C{int} in Python 3+ but a C{float} 

2564 in Python 2-. Remainder C{mod} an L{Fsum} instance. 

2565 ''' 

2566 _Names_ = ('div', 'mod') 

2567 _Units_ = (_Float_Int, Fsum) 

2568 

2569 

2570class Fsum2Tuple(_NamedTuple): # in .fstats 

2571 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum} 

2572 and the C{residual}, the sum of the remaining partials. Each 

2573 item is C{float} or C{int}. 

2574 

2575 @note: If the C{residual is INT0}, the C{fsum} is considered 

2576 to be I{exact}, see method L{Fsum2Tuple.is_exact}. 

2577 ''' 

2578 _Names_ = ( typename(Fsum.fsum), Fsum.residual.name) 

2579 _Units_ = (_Float_Int, _Float_Int) 

2580 

2581 def __abs__(self): # in .fmath 

2582 return self._Fsum.__abs__() 

2583 

2584 def __bool__(self): # PYCHOK Python 3+ 

2585 return bool(self._Fsum) 

2586 

2587 def __eq__(self, other): 

2588 return self._other_op(other, self.__eq__) 

2589 

2590 def __float__(self): 

2591 return self._Fsum.__float__() 

2592 

2593 def __ge__(self, other): 

2594 return self._other_op(other, self.__ge__) 

2595 

2596 def __gt__(self, other): 

2597 return self._other_op(other, self.__gt__) 

2598 

2599 def __le__(self, other): 

2600 return self._other_op(other, self.__le__) 

2601 

2602 def __lt__(self, other): 

2603 return self._other_op(other, self.__lt__) 

2604 

2605 def __int__(self): 

2606 return self._Fsum.__int__() 

2607 

2608 def __ne__(self, other): 

2609 return self._other_op(other, self.__ne__) 

2610 

2611 def __neg__(self): 

2612 return self._Fsum.__neg__() 

2613 

2614 __nonzero__ = __bool__ # Python 2- 

2615 

2616 def __pos__(self): 

2617 return self._Fsum.__pos__() 

2618 

2619 def as_integer_ratio(self): 

2620 '''Return this instance as the ratio of 2 integers. 

2621 

2622 @see: Method L{Fsum.as_integer_ratio} for further details. 

2623 ''' 

2624 return self._Fsum.as_integer_ratio() 

2625 

2626 @property_RO 

2627 def _fint2(self): 

2628 return self._Fsum._fint2 

2629 

2630 @property_RO 

2631 def _fprs2(self): 

2632 return self._Fsum._fprs2 

2633 

2634 @Property_RO 

2635 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats 

2636 s, r = _s_r2(*self) 

2637 ps = (r, s) if r else (s,) 

2638 return _Psum(ps, name=self.name) 

2639 

2640 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL): 

2641 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}. 

2642 ''' 

2643 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL) 

2644 

2645 def is_exact(self): 

2646 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}). 

2647 ''' 

2648 return self._Fsum.is_exact() 

2649 

2650 def is_finite(self): # in .constants 

2651 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}). 

2652 

2653 @see: Function L{isfinite<pygeodesy.isfinite>}. 

2654 ''' 

2655 return self._Fsum.is_finite() 

2656 

2657 def is_integer(self): 

2658 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}). 

2659 ''' 

2660 return self._Fsum.is_integer() 

2661 

2662 def _mul_scalar(self, other, op): # for Fsum._fmul 

2663 return self._Fsum._mul_scalar(other, op) 

2664 

2665 @property_RO 

2666 def _n(self): 

2667 return self._Fsum._n 

2668 

2669 def _other_op(self, other, which): 

2670 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum) 

2671 return getattr(C, typename(which))(s, other) 

2672 

2673 @property_RO 

2674 def _ps(self): 

2675 return self._Fsum._ps 

2676 

2677 @property_RO 

2678 def _ps_neg(self): 

2679 return self._Fsum._ps_neg 

2680 

2681 def signOf(self, **res): 

2682 '''Like method L{Fsum.signOf}. 

2683 ''' 

2684 return self._Fsum.signOf(**res) 

2685 

2686 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature 

2687 '''Return this L{Fsum2Tuple} as string (C{str}). 

2688 

2689 @kwarg fmt: Optional C{float} format (C{letter}). 

2690 @kwarg prec_sep: Optional keyword arguments for function 

2691 L{fstr<streprs.fstr>}. 

2692 ''' 

2693 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep)) 

2694 

2695_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines 

2696 

2697 

2698class _Ksum(Fsum): 

2699 '''(INTERNAL) For C{.karney._sum3}, specifically and only. 

2700 ''' 

2701 _isfine = _nonfinites_isfine_kwds[True] 

2702 

2703 def __init__(self, s, t, *xs): 

2704 ps = [t, s] if t else [s] 

2705 self._ps = self._ps_acc(ps, xs, up=False) 

2706 

2707 @property_RO 

2708 def _s_t_n3(self): 

2709 s, t = self._fprs2 

2710 return s, t, self._n 

2711 

2712 

2713class ResidualError(_ValueError): 

2714 '''Error raised for a division, power or root operation of 

2715 an L{Fsum} instance with a C{residual} I{ratio} exceeding 

2716 the L{RESIDUAL<Fsum.RESIDUAL>} threshold. 

2717 

2718 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}. 

2719 ''' 

2720 pass 

2721 

2722 

2723try: 

2724 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+ 

2725 

2726 # make sure _fsum works as expected (XXX check 

2727 # float.__getformat__('float')[:4] == 'IEEE'?) 

2728 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover 

2729 del _fsum # nope, remove _fsum ... 

2730 raise ImportError() # ... use _fsum below 

2731 

2732 _sum = _fsum 

2733except ImportError: 

2734 _sum = sum 

2735 

2736 def _fsum(xs): # in .elliptic, .geoids 

2737 '''(INTERNAL) Precision summation, Python 2.5-. 

2738 ''' 

2739 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True) 

2740 return float(F._facc(xs, up=False)) 

2741 

2742 

2743def fsum(xs, nonfinites=None, **floats): 

2744 '''Precision floating point summation from Python's C{math.fsum}. 

2745 

2746 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2747 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if 

2748 C{False} I{non-finites} raise an Overflow-/ValueError or if 

2749 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}). 

2750 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use 

2751 keyword argument C{B{nonfinites}=False} instead. 

2752 

2753 @return: Precision C{fsum} (C{float}). 

2754 

2755 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow. 

2756 

2757 @raise TypeError: Invalid B{C{xs}} item. 

2758 

2759 @raise ValueError: Invalid or C{NAN} B{C{xs}} item. 

2760 

2761 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites}, 

2762 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}. 

2763 ''' 

2764 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0 

2765 

2766 

2767def fsum_(*xs, **nonfinites): 

2768 '''Precision floating point summation of all positional items. 

2769 

2770 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2771 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2772 

2773 @see: Function L{fsum<fsums.fsum>} for further details. 

2774 ''' 

2775 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1? 

2776 

2777 

2778def fsumf_(*xs): 

2779 '''Precision floating point summation of all positional items with I{non-finites} C{OK}. 

2780 

2781 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), 

2782 all positional. 

2783 

2784 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2785 ''' 

2786 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1? 

2787 

2788 

2789def fsum1(xs, **nonfinites): 

2790 '''Precision floating point summation, 1-primed. 

2791 

2792 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

2793 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2794 

2795 @see: Function L{fsum<fsums.fsum>} for further details. 

2796 ''' 

2797 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0 

2798 

2799 

2800def fsum1_(*xs, **nonfinites): 

2801 '''Precision floating point summation of all positional items, 1-primed. 

2802 

2803 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional. 

2804 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}). 

2805 

2806 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2807 ''' 

2808 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1? 

2809 

2810 

2811def fsum1f_(*xs): 

2812 '''Precision floating point summation of all positional items, 1-primed and 

2813 with I{non-finites} C{OK}. 

2814 

2815 @see: Function L{fsum_<fsums.fsum_>} for further details. 

2816 ''' 

2817 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0 

2818 

2819 

2820def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers. 

2821 _x_kwds = dict(_x= (_passarg if nfOK else _2finite), 

2822 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds 

2823 _x_kwds.update(kwds) 

2824 return _x_kwds 

2825 

2826 

2827def _X_ps(X): # default C{_X} handler 

2828 return X._ps # lambda X: X._ps 

2829 

2830 

2831def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc 

2832 origin=0, which=None, **_Cdot): 

2833 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s. 

2834 ''' 

2835 i, x = 0, xs 

2836 try: 

2837 for i, x in enumerate(_xiterable(xs)): 

2838 if _isFsum_2Tuple(x): 

2839 for p in _X(x): 

2840 yield p if _isfine(p) else _nfError(p) 

2841 else: 

2842 f = _x(x) 

2843 yield f if _isfine(f) else _nfError(f) 

2844 

2845 except (OverflowError, TypeError, ValueError) as X: 

2846 t = _xsError(X, xs, i + origin, x) 

2847 if which: # prefix invokation 

2848 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot) 

2849 t = _COMMASPACE_(w, t) 

2850 raise _xError(X, t, txt=None) 

2851 

2852 

2853def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0 

2854 '''(INTERNAL) Precision summation of C{xs} with conditions. 

2855 ''' 

2856 if floats: # for backward compatibility 

2857 nonfinites = _xkwds_get1(floats, floats=nonfinites) 

2858 elif nonfinites is None: 

2859 nonfinites = not nonfiniterrors() 

2860 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) # PYCHOK yield 

2861 return _fsum(_1primed(fs) if primed else fs) 

2862 

2863 

2864# delete all decorators, etc. 

2865del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \ 

2866 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \ 

2867 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _envPYGEODESY, _std_ 

2868 

2869if __name__ == _DMAIN_: 

2870 

2871 # usage: python3 -m pygeodesy.fsums 

2872 

2873 def _test(n): 

2874 # copied from Hettinger, see L{Fsum} reference 

2875 from pygeodesy import frandoms, printf 

2876 

2877# printf(typename(_sum), end=_COMMASPACE_) 

2878 printf(typename(_fsum), end=_COMMASPACE_) 

2879 printf(typename(_psum), end=_COMMASPACE_) 

2880 printf(len(Fsum.__dict__), end=_COMMASPACE_) 

2881# printf(len(globals()), end=_COMMASPACE_) 

2882 

2883 F = Fsum() 

2884 if F.is_math_fsum(): 

2885 for t in frandoms(n, seeded=True): 

2886 assert float(F.fset_(*t)) == _fsum(t) 

2887 printf(_DOT_, end=NN) 

2888 printf(NN) 

2889 

2890 _test(128) 

2891 

2892# **) MIT License 

2893# 

2894# Copyright (C) 2016-2026 -- mrJean1 at Gmail -- All Rights Reserved. 

2895# 

2896# Permission is hereby granted, free of charge, to any person obtaining a 

2897# copy of this software and associated documentation files (the "Software"), 

2898# to deal in the Software without restriction, including without limitation 

2899# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

2900# and/or sell copies of the Software, and to permit persons to whom the 

2901# Software is furnished to do so, subject to the following conditions: 

2902# 

2903# The above copyright notice and this permission notice shall be included 

2904# in all copies or substantial portions of the Software. 

2905# 

2906# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

2907# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

2908# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

2909# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

2910# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

2911# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

2912# OTHER DEALINGS IN THE SOFTWARE.