1

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

3

4 u'''Class L{Fsum} for precision floating point summation and I{running}

5 summation based on, respectively similar to Python's C{math.fsum}.

6

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

8 C{residual} value, see property L{Fsum.residual}. However, there are several

9 C{integer} L{Fsum} cases, for example the result of C{ceil}, C{floor},

10 C{Fsum.__floordiv__} and methods L{Fsum.fint} and L{Fsum.fint2}.

11

12 Also, L{Fsum} methods L{Fsum.pow}, L{Fsum.__ipow__}, L{Fsum.__pow__} and

13 L{Fsum.__rpow__} return a (very long) C{int} if invoked with optional argument

14 C{mod} set to C{None}. The C{residual} of an C{integer} L{Fsum} may be between

15 C{-1.0} and C{+1.0}, including C{INT0} if considered to be I{exact}.

16

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

18 C{"0.0"} as the threshold to throw a L{ResidualError} for a division, power or

19 root operation of an L{Fsum} instance with a C{residual} I{ratio} exceeding

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

21 and L{Fsum.__itruediv__}.

22'''

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

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

25

26 from pygeodesy.basics import isbool, iscomplex, isint, isscalar, \

27 _signOf, itemsorted, signOf, _xiterable, \

28 _xiterablen, _enquote

29 from pygeodesy.constants import INT0, _isfinite, NEG0, _pos_self, \

30 _0_0, _1_0, _N_1_0, Float, Int

31 from pygeodesy.errors import _OverflowError, _TypeError, _UnexpectedError, \

32 _ValueError, _xError, _xError2, _xkwds_get1, \

33 _xkwds_pop2

34# from pygeodesy.internals import _enquote # from .basics

35 from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _DOT_, \

36 _EQUAL_, _from_, _LANGLE_, _NOTEQUAL_, \

37 _not_finite_, _PERCENT_, _PLUS_, \

38 _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_

39 from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2

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

41 _NotImplemented

42 from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \

43 Property, Property_RO, property_RO

44 from pygeodesy.streprs import Fmt, fstr, unstr

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

46

47 from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp

48

49__all__ = _ALL_LAZY.fsums

50__version__ = '24.05.29'

51

52_add_op_ = _PLUS_ # in .auxilats.auxAngle

53_eq_op_ = _EQUAL_ * 2 # _DEQUAL_

54_div_ = 'div'

55_floordiv_op_ = _SLASH_ * 2 # _DSLASH_

56_fset_op_ = _EQUAL_

57_ge_op_ = _RANGLE_ + _EQUAL_

58_gt_op_ = _RANGLE_

59_iadd_op_ = _add_op_ + _EQUAL_ # in .auxilats.auxAngle, .fstats

60_integer_ = 'integer'

61_le_op_ = _LANGLE_ + _EQUAL_

62_lt_op_ = _LANGLE_

63_mod_ = 'mod'

64_mod_op_ = _PERCENT_

65_mul_op_ = _STAR_

66_ne_op_ = _NOTEQUAL_

67_non_zero_ = 'non-zero'

68_pow_op_ = _STAR_ * 2 # _DSTAR_

69_significant_ = 'significant'

70_sub_op_ = _DASH_ # in .auxilats.auxAngle

71_threshold_ = 'threshold'

72_truediv_op_ = _SLASH_

73_divmod_op_ = _floordiv_op_ + _mod_op_

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

75

76

77 def _2delta(*ab):

78 '''(INTERNAL) Helper for C{Fsum._fsum2}.

79 '''

80 try:

81 a, b = _2sum(*ab)

82 except _OverflowError:

83 a, b = ab

84 return float(a if fabs(a) > fabs(b) else b)

85

86

87 def _2error(unused): # in .fstats

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

89 '''

90 raise ValueError(_not_finite_)

91

92

93 def _2finite(x):

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

95 '''

96 x = float(x)

97 return x if _isfinite(x) else _2error(x)

98

99

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

101 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.

102 '''

103 n, v = name_value.popitem() # _xkwds_item2(name_value)

104 try:

105 return _2finite(v)

106 except Exception as X:

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

108

109

110 def _X_ps(X): # for _2floats only

111 return X._ps

112

113

114 def _2floats(xs, origin=0, _X=_X_ps, _x=float):

115 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.

116 '''

117 try:

118 i, x = origin, _X

119 _fin = _isfinite

120 _FsT = _Fsum_Fsum2Tuple_types

121 _isa = isinstance

122 for x in _xiterable(xs):

123 if _isa(x, _FsT):

124 for p in _X(x._Fsum):

125 yield p

126 else:

127 f = _x(x)

128 yield f if _fin(f) else _2error(f)

129 i += 1

130 except Exception as X:

131 raise _xError(X, xs=xs) if x is _X else \

132 _xError(X, Fmt.INDEX(xs=i), x)

133

134

135 def _Fsumf_(*xs): # floats=True, in .auxLat, ...

136 '''(INTERNAL) An C{Fsum} of I{known scalars}.

137 '''

138 return Fsum()._facc_scalar(xs, up=False)

139

140

141 def _Fsum1f_(*xs): # floats=True, in .albers, ...

142 '''(INTERNAL) An C{Fsum} of I{known scalars}, 1-primed.

143 '''

144 return Fsum()._facc_scalar(_1primed(xs), up=False)

145

146

147 def _2halfeven(s, r, p):

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

149 '''

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

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

152 r *= 2

153 t = s + r

154 if r == (t - s):

155 s = t

156 return s

157

158

159 def _isFsum(x): # in .fmath

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

161 '''

162 return isinstance(x, Fsum)

163

164

165 def _isFsumTuple(x): # in .fmath

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

167 '''

168 return isinstance(x, _Fsum_Fsum2Tuple_types)

169

170

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

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

173 '''

174 return _Psum_(_1_0)._ftruediv(x, op, **raiser_RESIDUAL)

175

176

177 def _1primed(xs): # in .fmath

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

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

180 '''

181 yield _1_0

182 for x in xs:

183 yield x

184 yield _N_1_0

185

186

187 def _psum(ps): # PYCHOK used!

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

189 '''

