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

27 signOf, _signOf

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

29 _0_0, _1_0, _N_1_0, Float, Int

30 from pygeodesy.errors import _OverflowError, _TypeError, _ValueError, \

31 _xError, _xError2, _xkwds_get

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

33 _enquote, _EQUAL_, _from_, _LANGLE_, _NOTEQUAL_, \

34 _not_finite_, _PERCENT_, _PLUS_, _RANGLE_, \

35 _SLASH_, _SPACE_, _STAR_, _UNDER_

36 from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2

37 from pygeodesy.named import _Named, _NamedTuple, _NotImplemented

38 from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \

39 Property_RO, property_RO

40 from pygeodesy.streprs import Fmt, fstr, unstr

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

42

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

44

45__all__ = _ALL_LAZY.fsums

46__version__ = '24.05.08'

47

48_abs = abs

49_add_op_ = _PLUS_ # in .auxilats.auxAngle

50_eq_op_ = _EQUAL_ * 2 # _DEQUAL_

51_div_ = 'div'

52_Float = float # in .fstats

53_floordiv_op_ = _SLASH_ * 2 # _DSLASH_

54_fset_op_ = _EQUAL_

55_ge_op_ = _RANGLE_ + _EQUAL_

56_gt_op_ = _RANGLE_

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

58_integer_ = 'integer'

59_isAn = isinstance # in .fstats

60_le_op_ = _LANGLE_ + _EQUAL_

61_len = len

62_List = list

63_lt_op_ = _LANGLE_

64_mod_ = 'mod'

65_mod_op_ = _PERCENT_

66_mul_op_ = _STAR_

67_ne_op_ = _NOTEQUAL_

68_non_zero_ = 'non-zero'

69_pow_op_ = _STAR_ * 2 # _DSTAR_

70_significant_ = 'significant'

71_sub_op_ = _DASH_ # in .auxilats.auxAngle

72_threshold_ = 'threshold'

73_truediv_op_ = _SLASH_

74_Tuple = tuple # in .fstats

75_divmod_op_ = _floordiv_op_ + _mod_op_

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

77

78

79 def _2delta(*ab):

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

81 '''

82 try:

83 a, b = _2sum(*ab)

84 except _OverflowError:

85 a, b = ab

86 return _Float(a if fabs(a) > fabs(b) else b)

87

88

89 def _2error(unused): # in .fstats

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

91 '''

92 raise ValueError(_not_finite_)

93

94

95 def _2finite(x):

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

97 '''

98 x = _Float(x)

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

100

101

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

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

104 '''

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

106 try:

107 return _2finite(v)

108 except Exception as X:

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

110

111

112 def _X_ps(X): # for _2floats only

113 return X._ps

114

115

116 def _2floats(xs, origin=0, _X=_X_ps, _x=_Float):

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

118 '''

119 try:

120 i, x = origin, None

121 _fin = _isfinite

122 _FsT = _Fsum_Fsum2Tuple_types

123 _is = _isAn

124 for x in xs:

125 if _is(x, _FsT):

126 for p in _X(x._Fsum):

127 yield p

128 else:

129 f = _x(x)

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

131 i += 1

132 except Exception as X:

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

134

135

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

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

138 '''

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

140

141

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

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

144 '''

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

146

147

148 def _2halfeven(s, r, p):

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

150 '''

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

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

153 r *= 2

154 t = s + r

155 if r == (t - s):

156 s = t

157 return s

158

159

160 def _isFsum(x): # in .fmath

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

162 '''

163 return _isAn(x, Fsum)

164

165

166 def _isFsumTuple(x): # in .fmath

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

168 '''

169 return _isAn(x, _Fsum_Fsum2Tuple_types)

170

171

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

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

174 '''

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

176

177

178 def _1primed(xs): # in .fmath

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

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

181 '''

182 yield _1_0

183 for x in xs:

184 yield x

185 yield _N_1_0

186

187

188 def _psum(ps): # PYCHOK used!

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

190 '''

191 # assert _isAn(ps, _List)

192 i = _len(ps) - 1

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

194 _2s = _2sum

195 while i > 0:

196 i -= 1

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

198 if r: # sum(ps) became inexact

199 if s:

200 ps[i:] = r, s

201 if i > 0:

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

203 break # return s

204 s = r # PYCHOK no cover

205 ps[i:] = s,

206 return s

207

208

209 def _Psum(ps, **name_RESIDUAL):

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

211 '''

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

213 if ps:

214 f._ps[:] = ps

215 f._n = _len(f._ps)

216 return f

217

218

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

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

221 '''

222 return _Psum(ps, **name_RESIDUAL)

223

224

225 def _2scalar2(other):

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

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

228 '''

229 if _isFsumTuple(other):

230 s, r = other._fint2

231 if r:

232 s, r = other._fprs2

233 if r: # PYCHOK no cover

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

235 else:

236 r = 0

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

238 if isint(s, both=True):

239 s = int(s)

240 return s, r

241

242

243 def _s_r(s, r):

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

245 '''

246 if r:

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

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

249 else:

250 r = INT0

251 return s, r

252

253

254 def _strcomplex(s, *args):

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

256 '''

257 c = _strcomplex.__name__[4:]

258 n = _DASH_(_len(args), _arg_)

259 t = unstr(pow, *args)

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

261

262

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

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

