1

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

3

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

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

6 plus optionally, accurate I{TwoProduct} multiplication.

7

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

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

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

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

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

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

14 otherwise the C{PyGeodesy 24.09.09} release.

15

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

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

18

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

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

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

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

23 and L{Fsum.__itruediv__}.

24

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

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

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

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

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

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

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

32

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

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

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

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

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

38'''

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

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

41

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

43 _signOf, itemsorted, signOf, _xiterable

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

45 _1_0, _N_1_0, _isfinite, _pos_self, \

46 Float, Int

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

48 _ValueError, _xError, _xError2, _xkwds, \

49 _xkwds_get, _xkwds_get1, _xkwds_not, \

50 _xkwds_pop, _xsError

51 from pygeodesy.internals import _enquote, _envPYGEODESY, _passarg, typename

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

53 _not_finite_, _SPACE_, _std_, _UNDER_

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

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

56 _NotImplemented, _ALL_LAZY, _MODS

57 from pygeodesy.props import _allPropertiesOf_n, deprecated_method, \

58 deprecated_property_RO, Property, \

59 Property_RO, property_RO

60 from pygeodesy.streprs import Fmt, fstr, unstr

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

62

63 from math import fabs, isinf, isnan, \

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

65

66__all__ = _ALL_LAZY.fsums

67__version__ = '25.04.26'

68

69 from pygeodesy.interns import (

70 _PLUS_ as _add_op_, # in .auxilats.auxAngle

71 _DSLASH_ as _floordiv_op_,

72 _EQUAL_ as _fset_op_,

73 _RANGLE_ as _gt_op_,

74 _LANGLE_ as _lt_op_,

75 _PERCENT_ as _mod_op_,

76 _STAR_ as _mul_op_,

77 _NOTEQUAL_ as _ne_op_,

78 _DSTAR_ as _pow_op_,

79 _DASH_ as _sub_op_, # in .auxilats.auxAngle

80 _SLASH_ as _truediv_op_

81)

82_divmod_op_ = _floordiv_op_ + _mod_op_

83_F2PRODUCT = _envPYGEODESY('FSUM_F2PRODUCT')

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

85_integer_ = 'integer'

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

87_NONFINITEr = _0_0 # NOT INT0!

88_NONFINITES = _envPYGEODESY('FSUM_NONFINITES')

89_non_zero_ = 'non-zero'

90_RESIDUAL_0_0 = _envPYGEODESY('FSUM_RESIDUAL', _0_0)

91_significant_ = 'significant'

92_threshold_ = 'threshold'

93

94

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

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

97 '''

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

99 else _nfError(x))

100

101

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

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

104 '''

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

106 try:

107 f = float(x)

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

109 except Exception as X:

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

111

112

113 try: # MCCABE 26

114 from math import fma as _fma

115

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

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

118 # TwoProductFMA U{Algorithm 3.5

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

120 for y in ys:

121 f = x * y

122 yield f

123 if _isfinite(f):

124 yield _fma(x, y, -f)

125 for z in zs:

126 yield z

127

128# _2split3 = \

129 _2split3s = _passarg # in Fsum.is_math_fma

130

131 except ImportError: # PYCHOK DSPACE! Python 3.12-

132

133 if _F2PRODUCT and _F2PRODUCT != _std_:

134 # backward to PyGeodesy 24.09.09, with _fmaX

135 from pygeodesy.basics import _integer_ratio2

136

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

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

139 # the same accuracy, but ~14x slower

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

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

142 d *= db

143 n *= nb * dc

144 n += nc * d

145 d *= dc

146 try:

147 n, d = _n_d2(n, d)

148 r = float(n / d)

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

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

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

152 else:

153 _integer_ratio2 = None # redef, in Fsum.is_math_fma

154

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

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

157 # the same accuracy, but ~13x slower

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

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

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

161

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

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

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

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

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

167 if isnan(r):

168 def _x(x):

169 return not isnan(x)

170 else: # non-finite, non-NAN

171 _x = _isfinite

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

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

174 return r

175

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

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

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

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

180 _, a, b = _2split3(x)

181 for y, c, d in y3s:

182 y *= x

183 yield y

184 if _isfinite(y):

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

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

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

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

189 yield a * c - y

190 yield b * c

191 if d:

192 yield a * d

193 yield b * d

194 for z in zs:

195 yield z

196

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

198

199 def _2split3(x):

200 # Split U{Algorithm 3.2

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

202 a = c = x * _2FACTOR

203 a -= c - x

204 b = x - a

205 return x, a, b

206

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

208 return map(_2split3, xs)

209

210

211 def f2product(two=None):

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

213

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

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

216

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

218

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

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

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

222 equivalent, slower implementation when not available.

223 '''

224 t = Fsum._f2product

225 if two is not None:

226 Fsum._f2product = bool(two)

227 return t

228

229

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

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

232 '''

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

234

235

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

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

238 '''

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

240

241

242 def _halfeven(s, r, p):

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

244 '''

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

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

247 r *= 2

248 t = s + r

249 if r == (t - s):

250 s = t

251 return s

252

253

254 def _isFsum(x): # in .fmath

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

256 '''

257 return isinstance(x, Fsum)

258

259

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

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

262 '''

263 return isinstance(x, _Fsum_2Tuple_types)

264

265

266 def _isOK(unused):

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

268 '''

269 return True

270

271

272 def _isOK_or_finite(x, _isfine=_isfinite):

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

274 '''

275 # assert _isin(_isfine, _isOK, _isfinite)

276 return _isfine(x) # C{bool}

277

278

279 def _n_d2(n, d):

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

281 '''

282 try:

283 c = _gcd(n, d)

284 if c > 1:

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

286 except TypeError: # non-int float

287 pass

288 return n, d

289

290

291 def _nfError(x, *args):

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

293 '''

294 E = _NonfiniteError(x)

295 t = Fmt.PARENSPACED(_not_finite_, x)

296 if args: # in _fmaX, _2sum

297 return E(txt=t, *args)

298 raise E(t, txt=None)

299

300

301 def _NonfiniteError(x):

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

303 '''

304 return _OverflowError if isinf(x) else (

305 _ValueError if isnan(x) else _AssertionError)

306

307

308 def nonfiniterrors(raiser=None):

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

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

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

312

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

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

315 the setting unchanged.

316

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

318

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

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

321 '''

322 d = Fsum._isfine

323 if raiser is not None:

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

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

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

327

328

329 def _1primed(xs): # in .fmath

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

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

332 '''

333 yield _1_0

334 for x in xs:

335 yield x

336 yield _N_1_0

337

338

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

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

341 '''

342 # assert isinstance(ps, list)

343 i = len(ps) - 1

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

345 while i > 0:

346 i -= 1

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

348 if r: # sum(ps) became inexact

349 if s:

350 ps[i:] = r, s

351 if i > 0:

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

353 break # return s

354 s = r # PYCHOK no cover

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

356 i = 0 # collapse ps

357 if ps:

358 s += sum(ps)

359 ps[i:] = s,

360 return s

361

362

363 def _Psum(ps, **name_f2product_nonfinites_RESIDUAL):

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

365 '''

366 F = Fsum(**name_f2product_nonfinites_RESIDUAL)

367 if ps:

368 F._ps[:] = ps

369 F._n = len(F._ps)

370 return F

371

372

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

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

375 '''

376 return _Psum(ps, **name_f2product_nonfinites_RESIDUAL)

377

378

379 def _residue(other):

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

381 '''

382 try:

383 r = other.residual

384 except AttributeError:

385 r = None # float, int, other

386 return r

387

388

389 def _s_r2(s, r):

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

391 '''

392 if _isfinite(s):

393 if r:

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

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

396 else:

397 r = INT0

398 else:

399 r = _NONFINITEr

400 return s, r

401

402

403 def _strcomplex(s, *args):

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

405 '''

406 c = typename(_strcomplex)[4:]

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

408 t = unstr(pow, *args)

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

410

411

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

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

414 '''

415 p = typename(_stresidual)[3:]

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

417 for n, v in itemsorted(mod_ratio):

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

419 t = _COMMASPACE_(t, p)

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

421

422

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

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

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

426 '''

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

428

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

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

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

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

433 s = a + b