190 # assert isinstance(ps, list)

191 i = len(ps) - 1

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

193 _2s = _2sum

194 while i > 0:

195 i -= 1

196 s, r = _2s(s, ps[i])

197 if r: # sum(ps) became inexact

198 if s:

199 ps[i:] = r, s

200 if i > 0:

201 s = _2halfeven(s, r, ps[i-1])

202 break # return s

203 s = r # PYCHOK no cover

204 ps[i:] = s,

205 return s

206

207

208 def _Psum(ps, **name_RESIDUAL):

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

210 '''

211 f = Fsum(**name_RESIDUAL) if name_RESIDUAL else Fsum()

212 if ps:

213 f._ps[:] = ps

214 f._n = len(f._ps)

215 return f

216

217

218 def _Psum_(*ps, **name_RESIDUAL):

219 '''(INTERNAL) Return an C{Fsum} from 1 or 2 known scalar(s) C{ps}.

220 '''

221 return _Psum(ps, **name_RESIDUAL)

222

223

224 def _2scalar2(other):

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

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

227 '''

228 if _isFsumTuple(other):

229 s, r = other._fint2

230 if r:

231 s, r = other._fprs2

232 if r: # PYCHOK no cover

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

234 else:

235 r = 0

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

237 if isint(s, both=True):

238 s = int(s)

239 return s, r

240

241

242 def _s_r(s, r):

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

244 '''

245 if r:

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

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

248 else:

249 r = INT0

250 return s, r

251

252

253 def _strcomplex(s, *args):

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

255 '''

256 c = _strcomplex.__name__[4:]

257 n = _DASH_(len(args), _arg_)

258 t = unstr(pow, *args)

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

260

261

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

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

264 '''

265 p = _stresidual.__name__[3:]

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

267 for n, v in itemsorted(mod_ratio):

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

269 t = _COMMASPACE_(t, p)

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

271

272

273 def _2sum(a, b): # by .testFmath

274 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual).

275 '''

276 s = a + b

277 if _isfinite(s):

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

279 b, a = a, b

280 return s, (b - (s - a))

281 u = unstr(_2sum, a, b)

282 t = Fmt.PARENSPACED(_not_finite_, s)

283 raise _OverflowError(u, txt=t)

284

285

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

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

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

289 '''

290 if kwds:

291 threshold, kwds = _xkwds_pop2(kwds, RESIDUAL=threshold)

292# threshold = kwds.pop('RESIDUAL', threshold)

293 if kwds:

294 raise _UnexpectedError(**kwds)

295 try:

296 return _2finite(threshold) # PYCHOK None

297 except Exception as x:

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

299

300

301 class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase

302 '''Precision floating point summation and I{running} summation.

303

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

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

306 intermediate, I{running} summuation.

307

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

309 any C{type} having method C{__float__} to convert the C{scalar} to a single

310 C{float}, except C{complex}.

311

312 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from

313 Python's C{math.fsum}.

314

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

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

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

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

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

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

321 '''

322 _math_fsum = None

323 _n = 0

324# _ps = [] # partial sums

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

326 _RESIDUAL = _threshold(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0))

327

328 def __init__(self, *xs, **name_RESIDUAL):

329 '''New L{Fsum} for I{running} precision floating point summation.

330

331 @arg xs: No, one or more initial items to add (each C{scalar} or

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

333 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) for this

334 L{Fsum} and the C{B{RESIDUAL}=0.0} threshold for

335 L{ResidualError}s (C{scalar}).

336

337 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.

338 '''

339 if name_RESIDUAL:

340 n, kwds = _name2__(**name_RESIDUAL)

341 if kwds:

342 R = Fsum._RESIDUAL

343 t = _threshold(R, **kwds)

344 if t != R:

345 self._RESIDUAL = t

346 if n:

347 self.name = n

348

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

350 if xs:

351 self._facc_1(xs, up=False)

352

353 def __abs__(self):

354 '''Return this instance' absolute value as an L{Fsum}.

355 '''

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

357 return (-self) if s < 0 else self._copy_2(self.__abs__)

358

359 def __add__(self, other):

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

361

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

363

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

365

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

367 '''

368 f = self._copy_2(self.__add__)

369 return f._fadd(other, _add_op_)

370

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

372 '''Return C{True} if this instance is I{exactly} non-zero.

373 '''

374 s, r = self._fprs2

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

376

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

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

379

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

381

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

383 '''

384 return self.ceil

385

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

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

388

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

390

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

392 '''

393 s = self._cmp_0(other, self.cmp.__name__)

394 return _signOf(s, 0)

395

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

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

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

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

400

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

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

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

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

405

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

407 B{C{RESIDUAL}}.

408

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

410 '''

411 f = self._copy_2(self.__divmod__)

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

413

414 def __eq__(self, other):

415 '''Compare this with an other instance or C{scalar}.

416 '''

417 return self._cmp_0(other, _eq_op_) == 0

418

419 def __float__(self):

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

421

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

423 '''

424 return float(self._fprs)

425

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

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

428

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

430

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

432 '''

433 return self.floor

434

435 def __floordiv__(self, other):

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

437

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

439

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

441

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

443 '''

444 f = self._copy_2(self.__floordiv__)

445 return f._floordiv(other, _floordiv_op_)

446

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

448 '''Not implemented.'''

449 return _NotImplemented(self, *other)

450

451 def __ge__(self, other):

452 '''Compare this with an other instance or C{scalar}.

453 '''

454 return self._cmp_0(other, _ge_op_) >= 0

455

456 def __gt__(self, other):

457 '''Compare this with an other instance or C{scalar}.

458 '''

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

460

461 def __hash__(self): # PYCHOK no cover

462 '''Return this instance' C{hash}.

463 '''

464 return hash(self._ps) # XXX id(self)?

465

466 def __iadd__(self, other):

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

468

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

470 an iterable of several of the former.

471

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

473

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

475 C{scalar} nor L{Fsum}.

476

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