265 '''

266 p = _stresidual.__name__[3:]

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

268 for n, v in itemsorted(mod_ratio):

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

270 t = _COMMASPACE_(t, p)

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

272

273

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

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

276 '''

277 s = a + b

278 if _isfinite(s):

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

280 b, a = a, b

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

282 u = unstr(_2sum, a, b)

283 t = Fmt.PARENSPACED(_not_finite_, s)

284 raise _OverflowError(u, txt=t)

285

286

287 def _threshold(threshold):

288 '''(INTERNAL) Get the L{ResidualError}s threshold.

289 '''

290 try:

291 t = _Float(threshold) or _0_0

292 return t if _isfinite(t) else _2error(t) # PYCHOK None

293 except Exception as x:

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

295

296

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

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

299

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

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

302 intermediate, I{running} summuation.

303

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

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

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

307

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

309 Python's C{math.fsum}.

310

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

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

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

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

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

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

317 '''

318 _math_fsum = None

319 _n = 0

320# _ps = [] # partial sums

321# _ps_max = 0 # max(Fsum._ps_max, _len(Fsum._ps))

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

323

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

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

326

327 @arg xs: No, one or more items to add (each C{scalar} or an L{Fsum}

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

329 @kwarg name_RESIDUAL: Optional C{B{name}=NN} for this L{Fsum} and

330 the C{B{RESIDUAL}=0.0} threshold for L{ResidualError}s.

331

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

333 '''

334 if name_RESIDUAL:

335

336 def _n_R(name=NN, RESIDUAL=None):

337 return name, RESIDUAL

338

339 n, R = _n_R(**name_RESIDUAL)

340 if R is not None:

341 self.RESIDUAL(R)

342 if n:

343 self.name = n

344

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

346 if xs:

347 self._facc_1(xs, up=False)

348

349 def __abs__(self):

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

351 '''

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

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

354

355 def __add__(self, other):

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

357

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

359

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

361

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

363 '''

364 f = self._copy_2(self.__add__)

365 return f._fadd(other, _add_op_)

366

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

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

369 '''

370 s, r = self._fprs2

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

372

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

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

375

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

377

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

379 '''

380 return self.ceil

381

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

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

384

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

386

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

388 '''

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

390 return _signOf(s, 0)

391

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

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

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

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

396

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

398 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

399 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

400 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

401

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

403 B{C{RESIDUAL}}.

404

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

406 '''

407 f = self._copy_2(self.__divmod__)

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

409

410 def __eq__(self, other):

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

412 '''

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

414

415 def __float__(self):

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

417

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

419 '''

420 return _Float(self._fprs)

421

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

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

424

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

426

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

428 '''

429 return self.floor

430

431 def __floordiv__(self, other):

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

433

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

435

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

437

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

439 '''

440 f = self._copy_2(self.__floordiv__)

441 return f._floordiv(other, _floordiv_op_)

442

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

444 '''Not implemented.'''

445 return _NotImplemented(self, *other)

446

447 def __ge__(self, other):

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

449 '''

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

451

452 def __gt__(self, other):

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

454 '''

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

456

457 def __hash__(self): # PYCHOK no cover

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

459 '''

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

461

462 def __iadd__(self, other):

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

464

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

466

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

468

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

470 C{scalar} nor L{Fsum}.

471

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

473 '''

474 return self._fadd(other, _iadd_op_)

475

476 def __ifloordiv__(self, other):

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

478

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

480

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

482

483 @raise ResidualError: Non-zero, significant residual

484 in B{C{other}}.

485

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

487

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

489

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

491

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

493 '''

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

495

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

497 '''Not implemented.'''

498 return _NotImplemented(self, other)

499

500 def __imod__(self, other):

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

502

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

504

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

506

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

508 '''

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

510

511 def __imul__(self, other):

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

513

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

515

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

517

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

519

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

521

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

523 '''

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

525

526 def __int__(self):

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

528

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

530 and L{Fsum.floor}.

531 '''

532 i, _ = self._fint2

533 return i

534

535 def __invert__(self): # PYCHOK no cover

536 '''Not implemented.'''

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

538 return _NotImplemented(self)

539

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

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

542

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

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

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

546 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

547 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

548 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

549

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

551

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

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

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

555

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

557

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

559 is non-zero and significant and either

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

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

562 C{None}.

563

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

565 invocation failed.

566

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

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

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

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

571 is given as C{0}.

572

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

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

575 '''

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

577

578 def __isub__(self, other):

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

580

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

582

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

584

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

586

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

588 '''

589 return self._fsub(other, _isub_op_)

590

591 def __iter__(self):

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

593 '''

594 return iter(self.partials)

595

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

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

598

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

600 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

601 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

602 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

603

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

605

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

607

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

609 B{C{RESIDUAL}}.

610

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

612

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

614

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

616

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

618 '''

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

620

621 def __le__(self, other):

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

623 '''

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

625

626 def __len__(self):

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

628 '''

629 return self._n

630

631 def __lt__(self, other):

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

633 '''

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

635

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

637 '''Not implemented.'''

638 return _NotImplemented(self, other)

639

640 def __mod__(self, other):

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

642

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

644 '''

645 f = self._copy_2(self.__mod__)

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

647

648 def __mul__(self, other):

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

650

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

652 '''

653 f = self._copy_2(self.__mul__)

654 return f._fmul(other, _mul_op_)

655

656 def __ne__(self, other):

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

658 '''

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

660