434 if _isfinite(s):

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

436 r = (b - s) + a

437 else:

438 r = (a - s) + b

439 elif _isfine(s):

440 r = _NONFINITEr

441 else: # non-finite and not OK

442 t = unstr(_2sum, a, b)

443 raise _nfError(s, t)

444 return s, r

445

446

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

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

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

450 '''

451 if kwds:

452 threshold = _xkwds_get1(kwds, RESIDUAL=threshold)

453 try:

454 return _2finite(threshold) # PYCHOK None

455 except Exception as x:

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

457

458

459 def _2tuple2(other):

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

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

462 '''

463 if _isFsum_2Tuple(other):

464 s, r = other._fint2

465 if r:

466 s, r = other._nfprs2

467 if r: # PYCHOK no cover

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

469 else:

470 r = 0

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

472 if isint(s, both=True):

473 s = int(s)

474 return s, r

475

476

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

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

479

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

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

482 intermediate, I{running} summuation.

483

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

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

486

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

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

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

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

491 exceptions by default.

492

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

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

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

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

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

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

499

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

501 multiplication.

502

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

504 C{PYGEODESY_FSUM_NONFINITES} and C{PYGEODESY_FSUM_RESIDUAL}.

505 '''

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

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

508 _n = 0

509# _ps = [] # partial sums

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

511 _RESIDUAL = _threshold(_RESIDUAL_0_0)

512

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

514 '''New L{Fsum}.

515

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

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

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

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

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

521 L{Fsum}.

522

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

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

525 '''

526 if name_f2product_nonfinites_RESIDUAL:

527 self._optionals(**name_f2product_nonfinites_RESIDUAL)

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

529 if xs:

530 self._facc_args(xs, up=False)

531

532 def __abs__(self):

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

534 '''

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

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

537

538 def __add__(self, other):

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

540

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

542

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

544

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

546 '''

547 f = self._copyd(self.__add__)

548 return f._fadd(other)

549

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

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

552 '''

553 s, r = self._nfprs2

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

555

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

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

558 '''

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

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

561 return self

562

563

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

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

566

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

568

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

570 '''

571 return self.ceil

572

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

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

575

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

577

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

579 '''

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

581 return _signOf(s, 0)

582

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

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

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

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

587

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

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

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

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

592

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

594 B{C{RESIDUAL}}.

595

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

597 '''

598 f = self._copyd(self.__divmod__)

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

600

601 def __eq__(self, other):

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

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

604 '''

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

606

607 def __float__(self):

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

609

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

611 '''

612 return float(self._fprs)

613

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

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

616

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

618

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

620 '''

621 return self.floor

622

623 def __floordiv__(self, other):

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

625

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

627

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

629

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

631 '''

632 f = self._copyd(self.__floordiv__)

633 return f._floordiv(other, _floordiv_op_)

634

635 def __ge__(self, other):

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

637 '''

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

639

640 def __gt__(self, other):

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

642 '''

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

644

645 def __hash__(self): # PYCHOK no cover

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

647 '''

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

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

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

651

652 def __iadd__(self, other):

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

654

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

656 an iterable of several of the former.

657

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

659

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

661 C{scalar} nor L{Fsum}.

662

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

664 '''

665 try:

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

667 except TypeError:

668 pass

669 _xiterable(other)

670 return self._facc(other)

671

672 def __ifloordiv__(self, other):

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

674

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

676

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

678

679 @raise ResidualError: Non-zero, significant residual

680 in B{C{other}}.

681

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

683

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

685

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

687

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

689 '''

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

691

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

693 '''Not implemented.'''

694 return _NotImplemented(self, other)

695

696 def __imod__(self, other):

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

698

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

700

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

702

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

704 '''

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

706

707 def __imul__(self, other):

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

709

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

711

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

713

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

715

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

717

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

719 '''

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

721

722 def __int__(self):

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

724

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

726 and L{Fsum.floor}.

727 '''

728 i, _ = self._fint2

729 return i

730

731 def __invert__(self): # PYCHOK no cover

732 '''Not implemented.'''

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

734 return _NotImplemented(self)

735

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

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

738

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

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

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

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

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

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

745

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

747

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

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

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

751

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

753

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

755 is non-zero and significant and either

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

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

758 C{None}.

759

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

761 invocation failed.

762

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

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

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

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

767 is given as C{0}.

768

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

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

771 '''

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

773

774 def __isub__(self, other):

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

776

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

778 an iterable of several of the former.

779

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

781

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

783

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

785 '''

786 try:

787 return self._fsub(other, _isub_op_)

788 except TypeError:

789 pass

790 _xiterable(other)

791 return self._facc_neg(other)

792

793 def __iter__(self):

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

795 '''

796 return iter(self.partials)

797

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

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

800

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

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

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

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

805

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

807

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

809

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

811 B{C{RESIDUAL}}.

812

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

814

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

816

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

818

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

820 '''

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

822

823 def __le__(self, other):

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

825 '''

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

827

828 def __len__(self):

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

830 '''

831 return self._n

832

833 def __lt__(self, other):

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

835 '''

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

837

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

839 '''Not implemented.'''

840 return _NotImplemented(self, other)

841

842 def __mod__(self, other):

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

844

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

846 '''

847 f = self._copyd(self.__mod__)

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

849

850 def __mul__(self, other):

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

852

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

854 '''

855 f = self._copyd(self.__mul__)

856 return f._fmul(other, _mul_op_)

857

858 def __ne__(self, other):

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

860 '''

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

862

863 def __neg__(self):

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

865 '''

866 f = self._copyd(self.__neg__)

867 return f._fset(self._neg)

868

869 def __pos__(self):

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

871 '''

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

873

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

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

876

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

878 '''

879 f = self._copyd(self.__pow__)

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

881

882 def __radd__(self, other):

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

884

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

886 '''

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

888 return f._fadd(self)

889

890 def __rdivmod__(self, other):

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

892 C{(quotient, remainder)}.

893

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

895 '''

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

897 return f._fdivmod2(self, _divmod_op_)

898

899# turned off, called by _deepcopy and _copy

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

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

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

903# '''

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

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

906

907# def __repr__(self):

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

909# '''

910# return self.toRepr(lenc=True)

911

912 def __rfloordiv__(self, other):

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

914

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

916 '''

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

918 return f._floordiv(self, _floordiv_op_)

919

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

921 '''Not implemented.'''

922 return _NotImplemented(self, other)

923

924 def __rmod__(self, other):

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

926

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

928 '''

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

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

931

932 def __rmul__(self, other):

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

934

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

936 '''

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

938 return f._fmul(self, _mul_op_)

939

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

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

942

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

944 '''

945 f = self._copyd(self.__round__)

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

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

948

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

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

951

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

953 '''

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

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

956

957 def __rsub__(self, other):

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

959

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

961 '''

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

963 return f._fsub(self, _sub_op_)

964

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

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

967

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

969 '''

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

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

972

973 def __str__(self):

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

975 '''

976 return self.toStr(lenc=True)

977

978 def __sub__(self, other):

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

980

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

982

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

984

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

986 '''

987 f = self._copyd(self.__sub__)

988 return f._fsub(other, _sub_op_)

989

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

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

992

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

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

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

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

997

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

999

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

1001 B{C{RESIDUAL}}.

1002

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

1004 '''

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

1006

1007 __trunc__ = __int__

1008

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

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

1011 __div__ = __truediv__

1012 __idiv__ = __itruediv__

1013 __long__ = __int__

1014 __nonzero__ = __bool__

1015 __rdiv__ = __rtruediv__

1016

1017 def as_integer_ratio(self):

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

1019

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

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

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

1023 instance is.

1024

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

1026 Python 2.7+.

1027 '''

1028 n, r = self._fint2

1029 if r:

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

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

1032 else: # PYCHOK no cover

1033 d = 1

1034 return n, d

1035

1036 @property_RO

1037 def as_iscalar(self):

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

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

1040 '''

1041 s, r = self._nfprs2

1042 return self if r else s

1043

1044 @property_RO

1045 def ceil(self):

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

1047 C{float} in Python 2-).

1048

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

1050

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

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