478 '''

479 try:

480 return self._fadd(other, _iadd_op_)

481 except TypeError:

482 return self._facc_inplace(other, _iadd_op_, self._facc)

483

484 def __ifloordiv__(self, other):

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

486

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

488

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

490

491 @raise ResidualError: Non-zero, significant residual

492 in B{C{other}}.

493

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

495

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

497

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

499

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

501 '''

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

503

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

505 '''Not implemented.'''

506 return _NotImplemented(self, other)

507

508 def __imod__(self, other):

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

510

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

512

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

514

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

516 '''

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

518

519 def __imul__(self, other):

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

521

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

523

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

525

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

527

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

529

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

531 '''

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

533

534 def __int__(self):

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

536

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

538 and L{Fsum.floor}.

539 '''

540 i, _ = self._fint2

541 return i

542

543 def __invert__(self): # PYCHOK no cover

544 '''Not implemented.'''

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

546 return _NotImplemented(self)

547

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

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

550

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

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

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

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

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

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

557

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

559

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

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

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

563

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

565

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

567 is non-zero and significant and either

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

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

570 C{None}.

571

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

573 invocation failed.

574

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

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

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

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

579 is given as C{0}.

580

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

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

583 '''

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

585

586 def __isub__(self, other):

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

588

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

590 an iterable of several of the former.

591

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

593

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

595

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

597 '''

598 try:

599 return self._fsub(other, _isub_op_)

600 except TypeError:

601 return self._facc_inplace(other, _isub_op_, self._facc_neg)

602

603 def __iter__(self):

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

605 '''

606 return iter(self.partials)

607

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

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

610

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

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

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

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

615

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

617

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

619

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

621 B{C{RESIDUAL}}.

622

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

624

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

626

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

628

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

630 '''

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

632

633 def __le__(self, other):

634 '''Compare this with an other instance or C{scalar}.

635 '''

636 return self._cmp_0(other, _le_op_) <= 0

637

638 def __len__(self):

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

640 '''

641 return self._n

642

643 def __lt__(self, other):

644 '''Compare this with an other instance or C{scalar}.

645 '''

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

647

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

649 '''Not implemented.'''

650 return _NotImplemented(self, other)

651

652 def __mod__(self, other):

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

654

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

656 '''

657 f = self._copy_2(self.__mod__)

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

659

660 def __mul__(self, other):

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

662

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

664 '''

665 f = self._copy_2(self.__mul__)

666 return f._fmul(other, _mul_op_)

667

668 def __ne__(self, other):

669 '''Compare this with an other instance or C{scalar}.

670 '''

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

672

673 def __neg__(self):

674 '''Return I{a copy of} this instance, I{negated}.

675 '''

676 f = self._copy_2(self.__neg__)

677 return f._fset(self._neg)

678

679 def __pos__(self):

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

681 '''

682 return self if _pos_self else self._copy_2(self.__pos__)

683

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

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

686

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

688 '''

689 f = self._copy_2(self.__pow__)

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

691

692 def __radd__(self, other):

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

694

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

696 '''

697 f = self._copy_2r(other, self.__radd__)

698 return f._fadd(self, _add_op_)

699

700 def __rdivmod__(self, other):

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

702 C{(quotient, remainder)}.

703

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

705 '''

706 f = self._copy_2r(other, self.__rdivmod__)

707 return f._fdivmod2(self, _divmod_op_)

708

709# def __repr__(self):

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

711# '''

712# return self.toRepr(lenc=True)

713

714 def __rfloordiv__(self, other):

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

716

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

718 '''

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

720 return f._floordiv(self, _floordiv_op_)

721

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

723 '''Not implemented.'''

724 return _NotImplemented(self, other)

725

726 def __rmod__(self, other):

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

728

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

730 '''

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

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

733

734 def __rmul__(self, other):

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

736

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

738 '''

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

740 return f._fmul(self, _mul_op_)

741

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

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

744

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

746 '''

747 f = self._copy_2(self.__round__)

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

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

750

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

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

753

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

755 '''

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

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

758

759 def __rsub__(self, other):

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

761

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

763 '''

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

765 return f._fsub(self, _sub_op_)

766

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

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

769

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

771 '''

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

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

774

775 def __str__(self):

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

777 '''

778 return self.toStr(lenc=True)

779

780 def __sub__(self, other):

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

782

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

784

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

786

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

788 '''

789 f = self._copy_2(self.__sub__)

790 return f._fsub(other, _sub_op_)

791

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

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

794

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

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

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

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

799

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

801

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

803 B{C{RESIDUAL}}.

804

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

806 '''

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

808

809 __trunc__ = __int__

810

811 if _sys_version_info2 < (3, 0): # PYCHOK no cover

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

813 __div__ = __truediv__

814 __idiv__ = __itruediv__

815 __long__ = __int__

816 __nonzero__ = __bool__

817 __rdiv__ = __rtruediv__

818

819 def as_integer_ratio(self):

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

821

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

823 with C{numerator} signed and C{denominator}

824 non-zero, positive.

825

826 @see: Standard C{float.as_integer_ratio} in Python 2.7+.

827 '''

828 n, r = self._fint2

829 if r:

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

831 n *= d

832 n += i

833 else: # PYCHOK no cover

834 d = 1

835 return n, d

836

837 @property_RO

838 def as_iscalar(self):

839 '''Get this instance I{as-is} (L{Fsum} or C{scalar}), the

840 latter only if the C{residual} equals C{zero}.

841 '''

842 s, r = self._fprs2

843 return self if r else s

844

845 @property_RO

846 def ceil(self):

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

848 C{float} in Python 2-).

849

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

851

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

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

854 '''

855 s, r = self._fprs2

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

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

858 c += 1

859 return c # _ceil(self._n_d)

860

861 cmp = __cmp__

862

863 def _cmp_0(self, other, op):

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

865 '''

866 if _isFsumTuple(other):

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

868 elif self._scalar(other, op):

869 s = self._ps_1sum(other)

870 else:

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

872 return s

873

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

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

876

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

878

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

880 '''

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

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

883 if f._ps is self._ps:

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

885 if not deep:

886 f._n = 1

887 # assert f._Fsum is f

888 return f

889

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

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