661 def __neg__(self):

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

663 '''

664 f = self._copy_2(self.__neg__)

665 return f._fset(self._neg)

666

667 def __pos__(self):

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

669 '''

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

671

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

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

674

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

676 '''

677 f = self._copy_2(self.__pow__)

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

679

680 def __radd__(self, other):

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

682

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

684 '''

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

686 return f._fadd(self, _add_op_)

687

688 def __rdivmod__(self, other):

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

690 C{(quotient, remainder)}.

691

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

693 '''

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

695 return f._fdivmod2(self, _divmod_op_)

696

697# def __repr__(self):

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

699# '''

700# return self.toRepr(lenc=True)

701

702 def __rfloordiv__(self, other):

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

704

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

706 '''

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

708 return f._floordiv(self, _floordiv_op_)

709

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

711 '''Not implemented.'''

712 return _NotImplemented(self, other)

713

714 def __rmod__(self, other):

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

716

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

718 '''

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

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

721

722 def __rmul__(self, other):

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

724

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

726 '''

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

728 return f._fmul(self, _mul_op_)

729

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

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

732

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

734 '''

735 f = self._copy_2(self.__round__)

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

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

738

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

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

741

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

743 '''

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

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

746

747 def __rsub__(self, other):

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

749

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

751 '''

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

753 return f._fsub(self, _sub_op_)

754

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

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

757

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

759 '''

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

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

762

763 def __str__(self):

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

765 '''

766 return self.toStr(lenc=True)

767

768 def __sub__(self, other):

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

770

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

772

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

774

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

776 '''

777 f = self._copy_2(self.__sub__)

778 return f._fsub(other, _sub_op_)

779

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

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

782

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

784 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

785 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

786 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

787

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

789

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

791 B{C{RESIDUAL}}.

792

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

794 '''

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

796

797 __trunc__ = __int__

798

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

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

801 __div__ = __truediv__

802 __idiv__ = __itruediv__

803 __long__ = __int__

804 __nonzero__ = __bool__

805 __rdiv__ = __rtruediv__

806

807 def as_integer_ratio(self):

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

809

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

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

812 non-zero, positive.

813

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

815 '''

816 n, r = self._fint2

817 if r:

818 i, d = _Float(r).as_integer_ratio()

819 n *= d

820 n += i

821 else: # PYCHOK no cover

822 d = 1

823 return n, d

824

825 @property_RO

826 def as_iscalar(self):

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

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

829 '''

830 s, r = self._fprs2

831 return self if r else s

832

833 @property_RO

834 def ceil(self):

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

836 C{float} in Python 2-).

837

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

839

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

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

842 '''

843 s, r = self._fprs2

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

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

846 c += 1

847 return c # _ceil(self._n_d)

848

849 cmp = __cmp__

850

851 def _cmp_0(self, other, op):

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

853 '''

854 if _isFsumTuple(other):

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

856 elif self._scalar(other, op):

857 s = self._ps_1sum(other)

858 else:

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

860 return s

861

862 def copy(self, deep=False, name=NN):

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

864

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

866 '''

867 f = _Named.copy(self, deep=deep, name=name)

868 if f._ps is self._ps:

869 f._ps = _List(self._ps) # separate list

870 if not deep:

871 f._n = 1

872 # assert f._Fsum is f

873 return f

874

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

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

877 '''

878 n = name or which.__name__

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

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

881 f._ps = _List(self._ps) # separate list

882 # assert f._n == self._n

883 # assert f._Fsum is f

884 return f

885

886 def _copy_2r(self, other, which):

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

888 '''

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

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

891

892# def _copy_RESIDUAL(self, other):

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

894# '''

895# R = other._RESIDUAL

896# if R is not Fsum._RESIDUAL:

897# self._RESIDUAL = R

898

899 divmod = __divmod__

900

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

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

903 '''

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

905

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

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

908 '''

909 E, t = _xError2(X)

910 if mod:

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

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

913

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

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

916 '''

917 E, t = _xError2(X)

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

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

920

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

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

923 '''

924 if xs:

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

926 ps = self._ps

927 ps[:] = self._ps_acc(_List(ps), _xs, up=up)

928 return self

929

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

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

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

933 '''

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

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

936

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

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

939 '''

940 def _N(X):

941 return X._ps_neg

942

943 def _n(x):

944 return -_Float(x)

945

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

947

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

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

950 '''

951 def _Pow4(p):

952 r = 0

953 if _isFsumTuple(p):

954 s, r = p._fprs2

955 if r:

956 m = Fsum._pow

957 else: # scalar

958 return _Pow4(s)

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

960 p = s = int(p)

961 m = Fsum._pow_int

962 else:

963 p = s = _2float(power=p)

964 m = Fsum._pow_scalar

965 return m, p, s, r

966

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

968 if p: # and xs:

969 op = which.__name__

970 _Fs = Fsum

971 _is = _isAn

972 _pow = self._pow_2_3

973

974 def _P(X):

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

976 return f._ps if _is(f, _Fs) else (f,)

977

978 def _p(x):

979 x = _Float(x)

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

981 if f and r:

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

983 return f

984

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

986 else:

987 f = self._facc_scalar_(_Float(_len(xs))) # x**0 == 1

988 return f

989

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

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

992 '''

993 if xs:

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

995 return self

996

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

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

999 '''

1000 if xs:

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

1002 return self

1003

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

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

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

1007# '''