1053 '''

1054 s, r = self._fprs2

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

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

1057 c += 1

1058 return c # _ceil(self._n_d)

1059

1060 cmp = __cmp__

1061

1062 def _cmp_0(self, other, op):

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

1064 '''

1065 if _isFsum_2Tuple(other):

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

1067 elif self._scalar(other, op):

1068 s = self._ps_1sum(other)

1069 else:

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

1071 return s

1072

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

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

1075

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

1077

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

1079 '''

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

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

1082 if f._ps is self._ps:

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

1084 if not deep:

1085 f._n = 1

1086 # assert f._f2product == self._f2product

1087 # assert f._Fsum is f

1088 # assert f._isfine is self._isfine

1089 # assert f._RESIDUAL is self._RESIDUAL

1090 return f

1091

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

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

1094 '''

1095 n = name or typename(which)

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

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

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

1099 # assert f._n == self._n

1100 # assert f._f2product == self._f2product

1101 # assert f._Fsum is f

1102 # assert f._isfine is self._isfine

1103 # assert f._RESIDUAL is self._RESIDUAL

1104 return f

1105

1106 divmod = __divmod__

1107

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

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

1110 '''

1111 # self.as_iscalar causes RecursionError for ._fprs2 errors

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

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

1114

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

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

1117 '''

1118 E, t = _xError2(X)

1119 if mod:

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

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

1122

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

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

1125 '''

1126 E, t = _xError2(X)

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

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

1129

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

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

1132 '''

1133 if xs:

1134 kwds = self._isfine

1135 if _X_x_origin:

1136 kwds = _xkwds(_X_x_origin, **kwds)

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

1138 ps = self._ps

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

1140# if len(ps) > 16:

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

1142 return self

1143

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

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

1146 arguments in the caller of this method.

1147 '''

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

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

1150

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

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

1153 '''

1154 if n > 0:

1155 _f = Fsum(**kwds)

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

1157 return self

1158

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

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

1161 '''

1162 def _N(X):

1163 return X._ps_neg

1164

1165 def _n(x):

1166 return -float(x)

1167

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

1169

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

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

1172 '''

1173 def _Pow4(p):

1174 r = 0

1175 if _isFsum_2Tuple(p):

1176 s, r = p._fprs2

1177 if r:

1178 m = Fsum._pow

1179 else: # scalar

1180 return _Pow4(s)

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

1182 p = s = int(p)

1183 m = Fsum._pow_int

1184 else:

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

1186 m = Fsum._pow_scalar

1187 return m, p, s, r

1188

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

1190 if p: # and xs:

1191 op = typename(which)

1192 _FsT = _Fsum_2Tuple_types

1193 _pow = self._pow_2_3

1194

1195 def _P(X):

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

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

1198

1199 def _p(x):

1200 x = float(x)

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

1202 if f and r:

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

1204 return f

1205

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

1207 else:

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

1209 return f

1210

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

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

1213 '''

1214 if xs:

1215 ps = self._ps

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

1217 return self

1218

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

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

1221 '''

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

1223

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

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

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

1227 '''

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

1229 **origin_which)) # PYCHOK yield

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

1231

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

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

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

1235# '''

1236# ps = self._ps

1237# while len(ps) > 1:

1238# p = ps.pop()

1239# if p:

1240# n = self._n

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

1242# self._n = n

1243# break

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

1245

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

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

1248

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

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

1251

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

1253

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

1255

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

1257

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

1259 '''

1260 if _isFsum_2Tuple(xs):

1261 self._facc_scalar(xs._ps)

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

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

1264 self._facc_scalar_(x)

1265 elif xs: # _xiterable(xs)

1266 self._facc(xs)

1267 return self

1268

1269 def fadd_(self, *xs):

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

1271

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

1273 or L{Fsum2Tuple}), all positional.

1274

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

1276 '''

1277 return self._facc_args(xs)

1278

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

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

1281 '''

1282 if _isFsum_2Tuple(other):

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

1284 elif self._scalar(other, op):

1285 self._facc_scalar_(other, **up)

1286 return self

1287

1288 fcopy = copy # for backward compatibility

1289 fdiv = __itruediv__

1290 fdivmod = __divmod__

1291

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

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

1294 '''

1295 # result mostly follows CPython function U{float_divmod

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

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

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

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

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

1301

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

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

1304 self += other

1305 q -= 1

1306# t = self.signOf()

1307# if t and t != s:

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

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

1310

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

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

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

1314 enumerate if B{incx} else _enumereverse}.

1315 '''

1316 # assert _xiterablen(cs)

1317 try:

1318 n = len(cs)

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

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

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

1322 H._mul_scalar

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

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

1325 H._fadd(c, up=False)

1326 else: # x == 0

1327 H = cs[0] if n else 0

1328 self._fadd(H)

1329 except Exception as X:

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

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

1332 return self

1333

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

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

1336 '''

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

1338 return other

1339 E = _NonfiniteError(other)

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

1341

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

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

1344

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

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

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

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

1349

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

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

1352

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

1354 B{C{RESIDUAL}}.

1355

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

1357 '''

1358 i, r = self._fint2

1359 if r:

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

1361 if R:

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

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

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

1365

1366 def fint2(self, **name):

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

1368 I{integer} residual.

1369

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

1371

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

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

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

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

1376 '''

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

1378

1379 @Property

1380 def _fint2(self): # see ._fset

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

1382 '''

1383 s, r = self._nfprs2

1384 if _isfinite(s):

1385 i = int(s)

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

1387 float(s - i)) or INT0

1388 else: # INF, NAN, NINF

1389 i = float(s)

1390# r = _NONFINITEr

1391 return i, r # Fsum2Tuple?

1392

1393 @_fint2.setter_ # PYCHOK setter_UNDERscore!

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

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

1396 '''

1397 if _isfinite(s):

1398 i = int(s)

1399 r = (s - i) or INT0

1400 else: # INF, NAN, NINF

1401 i = float(s)

1402 r = _NONFINITEr

1403 return i, r # like _fint2.getter

1404

1405 @deprecated_property_RO

1406 def float_int(self): # PYCHOK no cover

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

1408 return self.int_float() # raiser=False

1409

1410 @property_RO

1411 def floor(self):

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

1413 C{float} in Python 2-).

1414

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

1416

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

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

1419 '''

1420 s, r = self._fprs2

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

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

1423 f -= 1

1424 return f # _floor(self._n_d)

1425

1426# ffloordiv = __ifloordiv__ # for naming consistency?

1427# floordiv = __floordiv__ # for naming consistency?

1428

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

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

1431 '''

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

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

1434

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

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

1437

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

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

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

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

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

1443 '''

1444 op = typename(self.fma)

1445 _fs = self._ps_other

1446 try:

1447 s, r = self._fprs2

1448 if r:

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

1450 f += other2

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

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

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

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

1455 else:

1456 f = _fma(s, other1, other2)

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

1458 except TypeError as X:

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

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

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

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

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

1464 return self._fset(f)

1465

1466 fmul = __imul__

1467

1468 def _fmul(self, other, op):

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

1470 '''

1471 if _isFsum_2Tuple(other):

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

1473 f = self._mul_Fsum(other, op)

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

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

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

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

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

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

1480 else:

1481 s = self._scalar(other, op)

1482 f = self._mul_scalar(s, op)

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

1484

1485 @deprecated_method

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

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

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

1489

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

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

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

1493

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

1495 positional.

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

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

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

1499

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

1501

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

1503 '''

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

1505

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

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

1508 '''

1509 n = typename(where)

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

1511 if others and f:

1512 if f.f2product():

1513 def _pfs(f, ps):

1514 return _2products(f, _2split3s(ps))

1515 else:

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

1517 return (f * p for p in ps)

1518

1519 op, ps = n, f._ps

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

1521 for other in others: # to pinpoint errors

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

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

1524 f._update()

1525 except TypeError as X:

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

1527 except (OverflowError, ValueError) as X:

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

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

1530 f._fset(r)

1531 return f

1532

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

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

1535

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

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

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

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

1540

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

1542

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

1544 B{C{RESIDUAL}}.

1545

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

1547 '''

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

1549

1550 fpow = __ipow__

1551

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

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

1554 '''

1555 if mod:

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

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

1558 elif self.is_integer():

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

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

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

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

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

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

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