892 '''

893 n = name or which.__name__ # _dunder_nameof

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

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

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

897 # assert f._n == self._n

898 # assert f._Fsum is f

899 return f

900

901 def _copy_2r(self, other, which):

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

903 '''

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

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

906

907# def _copy_RESIDUAL(self, other):

908# '''(INTERNAL) Copy C{other._RESIDUAL}.

909# '''

910# R = other._RESIDUAL

911# if R is not Fsum._RESIDUAL:

912# self._RESIDUAL = R

913

914 divmod = __divmod__

915

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

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

918 '''

919 return Error(_SPACE_(self.as_iscalar, op, other), **txt_cause)

920

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

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

923 '''

924 E, t = _xError2(X)

925 if mod:

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

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

928

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

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

931 '''

932 E, t = _xError2(X)

933 u = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)

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

935

936 def _facc(self, xs, up=True, **origin_X_x):

937 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s.

938 '''

939 if xs:

940 _xs = _2floats(xs, **origin_X_x) # PYCHOK yield

941 ps = self._ps

942 ps[:] = self._ps_acc(list(ps), _xs, up=up)

943 return self

944

945 def _facc_1(self, xs, **up):

946 '''(INTERNAL) Accumulate 0, 1 or more C{scalars} or L{Fsum}s,

947 all positional C{xs} in the caller of this method.

948 '''

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

950 self._facc(xs, origin=1, **up)

951

952 def _facc_inplace(self, other, op, _facc):

953 '''(INTERNAL) Accumulate from an iterable.

954 '''

955 try:

956 return _facc(other, origin=1) if _xiterable(other) else self

957 except Exception as X:

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

959

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

961 '''(INTERNAL) Accumulate more C{scalars} or L{Fsum}s, negated.

962 '''

963 def _N(X):

964 return X._ps_neg

965

966 def _n(x):

967 return -float(x)

968

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

970

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

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

973 '''

974 def _Pow4(p):

975 r = 0

976 if _isFsumTuple(p):

977 s, r = p._fprs2

978 if r:

979 m = Fsum._pow

980 else: # scalar

981 return _Pow4(s)

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

983 p = s = int(p)

984 m = Fsum._pow_int

985 else:

986 p = s = _2float(power=p)

987 m = Fsum._pow_scalar

988 return m, p, s, r

989

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

991 if p: # and xs:

992 op = which.__name__

993 _flt = float

994 _Fs = Fsum

995 _isa = isinstance

996 _pow = self._pow_2_3

997

998 def _P(X):

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

1000 return f._ps if _isa(f, _Fs) else (f,)

1001

1002 def _p(x):

1003 x = _flt(x)

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

1005 if f and r:

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

1007 return f

1008

1009 f = self._facc(xs, origin=1, _X=_P, _x=_p)

1010 else:

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

1012 return f

1013

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

1015 '''(INTERNAL) Accumulate all C{xs}, known to be scalar.

1016 '''

1017 if xs:

1018 _ = self._ps_acc(self._ps, xs, **up)

1019 return self

1020

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

1022 '''(INTERNAL) Accumulate all positional C{xs}, known to be scalar.

1023 '''

1024 if xs:

1025 _ = self._ps_acc(self._ps, xs, **up)

1026 return self

1027

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

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

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

1031# '''

1032# ps = self._ps

1033# while len(ps) > 1:

1034# p = ps.pop()

1035# if p:

1036# n = self._n

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

1038# self._n = n

1039# break

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

1041

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

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

1044

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

1046 or an L{Fsum} or L{Fsum2Tuple} instance).

1047

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

1049

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

1051

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

1053

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

1055 '''

1056 if _isFsumTuple(xs):

1057 self._facc_scalar(xs._ps)

1058 elif isscalar(xs): # for backward compatibility

1059 self._facc_scalar_(_2float(x=xs)) # PYCHOK no cover

1060 elif xs: # _xiterable(xs)

1061 self._facc(xs)

1062 return self

1063

1064 def fadd_(self, *xs):

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

1066

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

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

1069

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

1071 '''

1072 return self._facc_1(xs)

1073

1074 def _fadd(self, other, op, **up): # in .fmath.Fhorner

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

1076 '''

1077 if not self._ps: # new Fsum(x)

1078 self._fset(other, op=op, **up)

1079 elif _isFsumTuple(other):

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

1081 elif self._scalar(other, op):

1082 self._facc_scalar_(other, **up)

1083 return self

1084

1085 fcopy = copy # for backward compatibility

1086 fdiv = __itruediv__

1087 fdivmod = __divmod__

1088

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

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

1091 '''

1092 # result mostly follows CPython function U{float_divmod

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

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

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

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

1097 self -= Fsum(q) * other # NOT other * q!

1098

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

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

1101 self += other

1102 q -= 1

1103# t = self.signOf()

1104# if t and t != s:

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

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

1107

1108 def _fhorner(self, x, cs, op): # in .fmath

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

1110 M{sum(cs[i] * x**i for i=0..len(cs)-1)}.

1111 '''

1112 if _xiterablen(cs):

1113 H = Fsum(name__=self._fhorner)

1114 if _isFsumTuple(x):

1115 _mul = H._mul_Fsum

1116 else:

1117 _mul = H._mul_scalar

1118 x = _2float(x=x)

1119 if len(cs) > 1 and x:

1120 for c in reversed(cs):

1121 H._fset_ps(_mul(x, op))

1122 H._fadd(c, op, up=False)

1123 else: # x == 0

1124 H = cs[0]

1125 self._fadd(H, op)

1126 return self

1127

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

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

1130 '''

1131 if _isfinite(other):

1132 return other

1133 raise ValueError(_not_finite_) if op is None else \

1134 self._Error(op, other, _ValueError, txt=_not_finite_)

1135

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

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

1138

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

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

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

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

1143

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

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

1146

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

1148 B{C{RESIDUAL}}.

1149

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

1151 '''

1152 i, r = self._fint2

1153 if r:

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

1155 if R:

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

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

1158 return _Psum_(i, name=_name__(name, name__=self.fint))

1159

1160 def fint2(self, **name):

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

1162 I{integer} residual.

1163

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

1165

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

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

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

1169 '''

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