1008# ps = self._ps

1009# while _len(ps) > 1:

1010# p = ps.pop()

1011# if p:

1012# n = self._n

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

1014# self._n = n

1015# break

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

1017

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

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

1020

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

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

1023

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

1025

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

1027

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

1029

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

1031 '''

1032 if _isFsumTuple(xs):

1033 self._facc_scalar(xs._ps) # _Tuple(xs._ps)

1034 elif isscalar(xs): # for backward compatibility

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

1036 elif xs: # assert isiterable(xs)

1037 self._facc(xs)

1038 return self

1039

1040 def fadd_(self, *xs):

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

1042

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

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

1045

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

1047 '''

1048 return self._facc_1(xs)

1049

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

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

1052 '''

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

1054 self._fset(other, as_is=False, **up)

1055 elif _isFsumTuple(other):

1056 self._facc_scalar(other._ps, **up) # _Tuple

1057 elif self._scalar(other, op):

1058 self._facc_scalar_(other, **up)

1059 return self

1060

1061 fcopy = copy # for backward compatibility

1062 fdiv = __itruediv__

1063 fdivmod = __divmod__

1064

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

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

1067 '''

1068 # result mostly follows CPython function U{float_divmod

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

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

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

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

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

1074

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

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

1077 self += other

1078 q -= 1

1079# t = self.signOf()

1080# if t and t != s:

1081# raise self._Error(op, other, _AssertionError, txt=signOf.__name__)

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

1083

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

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

1086 '''

1087 if _isfinite(other):

1088 return other

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

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

1091

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

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

1094

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

1096 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

1097 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

1098 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

1099

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

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

1102

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

1104 B{C{RESIDUAL}}.

1105

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

1107 '''

1108 i, r = self._fint2

1109 if r:

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

1111 if R:

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

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

1114 f = self._copy_2(self.fint, name=name)

1115 return f._fset(i)

1116

1117 def fint2(self, **name):

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

1119 I{integer} residual.

1120

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

1122

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

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

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

1126 '''

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

1128

1129 @Property_RO

1130 def _fint2(self): # see ._fset

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

1132 '''

1133 s, r = self._fprs2

1134 i = int(s)

1135 n = _len(self._ps)

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

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

1138

1139 @deprecated_property_RO

1140 def float_int(self): # PYCHOK no cover

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

1142 return self.int_float() # raiser=False

1143

1144 @property_RO

1145 def floor(self):

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

1147 C{float} in Python 2-).

1148

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

1150

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

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

1153 '''

1154 s, r = self._fprs2

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

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

1157 f -= 1

1158 return f # _floor(self._n_d)

1159

1160# ffloordiv = __ifloordiv__ # for naming consistency

1161# floordiv = __floordiv__ # for naming consistency

1162

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

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

1165 '''

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

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

1168

1169 fmul = __imul__

1170

1171 def _fmul(self, other, op):

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

1173 '''

1174 if _isFsumTuple(other):

1175 if _len(self._ps) != 1:

1176 f = self._mul_Fsum(other, op)

1177 elif _len(other._ps) != 1: # and _len(self._ps) == 1

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

1179 else: # _len(other._ps) == _len(self._ps) == 1

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

1181 else:

1182 s = self._scalar(other, op)

1183 f = self._mul_scalar(s, op)

1184 return self._fset(f) # n=_len(self) + 1

1185

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

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

1188

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

1190 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

1191 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

1192 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

1193

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

1195

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

1197 B{C{RESIDUAL}}.

1198

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

1200 '''

1201 return _Float(self.fdiv(over, **raiser_RESIDUAL)._fprs)

1202

1203 fpow = __ipow__

1204

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

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

1207 '''

1208 if mod:

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

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

1211 elif self.is_integer():

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

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

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

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

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

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

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

1219 else: # pow(self, other)

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

1221 return self._fset(f, as_is=isint(f)) # n=max(_len(self), 1)

1222

1223 @Property_RO

1224 def _fprs(self):

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

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

1227

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

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

1230 '''

1231 s, _ = self._fprs2

1232 return s # ._fprs2.fsum

1233

1234 @Property_RO

1235 def _fprs2(self):

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

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

1238 '''

1239 ps = self._ps

1240 n = _len(ps) - 2

1241 if n > 0: # _len(ps) > 2

1242 s = _psum(ps)

1243 n = _len(ps) - 2

1244 if n > 0:

1245 r = self._ps_1sum(s)

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

1247 if n == 0: # _len(ps) == 2

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

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

1250 elif ps: # _len(ps) == 1

1251 s, r = ps[0], INT0

1252 else: # _len(ps) == 0

1253 s, r = _0_0, INT0

1254 ps[:] = s,

1255 # assert self._ps is ps

1256 return Fsum2Tuple(s, r)

1257

1258 def fset_(self, *xs):

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

1260

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

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

1263 all positional.

1264

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

1266

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

1268 '''

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

1270 Fsum(*xs) if xs else _0_0)

1271 return self._fset(f)

1272

1273 def _fset(self, other, as_is=True, n=0, up=True):

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