1566 else: # pow(self, other)

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

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

1569

1570 def f2product(self, *two):

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

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

1573

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

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

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

1577

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

1579

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

1581

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

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

1584 '''

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

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

1587 if two[0] is not None:

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

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

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

1591 return t

1592

1593 @Property

1594 def _fprs(self):

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

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

1597

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

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

1600 '''

1601 s, _ = self._fprs2

1602 return s # ._fprs2.fsum

1603

1604 @_fprs.setter_ # PYCHOK setter_UNDERscore!

1605 def _fprs(self, s):

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

1607 '''

1608 return s

1609

1610 @Property

1611 def _fprs2(self):

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

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

1614 '''

1615 ps = self._ps

1616 n = len(ps)

1617 try:

1618 if n > 2:

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

1620 if not _isfinite(s):

1621 ps[:] = s, # collapse ps

1622 return Fsum2Tuple(s, _NONFINITEr)

1623 n = len(ps)

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

1625 if n > 2:

1626 r = self._ps_1sum(s)

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

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

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

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

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

1632 s = ps[0]

1633 r = INT0 if _isfinite(s) else _NONFINITEr

1634 else: # len(ps) == 0

1635 s = _0_0

1636 r = INT0 if _isfinite(s) else _NONFINITEr

1637 ps[:] = s,

1638 except (OverflowError, ValueError) as X:

1639 op = _fset_op_ # INF, NAN, NINF

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

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

1642 r = _NONFINITEr

1643 # assert self._ps is ps

1644 return Fsum2Tuple(s, r)

1645

1646 @_fprs2.setter_ # PYCHOK setter_UNDERscore!

1647 def _fprs2(self, s_r):

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

1649 '''

1650 return Fsum2Tuple(s_r)

1651

1652 def fset_(self, *xs):

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

1654

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

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

1657

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

1659

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

1661 '''

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

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

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

1665

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

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

1668 '''

1669 if other is self:

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

1671 elif _isFsum_2Tuple(other):

1672 if op: # and not self.nonfinitesOK:

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

1674 self._ps[:] = other._ps

1675 self._n = n or other._n

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

1677 Fsum._fint2._update_from(self, other)

1678 Fsum._fprs ._update_from(self, other)

1679 Fsum._fprs2._update_from(self, other)

1680 elif isscalar(other):

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

1682 self._ps[:] = s,

1683 self._n = n or 1

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

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

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

1687 self._fint2 = s

1688 self._fprs = s

1689 self._fprs2 = s, INT0

1690 # assert self._fprs is s

1691 else:

1692 op = _xkwds_get1(op, op=_fset_op_)

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

1694 return self

1695

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

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

1698

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

1700 '''

1701 return self._facc_neg(xs)

1702

1703 def fsub_(self, *xs):

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

1705

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

1707 '''

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

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

1710

1711 def _fsub(self, other, op):

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

1713 '''

1714 if _isFsum_2Tuple(other):

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

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

1717 elif other._ps:

1718 self._facc_scalar(other._ps_neg)

1719 elif self._scalar(other, op):

1720 self._facc_scalar_(-other)

1721 return self

1722

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

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

1725 precision running sum.

1726

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

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

1729

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

1731

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

1733

1734 @note: Accumulation can continue after summation.

1735 '''

1736 return self._facc(xs)._fprs

1737

1738 def fsum_(self, *xs):

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

1740 precision running sum.

1741

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

1743 L{Fsum2Tuple}), all positional.

1744

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

1746

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

1748 '''

1749 return self._facc_args(xs)._fprs

1750

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

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

1753

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

1755

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

1757 '''

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

1759

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

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

1762

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

1764

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

1766 '''

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

1768

1769 @property_RO

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

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

1772

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

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

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

1776 overridden with C{name_f2product_nonfinites_RESIDUAL} and

1777 with any C{xs} accumulated.

1778 '''

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

1780 nonfinites=self.nonfinites(),

1781 RESIDUAL =self.RESIDUAL())

1782 if name_f2product_nonfinites_RESIDUAL: # overwrites

1783 kwds.update(name_f2product_nonfinites_RESIDUAL)

1784 f = Fsum(**kwds)

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

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

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

1788

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

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

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

1792

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

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

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

1796

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

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

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

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

1801 to be I{exact}.

1802

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

1804 '''

1805 t = self._facc(xs)._fprs2

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

1807

1808 def fsum2_(self, *xs):

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

1810 precision running sum and the I{differential}.

1811

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

1813 L{Fsum2Tuple}), all positional.

1814

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

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

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

1818

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

1820 '''

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

1822

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

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

1825 '''

1826 p, q = self._fprs2

1827 if xs:

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

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

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

1831 r, _ = _s_r2(d, r)

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

1833 else:

1834 return p, _0_0

1835

1836 def fsumf_(self, *xs):

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

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

1839 '''

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

1841

1842 def Fsumf_(self, *xs):

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

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

1845 '''

1846 return self._facc_scalarf(xs, which=self.Fsumf_)._copyd(self.Fsumf_) # origin=1?

1847

1848 def fsum2f_(self, *xs):

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

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

1851 '''

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

1853

1854# ftruediv = __itruediv__ # for naming consistency?

1855

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

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

1858 '''

1859 n = _1_0

1860 if _isFsum_2Tuple(other):

1861 if other is self or self == other:

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

1863 d, r = other._fprs2

1864 if r:

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

1866 if R:

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

1868 d, n = other.as_integer_ratio()

1869 else:

1870 d = self._scalar(other, op)

1871 try:

1872 s = n / d

1873 except Exception as X:

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

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

1876 return self._fset(f)

1877

1878 @property_RO

1879 def imag(self):

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

1881

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

1883 '''

1884 return _0_0

1885

1886 def int_float(self, **raiser_RESIDUAL):

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

1888

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

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

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

1892

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

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

1895 is zero or not significant.

1896

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

1898 B{C{RESIDUAL}}.

1899

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

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

1902 '''

1903 s, r = self._fint2

1904 if r:

1905 s, r = self._fprs2

1906 if r: # PYCHOK no cover

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

1908 if R:

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

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

1911 s = float(s)

1912 return s

1913

1914 def is_exact(self):

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

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

1917 '''

1918 return self.residual is INT0

1919

1920 def is_finite(self): # in .constants

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

1922

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

1924 '''

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

1926

1927 def is_integer(self):

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

1929

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

1931 '''

1932 s, r = self._fint2

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

1934

1935 def is_math_fma(self):

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

1937

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

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

1940 C{PyGeodesy} implementation.

1941 '''

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

1943

1944 def is_math_fsum(self):

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

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

1947

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

1949 otherwise.

1950 '''

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

1952

1953 def is_scalar(self, **raiser_RESIDUAL):

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

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

1956

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

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

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

1960

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

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

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

1964

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

1966 B{C{RESIDUAL}}.

1967

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

1969 L{Fsum.as_iscalar}.

1970 '''

1971 s, r = self._fprs2

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

1973

1974 def _mul_Fsum(self, other, op):

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

1976 '''

1977 # assert _isFsum_2Tuple(other)

1978 if self._ps and other._ps:

1979 try:

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

1981 except Exception as X:

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

1983 else:

1984 f = _0_0

1985 return f

1986

1987 def _mul_reduce(self, *others):

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

1989 '''

1990 r = _1_0

1991 for f in others:

1992 r *= sum(f._ps) if _isFsum_2Tuple(f) else float(f)

1993 return r

1994

1995 def _mul_scalar(self, factor, op):

1996 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0.0} or C{self}.

1997 '''

1998 # assert isscalar(factor)

1999 if self._ps and self._finite(factor, op=op):

2000 f = self if factor == _1_0 else (

2001 self._neg if factor == _N_1_0 else

2002 self._ps_mul(op, factor).as_iscalar)

2003 else:

2004 f = _0_0

2005 return f

2006

2007# @property_RO

2008# def _n_d(self):

2009# n, d = self.as_integer_ratio()

2010# return n / d

2011

2012 @property_RO

2013 def _neg(self):

2014 '''(INTERNAL) Return C{Fsum(-self)} or scalar C{NEG0}.