1171

1172 @Property

1173 def _fint2(self): # see ._fset

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

1175 '''

1176 s, r = self._fprs2

1177 i = int(s)

1178 n = len(self._ps)

1179 r = self._ps_1sum(i) if r and n > 1 else float(s - i)

1180 return i, (r or INT0) # Fsum2Tuple?

1181

1182 @_fint2.setter_ # PYCHOK setter_underscore!

1183 def _fint2(self, s):

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

1185 '''

1186 i = int(s)

1187 return i, ((s - i) or INT0)

1188

1189 @deprecated_property_RO

1190 def float_int(self): # PYCHOK no cover

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

1192 return self.int_float() # raiser=False

1193

1194 @property_RO

1195 def floor(self):

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

1197 C{float} in Python 2-).

1198

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

1200

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

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

1203 '''

1204 s, r = self._fprs2

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

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

1207 f -= 1

1208 return f # _floor(self._n_d)

1209

1210# ffloordiv = __ifloordiv__ # for naming consistency

1211# floordiv = __floordiv__ # for naming consistency

1212

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

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

1215 '''

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

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

1218

1219 fmul = __imul__

1220

1221 def _fmul(self, other, op):

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

1223 '''

1224 if _isFsumTuple(other):

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

1226 f = self._mul_Fsum(other, op)

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

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

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

1230 f = self._finite(self._ps[0] * other._ps[0])

1231 else:

1232 s = self._scalar(other, op)

1233 f = self._mul_scalar(s, op)

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

1235

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

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

1238

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

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

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

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

1243

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

1245

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

1247 B{C{RESIDUAL}}.

1248

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

1250 '''

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

1252

1253 fpow = __ipow__

1254

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

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

1257 '''

1258 if mod:

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

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

1261 elif self.is_integer():

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

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

1264 x, r = _2scalar2(other) # C{int}, C{float} or other

1265 f = _Psum_(i)._pow_Fsum(other, op, **raiser_RESIDUAL) if r else \

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

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

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

1269 else: # pow(self, other)

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

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

1272

1273 @Property

1274 def _fprs(self):

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

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

1277

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

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

1280 '''

1281 s, _ = self._fprs2

1282 return s # ._fprs2.fsum

1283

1284 @_fprs.setter_ # PYCHOK setter_underscore!

1285 def _fprs(self, s):

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

1287 '''

1288 return s

1289

1290 @Property

1291 def _fprs2(self):

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

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

1294 '''

1295 ps = self._ps

1296 n = len(ps) - 2

1297 if n > 0: # len(ps) > 2

1298 s = _psum(ps)

1299 n = len(ps) - 2

1300 if n > 0:

1301 r = self._ps_1sum(s)

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

1303 if n == 0: # len(ps) == 2

1304 s, r = _s_r(*_2sum(*ps))

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

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

1307 s, r = ps[0], INT0

1308 else: # len(ps) == 0

1309 s, r = _0_0, INT0

1310 ps[:] = s,

1311 # assert self._ps is ps

1312 return Fsum2Tuple(s, r)

1313

1314 @_fprs2.setter_ # PYCHOK setter_underscore!

1315 def _fprs2(self, s_r):

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

1317 '''

1318 return Fsum2Tuple(s_r)

1319

1320 def fset_(self, *xs):

1321 '''Replace this instance' value with all positional items.

1322

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

1324 an L{Fsum} or L{Fsum2Tuple} instance),

1325 all positional.

1326

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

1328

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

1330 '''

1331 f = xs[0] if len(xs) == 1 else (

1332 Fsum(*xs) if xs else _0_0)

1333 return self._fset(f)

1334

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

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

1337 '''

1338 if other is self:

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

1340 elif _isFsumTuple(other):

1341 self._ps[:] = other._ps

1342 self._n = n or other._n

1343# self._copy_RESIDUAL(other)

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

1345 Fsum._fint2._update_from(self, other)

1346 Fsum._fprs ._update_from(self, other)

1347 Fsum._fprs2._update_from(self, other)

1348 elif isscalar(other):

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

1350 self._ps[:] = s,

1351 self._n = n or 1

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

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

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

1355 self._fint2 = s

1356 self._fprs = s

1357 self._fprs2 = s, INT0

1358 # assert self._fprs is s

1359 else: # PYCHOK no cover

1360 op = _xkwds_get1(op, op=_fset_op_)

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

1362 return self

1363

1364 def _fset_ps(self, other): # in .fmath

1365 '''(INTERNAL) Set partials from a known C{scalar}, L{Fsum} or L{Fsum2Tuple}.

1366 '''

1367 return self._fset(other, up=False)

1368

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

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

1371

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

1373 '''

1374 return self._facc_neg(xs)

1375

1376 def fsub_(self, *xs):

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

1378

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

1380 '''

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

1382 self._facc_neg(xs, origin=1)

1383

1384 def _fsub(self, other, op):

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

1386 '''

1387 if _isFsumTuple(other):

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

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

1390 elif other._ps:

1391 self._facc_scalar(other._ps_neg)

1392 elif self._scalar(other, op):

1393 self._facc_scalar_(-other)

1394 return self

1395

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

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

1398 current precision running sum.

1399

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

1401 or an L{Fsum} or L{Fsum2Tuple} instance).

1402

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

1404

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

1406

1407 @note: Accumulation can continue after summation.

1408 '''

1409 return self._facc(xs)._fprs

1410

1411 def fsum_(self, *xs):

1412 '''Add any positional items, summate and return the

1413 current precision running sum.

1414

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

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

1417

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

1419

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

1421 '''

1422 return self._facc_1(xs)._fprs

1423

1424 @property_RO

1425 def _Fsum(self): # like L{Fsum2Tuple._Fsum}, for C{_2floats}, .fstats

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

1427

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

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

1430

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

1432

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

1434 '''

1435 return self._facc_1(xs)._copy_2(self.Fsum_, **name)

1436

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

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

1439

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

1441

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

1443 '''