1275 '''

1276 if other is self:

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

1278 elif _isFsumTuple(other):

1279 self._ps[:] = other._ps

1280 self._n = n or other._n

1281# self._copy_RESIDUAL(other)

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

1283 Fsum._fint2._update_from(self, other)

1284 Fsum._fprs ._update_from(self, other)

1285 Fsum._fprs2._update_from(self, other)

1286 elif isscalar(other):

1287 s = other if as_is else _Float(other)

1288 self._ps[:] = s,

1289 self._n = n or 1

1290 if up:

1291 i = int(s) # see ._fint2

1292 t = i, ((s - i) or INT0)

1293 # Property_ROs _fint2, _fprs and _fprs2 can't be a Property:

1294 # Property's _fset zaps the value just set by the @setter

1295 self.__dict__.update(_fint2=t, _fprs=s, _fprs2=Fsum2Tuple(s, INT0))

1296 else: # PYCHOK no cover

1297 raise self._Error(_fset_op_, other, _TypeError)

1298 return self

1299

1300 def _fset_ps(self, other, n=0): # in .fmath

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

1302 '''

1303 if _isFsumTuple(other):

1304 self._ps[:] = other._ps

1305 self._n = n or other._n

1306 else: # assert isscalar(other)

1307 self._ps[:] = other,

1308 self._n = n or 1

1309 return self

1310

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

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

1313

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

1315 '''

1316 return self._facc_neg(xs)

1317

1318 def fsub_(self, *xs):

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

1320

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

1322 '''

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

1324 self._facc_neg(xs, origin=1)

1325

1326 def _fsub(self, other, op):

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

1328 '''

1329 if _isFsumTuple(other):

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

1331 self._fset(_0_0, n=_len(self) * 2)

1332 elif other._ps:

1333 self._facc_scalar(other._ps_neg)

1334 elif self._scalar(other, op):

1335 self._facc_scalar_(-other)

1336 return self

1337

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

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

1340 current precision running sum.

1341

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

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

1344

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

1346

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

1348

1349 @note: Accumulation can continue after summation.

1350 '''

1351 return self._facc(xs)._fprs

1352

1353 def fsum_(self, *xs):

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

1355 current precision running sum.

1356

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

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

1359

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

1361

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

1363 '''

1364 return self._facc_1(xs)._fprs

1365

1366 @property_RO

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

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

1369

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

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

1372

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

1374

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

1376 '''

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

1378

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

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

1381

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

1383

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

1385 '''

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

1387

1388 def fsum2(self, xs=(), name=NN):

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

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

1391

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

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

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

1395

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

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

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

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

1400 to be I{exact}.

1401

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

1403 '''

1404 t = self._facc(xs)._fprs2

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

1406

1407 def fsum2_(self, *xs):

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

1409 precision running sum and the I{differential}.

1410

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

1412 L{Fsum2Tuple} instance), all positional.

1413

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

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

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

1417

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

1419 '''

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

1421

1422 def _fsum2(self, xs, _f, **origin):

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

1424 '''

1425 p, q = self._fprs2

1426 if xs:

1427 s, r = _f(xs, **origin)._fprs2

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

1429 else:

1430 return p, _0_0

1431

1432 def fsumf_(self, *xs):

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

1434 '''

1435 return self._facc_scalar(xs)._fprs

1436

1437 def Fsumf_(self, *xs):

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

1439 '''

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

1441

1442 def fsum2f_(self, *xs):

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

1444 '''

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

1446

1447# ftruediv = __itruediv__ # for naming consistency?

1448

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

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

1451 '''

1452 n = _1_0

1453 if _isFsumTuple(other):

1454 if other is self or self == other:

1455 return self._fset(n) # n=_len(self)

1456 d, r = other._fprs2

1457 if r:

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

1459 if R:

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

1461 d, n = other.as_integer_ratio()

1462 else:

1463 d = self._scalar(other, op)

1464 try:

1465 s = n / d

1466 except Exception as X:

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

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

1469 return self._fset(f) # as_is=False

1470

1471 @property_RO

1472 def imag(self):

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

1474

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

1476 '''

1477 return _0_0

1478

1479 def int_float(self, **raiser_RESIDUAL):

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

1481

1482 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

1483 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

1484 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

1485

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

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

1488 zero or not significant.

1489

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

1491 B{C{RESIDUAL}}.

1492

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

1494 property L{Fsum.as_iscalar}.

1495 '''

1496 s, r = self._fint2

1497 if r:

1498 s, r = self._fprs2

1499 if r: # PYCHOK no cover

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

1501 if R:

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

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

1504 s = _Float(s) # redundant

1505 return s

1506

1507 def is_exact(self):

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

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

1510 '''

1511 return self.residual is INT0

1512

1513 def is_integer(self):

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

1515

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

1517 '''

1518 _, r = self._fint2

1519 return False if r else True

1520

1521 def is_math_fsum(self):

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

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

1524 C{math.fsum} or not.

1525

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

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

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

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

1530 none are.

1531 '''

1532 f = Fsum._math_fsum

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

1534

1535 def is_scalar(self, **raiser_RESIDUAL):

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

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

1538

1539 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to ignore

1540 L{ResidualError}s and C{B{RESIDUAL}=scalar} to override

1541 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.

1542

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

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

1545

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

1547 B{C{RESIDUAL}}.

1548

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

1550 L{Fsum.as_iscalar}.

1551 '''

1552 s, r = self._fprs2

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

1554

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

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

1557 '''

1558 # assert _isFsumTuple(other)

1559 if self._ps and other._ps:

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

1561 else:

1562 f = _0_0

1563 return f

1564

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

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

1567 '''

1568 # assert isscalar(factor)

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