2015 '''

2016 return _Psum(self._ps_neg) if self._ps else NEG0

2017

2018 @property_RO

2019 def _nfprs2(self):

2020 '''(INTERNAL) Handle I{non-finite} C{_fprs2}.

2021 '''

2022 try: # to handle nonfiniterrors, etc.

2023 t = self._fprs2

2024 except (OverflowError, ValueError):

2025 t = Fsum2Tuple(sum(self._ps), _NONFINITEr)

2026 return t

2027

2028 def nonfinites(self, *OK):

2029 '''Handle I{non-finite} C{float}s as C{inf}, C{INF}, C{NINF}, C{nan}

2030 and C{NAN} for this L{Fsum} or throw C{OverflowError} respectively

2031 C{ValueError} exceptions, overriding the L{nonfiniterrors} default.

2032

2033 @arg OK: If omitted, leave the override unchanged, if C{True},

2034 I{non-finites} are C{OK}, if C{False} throw exceptions

2035 or if C{None} remove the override (C{bool} or C{None}).

2036

2037 @return: The previous setting (C{bool} or C{None} if not set).

2038

2039 @see: Function L{nonfiniterrors<fsums.nonfiniterrors>}.

2040

2041 @note: Use property L{nonfinitesOK<Fsum.nonfinitesOK>} to determine

2042 whether I{non-finites} are C{OK} for this L{Fsum} and by the

2043 L{nonfiniterrors} default.

2044 '''

2045 _ks = Fsum._nonfinites_isfine_kwds

2046 if OK: # delattrof(self, _isfine=None)

2047 k = _xkwds_pop(self.__dict__, _isfine=None)

2048 if OK[0] is not None:

2049 self._isfine = _ks[bool(OK[0])]

2050 self._update()

2051 else: # getattrof(self, _isfine=None)

2052 k = _xkwds_get(self.__dict__, _isfine=None)

2053 # dict(map(reversed, _ks.items())).get(k, None)

2054 # raises a TypeError: unhashable type: 'dict'

2055 return True if k is _ks[True] else (

2056 False if k is _ks[False] else None)

2057

2058 _nonfinites_isfine_kwds = {True: dict(_isfine=_isOK),

2059 False: dict(_isfine=_isfinite)}

2060

2061 @property_RO

2062 def nonfinitesOK(self):

2063 '''Are I{non-finites} C{OK} for this L{Fsum} or by default? (C{bool}).

2064 '''

2065# nf = self.nonfinites()

2066# if nf is None:

2067# nf = not nonfiniterrors()

2068 return _isOK_or_finite(INF, **self._isfine)

2069

2070 def _nonfiniteX(self, X, op, f, nonfinites=None, raiser=None):

2071 '''(INTERNAL) Handle a I{non-finite} exception.

2072 '''

2073 if nonfinites is None:

2074 nonfinites = _isOK_or_finite(f, **self._isfine) if raiser is None else (not raiser)

2075 if not nonfinites:

2076 raise self._ErrorX(X, op, f)

2077 return f

2078

2079 def _optionals(self, f2product=None, nonfinites=None, **name_RESIDUAL):

2080 '''(INTERNAL) Re/set options from keyword arguments.

2081 '''

2082 if f2product is not None:

2083 self.f2product(f2product)

2084 if nonfinites is not None:

2085 self.nonfinites(nonfinites)

2086 if name_RESIDUAL: # MUST be last

2087 n, kwds = _name2__(**name_RESIDUAL)

2088 if kwds:

2089 R = Fsum._RESIDUAL

2090 t = _threshold(R, **kwds)

2091 if t != R:

2092 self._RESIDUAL = t

2093 if n:

2094 self.name = n # self.rename(n)

2095

2096 def _1_Over(self, x, op, **raiser_RESIDUAL): # vs _1_over

2097 '''(INTERNAL) Return C{Fsum(1) / B{x}}.

2098 '''

2099 return self._Fsum_as(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)

2100

2101 @property_RO

2102 def partials(self):

2103 '''Get this instance' current, partial sums (C{tuple} of C{float}s).

2104 '''

2105 return tuple(self._ps)

2106

2107 def pow(self, x, *mod, **raiser_RESIDUAL):

2108 '''Return C{B{self}**B{x}} as L{Fsum}.

2109

2110 @arg x: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

2111 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument

2112 C{pow(B{self}, B{other}, B{mod})} version.

2113 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore

2114 L{ResidualError}s (C{bool}) and C{B{RESIDUAL}=scalar}

2115 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.

2116

2117 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}

2118 result (L{Fsum}).

2119

2120 @raise ResidualError: Non-zero, significant residual or invalid

2121 B{C{RESIDUAL}}.

2122

2123 @note: If B{C{mod}} is given and C{None}, the result will be an

2124 C{integer} L{Fsum} provided this instance C{is_integer}

2125 or set to C{integer} by an L{Fsum.fint} call.

2126

2127 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint}, L{Fsum.is_integer}

2128 and L{Fsum.root}.

2129 '''

2130 f = self._copyd(self.pow)

2131 return f._fpow(x, _pow_op_, *mod, **raiser_RESIDUAL) # f = pow(f, x, *mod)

2132

2133 def _pow(self, other, unused, op, **raiser_RESIDUAL):

2134 '''Return C{B{self} ** B{other}}.

2135 '''

2136 if _isFsum_2Tuple(other):

2137 f = self._pow_Fsum(other, op, **raiser_RESIDUAL)

2138 elif self._scalar(other, op):

2139 x = self._finite(other, op=op)

2140 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)

2141 else:

2142 f = self._pow_0_1(0, other)

2143 return f

2144

2145 def _pow_0_1(self, x, other):

2146 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.

2147 '''

2148 return self if x else (1 if isint(other) and self.is_integer() else _1_0)

2149

2150 def _pow_2_3(self, b, x, other, op, *mod, **raiser_RESIDUAL):

2151 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} and 3-arg C{pow(B{b},

2152 B{x}, int B{mod} or C{None})}, embellishing errors.

2153 '''

2154

2155 if mod: # b, x, mod all C{int}, unless C{mod} is C{None}

2156 m = mod[0]

2157 # assert _isFsum_2Tuple(b)

2158

2159 def _s(s, r):

2160 R = self._raiser(r, s, **raiser_RESIDUAL)

2161 if R:

2162 raise self._ResidualError(op, other, r, mod=m, **R)

2163 return s

2164

2165 b = _s(*(b._fprs2 if m is None else b._fint2))

2166 x = _s(*_2tuple2(x))

2167

2168 try:

2169 # 0**INF == 0.0, 1**INF == 1.0, -1**2.3 == -(1**2.3)

2170 s = pow(b, x, *mod)

2171 if iscomplex(s):

2172 # neg**frac == complex in Python 3+, but ValueError in 2-

2173 raise ValueError(_strcomplex(s, b, x, *mod))

2174 _ = _2finite(s, **self._isfine) # ignore float

2175 return s

2176 except Exception as X:

2177 raise self._ErrorX(X, op, other, *mod)

2178

2179 def _pow_Fsum(self, other, op, **raiser_RESIDUAL):

2180 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsum_2Tuple(other)}.

2181 '''

2182 # assert _isFsum_2Tuple(other)

2183 x, r = other._fprs2

2184 f = self._pow_scalar(x, other, op, **raiser_RESIDUAL)

2185 if f and r:

2186 f *= self._pow_scalar(r, other, op, **raiser_RESIDUAL)

2187 return f

2188

2189 def _pow_int(self, x, other, op, **raiser_RESIDUAL):

2190 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.

2191 '''

2192 # assert isint(x) and x >= 0

2193 ps = self._ps

2194 if len(ps) > 1:

2195 _mul_Fsum = Fsum._mul_Fsum

2196 if x > 4:

2197 p = self

2198 f = self if (x & 1) else self._Fsum_as(_1_0)

2199 m = x >> 1 # // 2

2200 while m:

2201 p = _mul_Fsum(p, p, op) # p **= 2

2202 if (m & 1):

2203 f = _mul_Fsum(f, p, op) # f *= p

2204 m >>= 1 # //= 2

2205 elif x > 1: # self**2, 3, or 4

2206 f = _mul_Fsum(self, self, op)

2207 if x > 2: # self**3 or 4

2208 p = self if x < 4 else f

2209 f = _mul_Fsum(f, p, op)

2210 else: # self**1 or self**0 == 1 or _1_0

2211 f = self._pow_0_1(x, other)

2212 elif ps: # self._ps[0]**x

2213 f = self._pow_2_3(ps[0], x, other, op, **raiser_RESIDUAL)

2214 else: # PYCHOK no cover

2215 # 0**pos_int == 0, but 0**0 == 1

2216 f = 0 if x else 1

2217 return f

2218

2219 def _pow_scalar(self, x, other, op, **raiser_RESIDUAL):

2220 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.

2221 '''