1444 return Fsum2Tuple(self._facc_1(xs)._fprs2, **name)

1445

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

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

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

1449

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

1451 or an L{Fsum} or L{Fsum2Tuple} instance).

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

1453

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

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

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

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

1458 to be I{exact}.

1459

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

1461 '''

1462 t = self._facc(xs)._fprs2

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

1464

1465 def fsum2_(self, *xs):

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

1467 precision running sum and the I{differential}.

1468

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

1470 L{Fsum2Tuple} instance), all positional.

1471

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

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

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

1475

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

1477 '''

1478 return self._fsum2(xs, self._facc_1)

1479

1480 def _fsum2(self, xs, _facc, **origin):

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

1482 '''

1483 p, q = self._fprs2

1484 if xs:

1485 s, r = _facc(xs, **origin)._fprs2

1486 return s, _2delta(s - p, r - q) # _fsum(_1primed((s, -p, r, -q))

1487 else:

1488 return p, _0_0

1489

1490 def fsumf_(self, *xs):

1491 '''Like method L{Fsum.fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.

1492 '''

1493 return self._facc_scalar(xs)._fprs

1494

1495 def Fsumf_(self, *xs):

1496 '''Like method L{Fsum.Fsum_} iff I{all} C{B{xs}} are I{known to be scalar}.

1497 '''

1498 return self._facc_scalar(xs)._copy_2(self.Fsumf_)

1499

1500 def fsum2f_(self, *xs):

1501 '''Like method L{Fsum.fsum2_} iff I{all} C{B{xs}} are I{known to be scalar}.

1502 '''

1503 return self._fsum2(xs, self._facc_scalar, origin=1)

1504

1505# ftruediv = __itruediv__ # for naming consistency?

1506

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

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

1509 '''

1510 n = _1_0

1511 if _isFsumTuple(other):

1512 if other is self or self == other:

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

1514 d, r = other._fprs2

1515 if r:

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

1517 if R:

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

1519 d, n = other.as_integer_ratio()

1520 else:

1521 d = self._scalar(other, op)

1522 try:

1523 s = n / d

1524 except Exception as X:

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

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

1527 return self._fset(f)

1528

1529 @property_RO

1530 def imag(self):

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

1532

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

1534 '''

1535 return _0_0

1536

1537 def int_float(self, **raiser_RESIDUAL):

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

1539

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

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

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

1543

1544 @return: This C{integer} sum if this instance C{is_integer},

1545 otherwise return the C{float} sum if the residual is

1546 zero or not significant.

1547

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

1549 B{C{RESIDUAL}}.

1550

1551 @see: Methods L{Fsum.fint}, L{Fsum.fint2}, L{Fsum.RESIDUAL} and

1552 property L{Fsum.as_iscalar}.

1553 '''

1554 s, r = self._fint2

1555 if r:

1556 s, r = self._fprs2

1557 if r: # PYCHOK no cover

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

1559 if R:

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

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

1562 s = float(s)

1563 return s

1564

1565 def is_exact(self):

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

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

1568 '''

1569 return self.residual is INT0

1570

1571 def is_integer(self):

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

1573

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

1575 '''

1576 _, r = self._fint2

1577 return False if r else True

1578

1579 def is_math_fsum(self):

1580 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and

1581 L{fsum1_} plus partials summation are based on Python's

1582 C{math.fsum} or not.

1583

1584 @return: C{2} if all functions and partials summation

1585 are based on C{math.fsum}, C{True} if only

1586 the functions are based on C{math.fsum} (and

1587 partials summation is not) or C{False} if

1588 none are.

1589 '''

1590 f = Fsum._math_fsum

1591 return 2 if _psum is f else bool(f)

1592

1593 def is_scalar(self, **raiser_RESIDUAL):

1594 '''Is this instance' running sum C{scalar} without residual or with

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

1596

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

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

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

1600

1601 @return: C{True} if this instance' non-zero residual C{ratio} exceeds

1602 the L{RESIDUAL<Fsum.RESIDUAL>} threshold (C{bool}).

1603

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

1605 B{C{RESIDUAL}}.

1606

1607 @see: Method L{Fsum.RESIDUAL}, L{Fsum.is_integer} and property

1608 L{Fsum.as_iscalar}.

1609 '''

1610 s, r = self._fprs2

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

1612

1613 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner

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

1615 '''

1616 # assert _isFsumTuple(other)

1617 if self._ps and other._ps:

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

1619 else:

1620 f = _0_0

1621 return f

1622

1623 def _mul_scalar(self, factor, op): # in .fmath.Fhorner

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

1625 '''

1626 # assert isscalar(factor)

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

1628 f = self if factor == _1_0 else (

1629 self._neg if factor == _N_1_0 else

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

1631 else:

1632 f = _0_0

1633 return f

1634

1635# @property_RO

1636# def _n_d(self):

1637# n, d = self.as_integer_ratio()

1638# return n / d

1639

1640 @property_RO

1641 def _neg(self):

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

1643 '''

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

1645

1646 @property_RO

1647 def partials(self):

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

1649 '''

1650 return tuple(self._ps)

1651

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

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

1654

1655 @arg x: The exponent (C{scalar} or L{Fsum}).

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

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

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

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

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

1661

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

1663 result (L{Fsum}).

1664

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

1666 B{C{RESIDUAL}}.

1667

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

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

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

1671

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

1673 and L{Fsum.root}.

1674 '''

1675 f = self._copy_2(self.pow)

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

1677

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

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

1680 '''

1681 if _isFsumTuple(other):

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

1683 elif self._scalar(other, op):

1684 x = self._finite(other, op)

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

1686 else:

1687 f = self._pow_0_1(0, other)

1688 return f

1689

1690 def _pow_0_1(self, x, other):

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

1692 '''

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

1694

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

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

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

1698 '''

1699

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

1701 m = mod[0]

1702 # assert _isFsumTuple(b)

1703

1704 def _s(s, r):

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

1706 if R:

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

1708 return s

1709

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

1711 x = _s(*_2scalar2(x))

1712

1713 try:

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

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

1716 if iscomplex(s):

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

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

1719 return self._finite(s)

1720 except Exception as X:

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

1722

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

1724 '''(INTERNAL) Return C{B{self} **= B{other}} for C{_isFsumTuple(other)}.

1725 '''

1726 # assert _isFsumTuple(other)

1727 x, r = other._fprs2

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

1729 if f and r:

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

1731 return f

1732

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

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

1735 '''

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

1737 ps = self._ps

1738 if len(ps) > 1:

1739 _mul_Fsum = Fsum._mul_Fsum

1740 if x > 4:

1741 p = self

1742 f = self if (x & 1) else _Psum_(_1_0)

1743 m = x >> 1 # // 2

1744 while m:

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

1746 if (m & 1):

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

1748 m >>= 1 # //= 2

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

1750 f = _mul_Fsum(self, self, op)

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

1752 p = self if x < 4 else f

1753 f = _mul_Fsum(f, p, op)

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

1755 f = self._pow_0_1(x, other)

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

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

1758 else: # PYCHOK no cover

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

1760 f = 0 if x else 1

1761 return f

1762

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

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

1765 '''

1766 s, r = self._fprs2

1767 if r:

1768 # assert s != 0

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

1770 x = int(x)

1771 y = abs(x)

1772 if y > 1:

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

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

1775 return f # Fsum or scalar

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

1777 if _isFsum(f):

1778 s, r = f._fprs2

1779 if r:

1780 return _1_Over(f, op, **raiser_RESIDUAL)

1781 else: # scalar

1782 s = f

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

1784 # float_pow error iff s is zero

1785 x = -1

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

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

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

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

1790 else: # self**fractional

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

1792 if R:

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

1794 n, d = self.as_integer_ratio()

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

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

1797 s = n / d

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

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

1800

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

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

1803 '''

1804 n = 0

1805 _2s = _2sum

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

1807 # assert isscalar(x) and _isfinite(x)

1808 if x:

1809 i = 0

1810 for p in ps:

1811 x, p = _2s(x, p)

1812 if p:

1813 ps[i] = p

1814 i += 1

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

1816 n += 1

1817 if n:

1818 self._n += n

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

1820 if up:

1821 self._update()

1822 return ps

1823

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

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

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

1827 '''

1828 def _pfs(ps, fs):

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

1830 ps, fs = fs, ps

1831 _fin = _isfinite

1832 for f in fs:

1833 for p in ps:

1834 p *= f

1835 yield p if _fin(p) else self._finite(p, op)

1836

1837 return Fsum()._facc_scalar(_pfs(self._ps, factors), up=False)

1838

1839 @property_RO

1840 def _ps_neg(self):

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

1842 '''

1843 for p in self._ps:

1844 yield -p

1845

1846 def _ps_1sum(self, *less):

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

1848 '''

1849 def _1pls(ps, ls):

1850 yield _1_0

1851 for p in ps:

1852 yield p

1853 for p in ls:

1854 yield -p

1855 yield _N_1_0

1856

1857 return _fsum(_1pls(self._ps, less))

1858

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

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

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

1862 negative respectively positive C{RESIDUAL} threshold)?

1863 '''

1864 if r and raiser:

1865 t = self._RESIDUAL

1866 if RESIDUAL:

1867 t = _threshold(t, **RESIDUAL)

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

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

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

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

1872 return {}

1873

1874 rdiv = __rtruediv__

1875

1876 @property_RO

1877 def real(self):

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

1879

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

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

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

1883 '''

1884 return float(self._fprs)

1885

1886 @property_RO

1887 def residual(self):

1888 '''Get this instance' residual (C{float} or C{int}): the

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

1890

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

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

1893

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

1895 '''

1896 return self._fprs2.residual

1897

1898 def RESIDUAL(self, *threshold):

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

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

1901

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

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

1904 C{None} restore the default set with env variable

1905 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

1906 current setting.

1907

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

1909

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

1911

1912 @note: L{ResidualError}s may be thrown if the non-zero I{ratio}

1913 C{residual / fsum} exceeds the given B{C{threshold}} and

1914 if the C{residual} is non-zero and I{significant} vs the

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

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

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

1918 testing without I{significant}.

1919 '''

1920 r = self._RESIDUAL

1921 if threshold:

1922 t = threshold[0]

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

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

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

1926 return r

1927

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

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

1930 '''

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

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

1933 if mod is None else _integer_

1934

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

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

1937

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

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

1940

1941 @arg root: The order (C{scalar} or L{Fsum}), non-zero.

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

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

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

1945

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

1947

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

1949 B{C{RESIDUAL}}.

1950

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

1952 '''

1953 x = _1_Over(root, _truediv_op_, **raiser_RESIDUAL)

1954 f = self._copy_2(self.root)

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

1956

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

1958 '''(INTERNAL) Return scalar C{other}.

1959 '''

1960 if isscalar(other):

1961 return other

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

1963

1964 def signOf(self, res=True):

1965 '''Determine the sign of this instance.

1966

1967 @kwarg res: If C{True} consider, otherwise

1968 ignore the residual (C{bool}).

1969

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

1971 '''

1972 s, r = self._fprs2

1973 r = (-r) if res else 0

1974 return _signOf(s, r)

1975

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

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

1978

1979 @kwarg lenc_prec_sep_fmt: Optional keyword arguments

1980 for method L{Fsum.toStr}.

1981

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

1983 '''

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

1985

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

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

1988

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

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

1991 @kwarg prec_sep_fmt: Optional keyword arguments for method

1992 L{Fsum2Tuple.toStr}.

1993

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

1995 '''

1996 p = self.classname

1997 if lenc:

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

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

2000 t = self._fprs2.toStr(**prec_sep_fmt)

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

2002

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

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

2005 '''

2006 f = self._copy_2(self.__truediv__)

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

2008

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

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

2011 '''

2012 if updated:

2013 _pop = self.__dict__.pop

2014 for p in _ROs:

2015 _ = _pop(p, None)

2016# Fsum._fint2._update(self)

2017# Fsum._fprs ._update(self)

2018# Fsum._fprs2._update(self)

2019 return self # for .fset_

2020

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

2022

2023

2024 def _Float_Int(arg, **name_Error):

2025 '''(INTERNAL) Unit of L{Fsum2Tuple} items.

2026 '''

2027 U = Int if isint(arg) else Float

2028 return U(arg, **name_Error)

2029

2030

2031 class DivMod2Tuple(_NamedTuple):

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

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

2034

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

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

2037 '''

2038 _Names_ = (_div_, _mod_)

2039 _Units_ = (_Float_Int, Fsum)

2040

2041

2042 class Fsum2Tuple(_NamedTuple): # in .fstats

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

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

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

2046

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

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

2049 '''

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

2051 _Units_ = (_Float_Int, _Float_Int)

2052

2053 def __abs__(self): # in .fmath

2054 return self._Fsum.__abs__()

2055

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

2057 return bool(self._Fsum)

2058

2059 def __eq__(self, other):

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

2061

2062 def __float__(self):

2063 return self._Fsum.__float__()

2064

2065 def __ge__(self, other):

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

2067

2068 def __gt__(self, other):

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

2070

2071 def __le__(self, other):

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

2073

2074 def __lt__(self, other):

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

2076

2077 def __int__(self):

2078 return self._Fsum.__int__()

2079

2080 def __ne__(self, other):

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

2082

2083 def __neg__(self):

2084 return self._Fsum.__neg__()

2085

2086 __nonzero__ = __bool__ # Python 2-

2087

2088 def __pos__(self):

2089 return self._Fsum.__pos__()

2090

2091 def as_integer_ratio(self):

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

2093

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

2095 '''

2096 return self._Fsum.as_integer_ratio()

2097

2098 @property_RO

2099 def _fint2(self):

2100 return self._Fsum._fint2

2101

2102 @property_RO

2103 def _fprs2(self):

2104 return self._Fsum._fprs2

2105

2106 @Property_RO

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

2108 s, r = _s_r(*self)

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

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

2111

2112 def Fsum_(self, *xs, **name_RESIDUAL):

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

2114 '''

2115 f = _Psum(self._Fsum._ps, **name_RESIDUAL)

2116 return f._facc_1(xs, up=False) if xs else f

2117

2118 def is_exact(self):

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

2120 '''

2121 return self._Fsum.is_exact()

2122

2123 def is_integer(self):

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

2125 '''

2126 return self._Fsum.is_integer()

2127

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

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

2130

2131 @property_RO

2132 def _n(self):

2133 return self._Fsum._n

2134

2135 def _other_op(self, other, which):

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

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

2138

2139 @property_RO

2140 def _ps(self):

2141 return self._Fsum._ps

2142

2143 @property_RO

2144 def _ps_neg(self):

2145 return self._Fsum._ps_neg

2146

2147 def signOf(self, **res):

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

2149 '''

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

2151

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

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

2154

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

2156 @kwarg prec_sep: Optional keyword arguments for function

2157 L{fstr<streprs.fstr>}.

2158 '''

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

2160

2161_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines

2162

2163

2164 class ResidualError(_ValueError):

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

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

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

2168

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

2170 '''

2171 pass

2172

2173

2174 try:

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

2176

2177 # make sure _fsum works as expected (XXX check

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

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

2180 del _fsum # nope, remove _fsum ...

2181 raise ImportError # ... use _fsum below

2182

2183 Fsum._math_fsum = _sum = _fsum # PYCHOK exported

2184 except ImportError:

2185 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic

2186

2187 def _fsum(xs):

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

2189 '''

2190 F = Fsum()

2191 F.name = _fsum.__name__

2192 return F._facc(xs, up=False)._fprs2.fsum

2193

2194

2195 def fsum(xs, floats=False):

2196 '''Precision floating point summation based on/like Python's C{math.fsum}.

2197

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

2199 instance).

2200 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2201 be scalar} (C{bool}).

2202

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

2204

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

2206

2207 @raise TypeError: Non-scalar B{C{xs}} item.

2208

2209 @raise ValueError: Invalid or non-finite B{C{xs}} item.

2210

2211 @note: Exception and I{non-finite} handling may differ if not based

2212 on Python's C{math.fsum}.

2213

2214 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.

2215 '''

2216 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield

2217

2218

2219 def fsum_(*xs, **floats):

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

2221

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

2223 all positional.

2224 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2225 be scalar} (C{bool}).