1570 f = self if factor == _1_0 else (

1571 self._neg if factor == _N_1_0 else

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

1573 else:

1574 f = _0_0

1575 return f

1576

1577# @property_RO

1578# def _n_d(self):

1579# n, d = self.as_integer_ratio()

1580# return n / d

1581

1582 @property_RO

1583 def _neg(self):

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

1585 '''

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

1587

1588 @property_RO

1589 def partials(self):

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

1591 '''

1592 return _Tuple(self._ps)

1593

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

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

1596

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

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

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

1600 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

1601 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

1602 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

1603

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

1605 result (L{Fsum}).

1606

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

1608 B{C{RESIDUAL}}.

1609

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

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

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

1613

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

1615 and L{Fsum.root}.

1616 '''

1617 f = self._copy_2(self.pow)

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

1619

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

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

1622 '''

1623 if _isFsumTuple(other):

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

1625 elif self._scalar(other, op):

1626 x = self._finite(other, op)

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

1628 else:

1629 f = self._pow_0_1(0, other)

1630 return f

1631

1632 def _pow_0_1(self, x, other):

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

1634 '''

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

1636

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

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

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

1640 '''

1641

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

1643 m = mod[0]

1644 # assert _isFsumTuple(b)

1645

1646 def _s(s, r):

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

1648 if R:

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

1650 return s

1651

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

1653 x = _s(*_2scalar2(x))

1654

1655 try:

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

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

1658 if iscomplex(s):

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

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

1661 return self._finite(s)

1662 except Exception as X:

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

1664

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

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

1667 '''

1668 # assert _isFsumTuple(other)

1669 x, r = other._fprs2

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

1671 if f and r:

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

1673 return f

1674

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

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

1677 '''

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

1679 ps = self._ps

1680 if _len(ps) > 1:

1681 _mul_Fsum = Fsum._mul_Fsum

1682 if x > 4:

1683 p = self

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

1685 m = x >> 1 # // 2

1686 while m:

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

1688 if (m & 1):

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

1690 m >>= 1 # //= 2

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

1692 f = _mul_Fsum(self, self, op)

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

1694 p = self if x < 4 else f

1695 f = _mul_Fsum(f, p, op)

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

1697 f = self._pow_0_1(x, other)

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

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

1700 else: # PYCHOK no cover

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

1702 f = 0 if x else 1

1703 return f

1704

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

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

1707 '''

1708 s, r = self._fprs2

1709 if r:

1710 # assert s != 0

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

1712 x = int(x)

1713 y = _abs(x)

1714 if y > 1:

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

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

1717 return f # Fsum or scalar

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

1719 if _isFsum(f):

1720 s, r = f._fprs2

1721 if r:

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

1723 else: # scalar

1724 s = f

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

1726 # float_pow error iff s is zero

1727 x = -1

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

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

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

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

1732 else: # self**fractional

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

1734 if R:

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

1736 n, d = self.as_integer_ratio()

1737 if _abs(n) > _abs(d):

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

1739 s = n / d

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

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

1742

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

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

1745 '''

1746 n = 0

1747 _2s = _2sum

1748 for x in (_Tuple(xs) if xs is ps else xs):

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

1750 if x:

1751 i = 0

1752 for p in ps:

1753 x, p = _2s(x, p)

1754 if p:

1755 ps[i] = p

1756 i += 1

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

1758 n += 1

1759 if n:

1760 self._n += n

1761 # Fsum._ps_max = max(Fsum._ps_max, _len(ps))

1762 if up:

1763 self._update()

1764 return ps

1765

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

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

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

1769 '''

1770 def _pfs(ps, fs):

1771 if _len(ps) < _len(fs):

1772 ps, fs = fs, ps

1773 _fin = _isfinite

1774 for f in fs:

1775 for p in ps:

1776 p *= f

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

1778

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

1780

1781 @property_RO

1782 def _ps_neg(self):

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

1784 '''

1785 for p in self._ps:

1786 yield -p

1787

1788 def _ps_1sum(self, *less):

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

1790 '''

1791 def _1pls(ps, ls):

1792 yield _1_0

1793 for p in ps:

1794 yield p

1795 for p in ls:

1796 yield -p

1797 yield _N_1_0

1798

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

1800

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

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

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

1804 negative respectively positive C{RESIDUAL} threshold)?

1805 '''

1806 if r and raiser:

1807 t = self._RESIDUAL

1808 if RESIDUAL:

1809 t = _threshold(_xkwds_get(RESIDUAL, RESIDUAL=t))

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

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

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

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

1814 return {}

1815

1816 rdiv = __rtruediv__

1817

1818 @property_RO

1819 def real(self):

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

1821

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

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

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

1825 '''

1826 return _Float(self._fprs)

1827

1828 @property_RO

1829 def residual(self):

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

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

1832

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

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

1835

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

1837 '''

1838 return self._fprs2.residual

1839

1840 def RESIDUAL(self, *threshold):

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

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

1843

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

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

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

1847 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

1848 current setting.

1849

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

1851

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

1853

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

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

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

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

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

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

1860 testing without I{significant}.

1861 '''

1862 r = self._RESIDUAL

1863 if threshold:

1864 t = threshold[0]

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

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

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

1868 return r

1869

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

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

1872 '''

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

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

1875 if mod is None else _integer_

1876

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

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

1879

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

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

1882

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

1884 @kwarg raiser_RESIDUAL: Use C{B{raiser}=False} (C{bool}) to

1885 ignore L{ResidualError}s and C{B{RESIDUAL}=scalar}

1886 to override the L{RESIDUAL<Fsum.RESIDUAL>}.

1887

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

1889

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

1891 B{C{RESIDUAL}}.

1892

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

1894 '''

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

1896 f = self._copy_2(self.root)

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

1898

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

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

1901 '''

1902 if isscalar(other):

1903 return other

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

1905

1906 def signOf(self, res=True):

1907 '''Determine the sign of this instance.

1908

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

1910 ignore the residual (C{bool}).

1911

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

1913 '''

1914 s, r = self._fprs2

1915 r = (-r) if res else 0

1916 return _signOf(s, r)

1917

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

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

1920

1921 @kwarg lenc_prec_sep_fmt: Optional keyword arguments

1922 for method L{Fsum.toStr}.

1923

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

1925 '''

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

1927

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

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

1930

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

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

1933 @kwarg prec_sep_fmt: Optional keyword arguments for method

1934 L{Fsum2Tuple.toStr}.

1935

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

1937 '''

1938 p = self.classname

1939 if lenc:

1940 p = Fmt.SQUARE(p, _len(self))

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

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

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

1944

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

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

1947 '''

1948 f = self._copy_2(self.__truediv__)

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

1950

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

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

1953 '''

1954 if updated:

1955 _pop = self.__dict__.pop

1956 for p in _ROs:

1957 _ = _pop(p, None)

1958# Fsum._fint2._update(self)

1959# Fsum._fprs ._update(self)

1960# Fsum._fprs2._update(self)

1961 return self # for .fset_

1962

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

1964

1965

1966 def _Float_Int(arg, **name_Error):

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

1968 '''

1969 U = Int if isint(arg) else Float

1970 return U(arg, **name_Error)

1971

1972

1973 class DivMod2Tuple(_NamedTuple):

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

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

1976

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

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

1979 '''

1980 _Names_ = (_div_, _mod_)

1981 _Units_ = (_Float_Int, Fsum)

1982

1983

1984 class Fsum2Tuple(_NamedTuple): # in .fstats

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

1986 and the C{residual}, the sum of the remaining partials. Each

1987 item is C{float} or C{int}.

1988

1989 @note: If the C{residual is INT0}, the C{fsum} is considered

1990 to be I{exact}, see method L{Fsum2Tuple.is_exact}.

1991 '''

1992 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)

1993 _Units_ = (_Float_Int, _Float_Int)

1994

1995 def __abs__(self): # in .fmath

1996 return self._Fsum.__abs__()

1997

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

1999 return bool(self._Fsum)

2000

2001 def __eq__(self, other):

2002 return self._other_op(other, self.__eq__)

2003

2004 def __float__(self):

2005 return self._Fsum.__float__()

2006

2007 def __ge__(self, other):

2008 return self._other_op(other, self.__ge__)

2009

2010 def __gt__(self, other):

2011 return self._other_op(other, self.__gt__)

2012

2013 def __le__(self, other):

2014 return self._other_op(other, self.__le__)

2015

2016 def __lt__(self, other):

2017 return self._other_op(other, self.__lt__)

2018

2019 def __int__(self):

2020 return self._Fsum.__int__()

2021

2022 def __ne__(self, other):

2023 return self._other_op(other, self.__ne__)

2024

2025 def __neg__(self):

2026 return self._Fsum.__neg__()

2027

2028 __nonzero__ = __bool__ # Python 2-

2029

2030 def __pos__(self):

2031 return self._Fsum.__pos__()

2032

2033 def as_integer_ratio(self):

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

2035

2036 @see: Method L{Fsum.as_integer_ratio} for further details.

2037 '''

2038 return self._Fsum.as_integer_ratio()

2039

2040 @property_RO

2041 def _fint2(self):

2042 return self._Fsum._fint2

2043

2044 @property_RO

2045 def _fprs2(self):

2046 return self._Fsum._fprs2

2047

2048 @Property_RO

2049 def _Fsum(self): # this C{Fsum2Tuple} as L{Fsum}, in .fstats

2050 s, r = _s_r(*self)

2051 ps = (r, s) if r else (s,)

2052 return _Psum(ps, name=self.name)

2053

2054 def Fsum_(self, *xs, **name_RESIDUAL):

2055 '''Return this C{Fsum2Tuple} as an L{Fsum} plus some C{xs}.

2056 '''

2057 f = _Psum(self._Fsum._ps, **name_RESIDUAL)

2058 return f._facc_1(xs, up=False) if xs else f

2059

2060 def is_exact(self):

2061 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).