2222 s, r = self._fprs2

2223 if r:

2224 # assert s != 0

2225 if isint(x, both=True): # self**int

2226 x = int(x)

2227 y = abs(x)

2228 if y > 1:

2229 f = self._pow_int(y, other, op, **raiser_RESIDUAL)

2230 if x > 0: # i.e. > 1

2231 return f # Fsum or scalar

2232 # assert x < 0 # i.e. < -1

2233 if _isFsum(f):

2234 s, r = f._fprs2

2235 if r:

2236 return self._1_Over(f, op, **raiser_RESIDUAL)

2237 else: # scalar

2238 s = f

2239 # use s**(-1) to get the CPython

2240 # float_pow error iff s is zero

2241 x = -1

2242 elif x < 0: # self**(-1)

2243 return self._1_Over(self, op, **raiser_RESIDUAL) # 1 / self

2244 else: # self**1 or self**0

2245 return self._pow_0_1(x, other) # self, 1 or 1.0

2246 else: # self**fractional

2247 R = self._raiser(r, s, **raiser_RESIDUAL)

2248 if R:

2249 raise self._ResidualError(op, other, r, **R)

2250 n, d = self.as_integer_ratio()

2251 if abs(n) > abs(d):

2252 n, d, x = d, n, (-x)

2253 s = n / d

2254 # assert isscalar(s) and isscalar(x)

2255 return self._pow_2_3(s, x, other, op, **raiser_RESIDUAL)

2256

2257 def _ps_acc(self, ps, xs, up=True, **unused):

2258 '''(INTERNAL) Accumulate C{xs} known scalars into list C{ps}.

2259 '''

2260 n = 0

2261 _2s = _2sum

2262 _fi = self._isfine

2263 for x in (tuple(xs) if xs is ps else xs):

2264 # assert isscalar(x) and _isOK_or_finite(x, **self._isfine)

2265 if x:

2266 i = 0

2267 for p in ps:

2268 x, p = _2s(x, p, **_fi)

2269 if p:

2270 ps[i] = p

2271 i += 1

2272 ps[i:] = (x,) if x else ()

2273 n += 1

2274 if n:

2275 self._n += n

2276 # Fsum._ps_max = max(Fsum._ps_max, len(ps))

2277 if up:

2278 self._update()

2279# x = sum(ps)

2280# if not _isOK_or_finite(x, **fi):

2281# ps[:] = x, # collapse ps

2282 return ps

2283

2284 def _ps_mul(self, op, *factors):

2285 '''(INTERNAL) Multiply this instance' C{partials} with

2286 each scalar C{factor} and accumulate into an C{Fsum}.

2287 '''

2288 def _psfs(ps, fs, _isfine=_isfinite):

2289 if len(ps) < len(fs):

2290 ps, fs = fs, ps

2291 if self._f2product:

2292 fs, p = _2split3s(fs), fs

2293 if len(ps) > 1 and fs is not p:

2294 fs = tuple(fs) # several ps

2295 _pfs = _2products

2296 else:

2297 def _pfs(p, fs):

2298 return (p * f for f in fs)

2299

2300 for p in ps:

2301 for x in _pfs(p, fs):

2302 yield x if _isfine(x) else _nfError(x)

2303

2304 xs = _psfs(self._ps, factors, **self._isfine)

2305 f = _Psum(self._ps_acc([], xs, up=False), name=op)

2306 return f

2307

2308 @property_RO

2309 def _ps_neg(self):

2310 '''(INTERNAL) Yield the partials, I{negated}.

2311 '''

2312 for p in self._ps:

2313 yield -p

2314

2315 def _ps_other(self, op, other):

2316 '''(INTERNAL) Yield C{other} as C{scalar}s.

2317 '''

2318 if _isFsum_2Tuple(other):

2319 for p in other._ps:

2320 yield p

2321 else:

2322 yield self._scalar(other, op)

2323

2324 def _ps_1sum(self, *less):

2325 '''(INTERNAL) Return the partials sum, 1-primed C{less} some scalars.

2326 '''

2327 def _1psls(ps, ls):

2328 yield _1_0

2329 for p in ps:

2330 yield p

2331 for p in ls:

2332 yield -p

2333 yield _N_1_0

2334

2335 return _fsum(_1psls(self._ps, less))

2336

2337 def _raiser(self, r, s, raiser=True, **RESIDUAL):

2338 '''(INTERNAL) Does ratio C{r / s} exceed the RESIDUAL threshold

2339 I{and} is residual C{r} I{non-zero} or I{significant} (for a

2340 negative respectively positive C{RESIDUAL} threshold)?

2341 '''

2342 if r and raiser:

2343 t = self._RESIDUAL

2344 if RESIDUAL:

2345 t = _threshold(t, **RESIDUAL)

2346 if t < 0 or (s + r) != s:

2347 q = (r / s) if s else s # == 0.

2348 if fabs(q) > fabs(t):

2349 return dict(ratio=q, R=t)

2350 return {}

2351

2352 def _rcopyd(self, other, which):

2353 '''(INTERNAL) Copy for I{reverse-dyadic} operators.

2354 '''

2355 return other._copyd(which) if _isFsum(other) else \

2356 self._copyd(which)._fset(other)

2357

2358 rdiv = __rtruediv__

2359

2360 @property_RO

2361 def real(self):

2362 '''Get the C{real} part of this instance (C{float}).

2363

2364 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}

2365 and properties L{Fsum.ceil}, L{Fsum.floor},

2366 L{Fsum.imag} and L{Fsum.residual}.

2367 '''

2368 return float(self)

2369

2370 @property_RO

2371 def residual(self):

2372 '''Get this instance' residual or residue (C{float} or C{int}):

2373 the C{sum(partials)} less the precision running sum C{fsum}.

2374

2375 @note: The C{residual is INT0} iff the precision running

2376 C{fsum} is considered to be I{exact}.

2377

2378 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.

2379 '''

2380 return self._fprs2.residual

2381

2382 def RESIDUAL(self, *threshold):

2383 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,

2384 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.

2385

2386 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising

2387 L{ResidualError}s in division and exponention, if

2388 C{None}, restore the default set with env variable

2389 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

2390 current setting.

2391

2392 @return: The previous C{RESIDUAL} setting (C{float}), default C{0.0}.

2393

2394 @raise ResidualError: Invalid B{C{threshold}}.

2395

2396 @note: L{ResidualError}s may be thrown if (1) the non-zero I{ratio}

2397 C{residual / fsum} exceeds the given B{C{threshold}} and (2)

2398 the C{residual} is non-zero and (3) is I{significant} vs the

2399 C{fsum}, i.e. C{(fsum + residual) != fsum} and (4) optional

2400 keyword argument C{raiser=False} is missing. Specify a

2401 negative B{C{threshold}} for only non-zero C{residual}

2402 testing without the I{significant} case.

2403 '''

2404 r = self._RESIDUAL

2405 if threshold:

2406 t = threshold[0]

2407 self._RESIDUAL = Fsum._RESIDUAL if t is None else ( # for ...

2408 (_0_0 if t else _1_0) if isbool(t) else

2409 _threshold(t)) # ... backward compatibility

2410 return r

2411

2412 def _ResidualError(self, op, other, residual, **mod_R):

2413 '''(INTERNAL) Non-zero B{C{residual}} etc.

2414 '''

2415 def _p(mod=None, R=0, **unused): # ratio=0

2416 return (_non_zero_ if R < 0 else _significant_) \

2417 if mod is None else _integer_

2418

2419 t = _stresidual(_p(**mod_R), residual, **mod_R)

2420 return self._Error(op, other, ResidualError, txt=t)

2421

2422 def root(self, root, **raiser_RESIDUAL):

2423 '''Return C{B{self}**(1 / B{root})} as L{Fsum}.