2226

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

2228 '''

2229 return _fsum(xs if _xkwds_get1(floats, floats=False) is True else

2230 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield

2231

2232

2233 def fsumf_(*xs):

2234 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.

2235

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

2237 '''

2238 return _fsum(xs) if xs else _0_0

2239

2240

2241 def fsum1(xs, floats=False):

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

2243

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

2245 instance).

2246 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2247 be scalar} (C{bool}).

2248

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

2250 '''

2251 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield

2252

2253

2254 def fsum1_(*xs, **floats):

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

2256

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

2258 all positional.

2259 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2260 be scalar} (C{bool}).

2261

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

2263 '''

2264 return _fsum(_1primed(xs if _xkwds_get1(floats, floats=False) is True else

2265 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield

2266

2267

2268 def fsum1f_(*xs):

2269 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.

2270

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

2272 '''

2273 return _fsum(_1primed(xs)) if xs else _0_0

2274

2275

2276 if __name__ == '__main__':

2277

2278 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums

2279

2280 if _getenv(_psum.__name__, NN) == _fsum.__name__:

2281 _psum = _fsum

2282

2283 def _test(n):

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

2285 from pygeodesy import frandoms, printf

2286

2287 printf(_fsum.__name__, end=_COMMASPACE_)

2288 printf(_psum.__name__, end=_COMMASPACE_)

2289

2290 F = Fsum()

2291 if F.is_math_fsum():

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

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

2294 printf(_DOT_, end=NN)

2295 printf(NN)

2296

2297 _test(128)

2298

2299# **) MIT License

2300#

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

2302#

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

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

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

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

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

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

2309#

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

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

2312#

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

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

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

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

2317# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

2318# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

2319# OTHER DEALINGS IN THE SOFTWARE.