2062 '''

2063 return self._Fsum.is_exact()

2064

2065 def is_integer(self):

2066 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).

2067 '''

2068 return self._Fsum.is_integer()

2069

2070 def _mul_scalar(self, other, op): # for Fsum._fmul

2071 return self._Fsum._mul_scalar(other, op)

2072

2073 @property_RO

2074 def _n(self):

2075 return self._Fsum._n

2076

2077 def _other_op(self, other, which):

2078 C, s = (_Tuple, self) if _isAn(other, _Tuple) else (Fsum, self._Fsum)

2079 return getattr(C, which.__name__)(s, other)

2080

2081 @property_RO

2082 def _ps(self):

2083 return self._Fsum._ps

2084

2085 @property_RO

2086 def _ps_neg(self):

2087 return self._Fsum._ps_neg

2088

2089 def signOf(self, **res):

2090 '''Like method L{Fsum.signOf}.

2091 '''

2092 return self._Fsum.signOf(**res)

2093

2094 def toStr(self, fmt=Fmt.g, **prec_sep): # PYCHOK signature

2095 '''Return this L{Fsum2Tuple} as string (C{str}).

2096

2097 @kwarg fmt: Optional C{float} format (C{letter}).

2098 @kwarg prec_sep: Optional keyword arguments for function

2099 L{fstr<streprs.fstr>}.

2100 '''