2424

2425 @arg root: Non-zero order (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

2426 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} to ignore any

2427 L{ResidualError}s (C{bool}) or C{B{RESIDUAL}=scalar}

2428 to override the current L{RESIDUAL<Fsum.RESIDUAL>}.

2429

2430 @return: The C{self ** (1 / B{root})} result (L{Fsum}).

2431

2432 @raise ResidualError: Non-zero, significant residual or invalid

2433 B{C{RESIDUAL}}.

2434

2435 @see: Method L{Fsum.pow}.

2436 '''

2437 x = self._1_Over(root, _truediv_op_, **raiser_RESIDUAL)

2438 f = self._copyd(self.root)

2439 return f._fpow(x, f.name, **raiser_RESIDUAL) # == pow(f, x)

2440

2441 def _scalar(self, other, op, **txt):

2442 '''(INTERNAL) Return scalar C{other} or throw a C{TypeError}.

2443 '''

2444 if isscalar(other):

2445 return other

2446 raise self._Error(op, other, _TypeError, **txt) # _invalid_

2447

2448 def signOf(self, res=True):

2449 '''Determine the sign of this instance.

2450

2451 @kwarg res: If C{True}, consider the residual,

2452 otherwise ignore the latter (C{bool}).

2453

2454 @return: The sign (C{int}, -1, 0 or +1).

2455 '''

2456 s, r = self._nfprs2

2457 r = (-r) if res else 0

2458 return _signOf(s, r)

2459

2460 def toRepr(self, **lenc_prec_sep_fmt): # PYCHOK signature

2461 '''Return this C{Fsum} instance as representation.

2462

2463 @kwarg lenc_prec_sep_fmt: Optional keyword arguments

2464 for method L{Fsum.toStr}.

2465

2466 @return: This instance (C{repr}).

2467 '''

2468 return Fmt.repr_at(self, self.toStr(**lenc_prec_sep_fmt))

2469

2470 def toStr(self, lenc=True, **prec_sep_fmt): # PYCHOK signature

2471 '''Return this C{Fsum} instance as string.

2472

2473 @kwarg lenc: If C{True}, include the current C{[len]} of this

2474 L{Fsum} enclosed in I{[brackets]} (C{bool}).

2475 @kwarg prec_sep_fmt: Optional keyword arguments for method

2476 L{Fsum2Tuple.toStr}.

2477

2478 @return: This instance (C{str}).

2479 '''

2480 p = self.classname

2481 if lenc:

2482 p = Fmt.SQUARE(p, len(self))

2483 n = _enquote(self.name, white=_UNDER_)

2484 t = self._nfprs2.toStr(**prec_sep_fmt)

2485 return NN(p, _SPACE_, n, t)

2486

2487 def _truediv(self, other, op, **raiser_RESIDUAL):

2488 '''(INTERNAL) Return C{B{self} / B{other}} as an L{Fsum}.

2489 '''

2490 f = self._copyd(self.__truediv__)

2491 return f._ftruediv(other, op, **raiser_RESIDUAL)

2492

2493 def _update(self, updated=True): # see ._fset

2494 '''(INTERNAL) Zap all cached C{Property_RO} values.

2495 '''

2496 if updated:

2497 _pop = self.__dict__.pop

2498 for p in _ROs:

2499 _ = _pop(p, None)

2500# Fsum._fint2._update(self)

2501# Fsum._fprs ._update(self)

2502# Fsum._fprs2._update(self)

2503 return self # for .fset_

2504

2505_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK see Fsum._update

2506

2507 if _NONFINITES == _std_: # PYCHOK no cover

2508 _ = nonfiniterrors(False)

2509

2510

2511 def _Float_Int(arg, **name_Error):

2512 '''(INTERNAL) L{DivMod2Tuple}, L{Fsum2Tuple} Unit.

2513 '''

2514 U = Int if isint(arg) else Float

2515 return U(arg, **name_Error)

2516

2517

2518 class DivMod2Tuple(_NamedTuple):

2519 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder

2520 C{mod} results of a C{divmod} operation.

2521

2522 @note: Quotient C{div} an C{int} in Python 3+ but a C{float}

2523 in Python 2-. Remainder C{mod} an L{Fsum} instance.

2524 '''

2525 _Names_ = ('div', 'mod')

2526 _Units_ = (_Float_Int, Fsum)

2527

2528

2529 class Fsum2Tuple(_NamedTuple): # in .fstats

2530 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}

2531 and the C{residual}, the sum of the remaining partials. Each

2532 item is C{float} or C{int}.

2533

2534 @note: If the C{residual is INT0}, the C{fsum} is considered

2535 to be I{exact}, see method L{Fsum2Tuple.is_exact}.

2536 '''

2537 _Names_ = ( typename(Fsum.fsum), Fsum.residual.name)

2538 _Units_ = (_Float_Int, _Float_Int)

2539

2540 def __abs__(self): # in .fmath

2541 return self._Fsum.__abs__()

2542

2543 def __bool__(self): # PYCHOK Python 3+

2544 return bool(self._Fsum)

2545

2546 def __eq__(self, other):

2547 return self._other_op(other, self.__eq__)

2548

2549 def __float__(self):

2550 return self._Fsum.__float__()

2551

2552 def __ge__(self, other):

2553 return self._other_op(other, self.__ge__)

2554

2555 def __gt__(self, other):

2556 return self._other_op(other, self.__gt__)

2557

2558 def __le__(self, other):

2559 return self._other_op(other, self.__le__)

2560

2561 def __lt__(self, other):

2562 return self._other_op(other, self.__lt__)

2563

2564 def __int__(self):

2565 return self._Fsum.__int__()

2566

2567 def __ne__(self, other):

2568 return self._other_op(other, self.__ne__)

2569

2570 def __neg__(self):

2571 return self._Fsum.__neg__()

2572

2573 __nonzero__ = __bool__ # Python 2-

2574

2575 def __pos__(self):

2576 return self._Fsum.__pos__()

2577

2578 def as_integer_ratio(self):

2579 '''Return this instance as the ratio of 2 integers.

2580

2581 @see: Method L{Fsum.as_integer_ratio} for further details.

2582 '''

2583 return self._Fsum.as_integer_ratio()

2584

2585 @property_RO

2586 def _fint2(self):

2587 return self._Fsum._fint2

2588

2589 @property_RO

2590 def _fprs2(self):

2591 return self._Fsum._fprs2

2592

2593 @Property_RO

2594 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats

2595 s, r = _s_r2(*self)

2596 ps = (r, s) if r else (s,)

2597 return _Psum(ps, name=self.name)

2598

2599 def Fsum_(self, *xs, **name_f2product_nonfinites_RESIDUAL):

2600 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.

2601 '''

2602 return Fsum(self, *xs, **name_f2product_nonfinites_RESIDUAL)

2603

2604 def is_exact(self):

2605 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).

2606 '''

2607 return self._Fsum.is_exact()

2608

2609 def is_finite(self): # in .constants

2610 '''Is this L{Fsum2Tuple} C{finite}? (C{bool}).

2611

2612 @see: Function L{isfinite<pygeodesy.isfinite>}.

2613 '''

2614 return self._Fsum.is_finite()

2615

2616 def is_integer(self):

2617 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).

2618 '''

2619 return self._Fsum.is_integer()

2620

2621 def _mul_scalar(self, other, op): # for Fsum._fmul

2622 return self._Fsum._mul_scalar(other, op)

2623

2624 @property_RO

2625 def _n(self):

2626 return self._Fsum._n

2627

2628 def _other_op(self, other, which):

2629 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)

2630 return getattr(C, typename(which))(s, other)

2631

2632 @property_RO

2633 def _ps(self):

2634 return self._Fsum._ps

2635

2636 @property_RO

2637 def _ps_neg(self):

2638 return self._Fsum._ps_neg

2639

2640 def signOf(self, **res):

2641 '''Like method L{Fsum.signOf}.

2642 '''

2643 return self._Fsum.signOf(**res)

2644

2645 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature

2646 '''Return this L{Fsum2Tuple} as string (C{str}).

2647

2648 @kwarg fmt: Optional C{float} format (C{letter}).

2649 @kwarg prec_sep: Optional keyword arguments for function

2650 L{fstr<streprs.fstr>}.

2651 '''

2652 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))

2653

2654_Fsum_2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines

2655

2656

2657 class ResidualError(_ValueError):

2658 '''Error raised for a division, power or root operation of

2659 an L{Fsum} instance with a C{residual} I{ratio} exceeding

2660 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.

2661

2662 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.

2663 '''

2664 pass

2665

2666

2667 try:

2668 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+

2669

2670 # make sure _fsum works as expected (XXX check

2671 # float.__getformat__('float')[:4] == 'IEEE'?)

2672 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover

2673 del _fsum # nope, remove _fsum ...

2674 raise ImportError() # ... use _fsum below

2675

2676 _sum = _fsum # in .elliptic

2677 except ImportError:

2678 _sum = sum # in .elliptic

2679

2680 def _fsum(xs):

2681 '''(INTERNAL) Precision summation, Python 2.5-.

2682 '''

2683 F = Fsum(name=_fsum.name, f2product=False, nonfinites=True)

2684 return float(F._facc(xs, up=False))

2685

2686

2687 def fsum(xs, nonfinites=None, **floats):

2688 '''Precision floating point summation from Python's C{math.fsum}.

2689

2690 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

2691 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK}, if

2692 C{False} I{non-finites} raise an Overflow-/ValueError or if

2693 C{None}, L{nonfiniterrors} applies (C{bool} or C{None}).

2694 @kwarg floats: DEPRECATED keyword argument C{B{floats}=False} (C{bool}), use

2695 keyword argument C{B{nonfinites}=False} instead.

2696

2697 @return: Precision C{fsum} (C{float}).

2698

2699 @raise OverflowError: Infinite B{C{xs}} item or intermediate C{math.fsum} overflow.

2700

2701 @raise TypeError: Invalid B{C{xs}} item.

2702

2703 @raise ValueError: Invalid or C{NAN} B{C{xs}} item.

2704

2705 @see: Function L{nonfiniterrors}, class L{Fsum} and methods L{Fsum.nonfinites},

2706 L{Fsum.fsum}, L{Fsum.fadd} and L{Fsum.fadd_}.

2707 '''

2708 return _xsum(fsum, xs, nonfinites=nonfinites, **floats) if xs else _0_0

2709

2710

2711 def fsum_(*xs, **nonfinites):

2712 '''Precision floating point summation of all positional items.

2713

2714 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.

2715 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).

2716

2717 @see: Function L{fsum<fsums.fsum>} for further details.

2718 '''

2719 return _xsum(fsum_, xs, **nonfinites) if xs else _0_0 # origin=1?

2720

2721

2722 def fsumf_(*xs):

2723 '''Precision floating point summation of all positional items with I{non-finites} C{OK}.

2724

2725 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),

2726 all positional.

2727

2728 @see: Function L{fsum_<fsums.fsum_>} for further details.

2729 '''

2730 return _xsum(fsumf_, xs, nonfinites=True) if xs else _0_0 # origin=1?

2731

2732

2733 def fsum1(xs, **nonfinites):

2734 '''Precision floating point summation, 1-primed.

2735

2736 @arg xs: Iterable of items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

2737 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).

2738

2739 @see: Function L{fsum<fsums.fsum>} for further details.

2740 '''

2741 return _xsum(fsum1, xs, primed=1, **nonfinites) if xs else _0_0

2742

2743

2744 def fsum1_(*xs, **nonfinites):

2745 '''Precision floating point summation of all positional items, 1-primed.

2746

2747 @arg xs: Items to add (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.

2748 @kwarg nonfinites: Use C{B{nonfinites}=True} if I{non-finites} are C{OK} (C{bool}).

2749

2750 @see: Function L{fsum_<fsums.fsum_>} for further details.

2751 '''

2752 return _xsum(fsum1_, xs, primed=1, **nonfinites) if xs else _0_0 # origin=1?

2753

2754

2755 def fsum1f_(*xs):

2756 '''Precision floating point summation of all positional items, 1-primed and

2757 with I{non-finites} C{OK}.

2758

2759 @see: Function L{fsum_<fsums.fsum_>} for further details.

2760 '''

2761 return _xsum(fsum1f_, xs, nonfinites=True, primed=1) if xs else _0_0

2762

2763

2764 def _x_isfine(nfOK, **kwds): # get the C{_x} and C{_isfine} handlers.

2765 _x_kwds = dict(_x= (_passarg if nfOK else _2finite),

2766 _isfine=(_isOK if nfOK else _isfinite)) # PYCHOK kwds

2767 _x_kwds.update(kwds)

2768 return _x_kwds

2769

2770

2771 def _X_ps(X): # default C{_X} handler

2772 return X._ps # lambda X: X._ps

2773

2774

2775 def _xs(xs, _X=_X_ps, _x=float, _isfine=_isfinite, # defaults for Fsum._facc

2776 origin=0, which=None, **_Cdot):

2777 '''(INTERNAL) Yield each C{xs} item as 1 or more C{float}s.

2778 '''

2779 i, x = 0, xs

2780 try:

2781 for i, x in enumerate(_xiterable(xs)):

2782 if _isFsum_2Tuple(x):

2783 for p in _X(x):

2784 yield p if _isfine(p) else _nfError(p)

2785 else:

2786 f = _x(x)

2787 yield f if _isfine(f) else _nfError(f)

2788

2789 except (OverflowError, TypeError, ValueError) as X:

2790 t = _xsError(X, xs, i + origin, x)

2791 if which: # prefix invokation

2792 w = unstr(which, *xs, _ELLIPSIS=4, **_Cdot)

2793 t = _COMMASPACE_(w, t)

2794 raise _xError(X, t, txt=None)

2795

2796

2797 def _xsum(which, xs, nonfinites=None, primed=0, **floats): # origin=0

2798 '''(INTERNAL) Precision summation of C{xs} with conditions.

2799 '''

2800 if floats: # for backward compatibility

2801 nonfinites = _xkwds_get1(floats, floats=nonfinites)

2802 elif nonfinites is None:

2803 nonfinites = not nonfiniterrors()

2804 fs = _xs(xs, **_x_isfine(nonfinites, which=which)) # PYCHOK yield

2805 return _fsum(_1primed(fs) if primed else fs)

2806

2807

2808# delete all decorators, etc.

2809 del _allPropertiesOf_n, deprecated_method, deprecated_property_RO, \

2810 Property, Property_RO, property_RO, _ALL_LAZY, _F2PRODUCT, \

2811 MANT_DIG, _NONFINITES, _RESIDUAL_0_0, _envPYGEODESY, _std_

2812

2813 if __name__ == _DMAIN_:

2814

2815 # usage: python3 -m pygeodesy.fsums

2816

2817 def _test(n):

2818 # copied from Hettinger, see L{Fsum} reference

2819 from pygeodesy import frandoms, printf

2820

2821 printf(typename(_fsum), end=_COMMASPACE_)

2822 printf(typename(_psum), end=_COMMASPACE_)

2823

2824 F = Fsum()

2825 if F.is_math_fsum():

2826 for t in frandoms(n, seeded=True):

2827 assert float(F.fset_(*t)) == _fsum(t)

2828 printf(_DOT_, end=NN)

2829 printf(NN)

2830

2831 _test(128)

2832

2833# **) MIT License

2834#

2835# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.

2836#

2837# Permission is hereby granted, free of charge, to any person obtaining a

2838# copy of this software and associated documentation files (the "Software"),

2839# to deal in the Software without restriction, including without limitation

2840# the rights to use, copy, modify, merge, publish, distribute, sublicense,

2841# and/or sell copies of the Software, and to permit persons to whom the

2842# Software is furnished to do so, subject to the following conditions:

2843#

2844# The above copyright notice and this permission notice shall be included

2845# in all copies or substantial portions of the Software.

2846#

2847# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

2848# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

2849# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

2850# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

2851# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

2852# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

2853# OTHER DEALINGS IN THE SOFTWARE.