2101 return Fmt.PAREN(fstr(self, fmt=fmt, strepr=str, force=False, **prec_sep))

2102

2103_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines

2104

2105

2106 class ResidualError(_ValueError):

2107 '''Error raised for a division, power or root operation of

2108 an L{Fsum} instance with a C{residual} I{ratio} exceeding

2109 the L{RESIDUAL<Fsum.RESIDUAL>} threshold.

2110

2111 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.

2112 '''

2113 pass

2114

2115

2116 try:

2117 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+

2118

2119 # make sure _fsum works as expected (XXX check

2120 # float.__getformat__('float')[:4] == 'IEEE'?)

2121 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover

2122 del _fsum # nope, remove _fsum ...

2123 raise ImportError # ... use _fsum below

2124

2125 Fsum._math_fsum = _sum = _fsum # PYCHOK exported

2126 except ImportError:

2127 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic

2128

2129 def _fsum(xs):

2130 '''(INTERNAL) Precision summation, Python 2.5-.

2131 '''

2132 F = Fsum()

2133 F.name = _fsum.__name__

2134 return F._facc(xs, up=False)._fprs2.fsum

2135

2136

2137 def fsum(xs, floats=False):

2138 '''Precision floating point summation based on/like Python's C{math.fsum}.

2139

2140 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

2141 instance).

2142 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2143 be scalar} (C{bool}).

2144

2145 @return: Precision C{fsum} (C{float}).

2146

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

2148

2149 @raise TypeError: Non-scalar B{C{xs}} item.

2150

2151 @raise ValueError: Invalid or non-finite B{C{xs}} item.

2152

2153 @note: Exception and I{non-finite} handling may differ if not based

2154 on Python's C{math.fsum}.

2155

2156 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.

2157 '''

2158 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield

2159

2160

2161 def fsum_(*xs, **floats):

2162 '''Precision floating point summation of all positional items.

2163

2164 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),

2165 all positional.

2166 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2167 be scalar} (C{bool}).

2168

2169 @see: Function L{fsum<fsums.fsum>} for further details.

2170 '''

2171 return _fsum(xs if _xkwds_get(floats, floats=False) is True else

2172 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield

2173

2174

2175 def fsumf_(*xs):

2176 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.

2177

2178 @see: Function L{fsum_<fsums.fsum_>} for further details.

2179 '''

2180 return _fsum(xs) if xs else _0_0

2181

2182

2183 def fsum1(xs, floats=False):

2184 '''Precision floating point summation, 1-primed.

2185

2186 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

2187 instance).

2188 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2189 be scalar} (C{bool}).

2190

2191 @see: Function L{fsum<fsums.fsum>} for further details.

2192 '''

2193 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield

2194

2195

2196 def fsum1_(*xs, **floats):

2197 '''Precision floating point summation, 1-primed of all positional items.

2198

2199 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),

2200 all positional.

2201 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2202 be scalar} (C{bool}).

2203

2204 @see: Function L{fsum_<fsums.fsum_>} for further details.

2205 '''

2206 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) is True else

2207 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield

2208

2209

2210 def fsum1f_(*xs):

2211 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.

2212

2213 @see: Function L{fsum_<fsums.fsum_>} for further details.

2214 '''

2215 return _fsum(_1primed(xs)) if xs else _0_0

2216

2217

2218 if __name__ == '__main__':

2219

2220 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums

2221

2222 if _getenv(_psum.__name__, NN) == _fsum.__name__:

2223 _psum = _fsum

2224

2225 def _test(n):

2226 # copied from Hettinger, see L{Fsum} reference

2227 from pygeodesy import frandoms, printf

2228

2229 printf(_fsum.__name__, end=_COMMASPACE_)

2230 printf(_psum.__name__, end=_COMMASPACE_)

2231

2232 F = Fsum()

2233 if F.is_math_fsum():

2234 for t in frandoms(n, seeded=True):

2235 assert _Float(F.fset_(*t)) == _fsum(t)

2236 printf(_DOT_, end=NN)

2237 printf(NN)

2238

2239 _test(128)

2240

2241# **) MIT License

2242#

2243# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

2244#

2245# Permission is hereby granted, free of charge, to any person obtaining a

2246# copy of this software and associated documentation files (the "Software"),

2247# to deal in the Software without restriction, including without limitation

2248# the rights to use, copy, modify, merge, publish, distribute, sublicense,

2249# and/or sell copies of the Software, and to permit persons to whom the

2250# Software is furnished to do so, subject to the following conditions:

2251#

2252# The above copyright notice and this permission notice shall be included

2253# in all copies or substantial portions of the Software.

2254#

2255# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

2256# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

2257# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

2258# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

2259# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

2260# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

2261# OTHER DEALINGS IN THE SOFTWARE.