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 _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, _ValueError, \

32 _xError, _xError2, _xkwds_get

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

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

35 _EQUAL_, _from_, _LANGLE_, _NOTEQUAL_, \

36 _not_finite_, _PERCENT_, _PLUS_, \

37 _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_

38 from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2

39 from pygeodesy.named import _Named, _NamedTuple, _NotImplemented

40 from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \

41 Property_RO, property_RO

42 from pygeodesy.streprs import Fmt, fstr, unstr

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

44

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

46

47__all__ = _ALL_LAZY.fsums

48__version__ = '24.05.13'

49

50_add_op_ = _PLUS_ # in .auxilats.auxAngle

51_eq_op_ = _EQUAL_ * 2 # _DEQUAL_

52_div_ = 'div'

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_le_op_ = _LANGLE_ + _EQUAL_

60_lt_op_ = _LANGLE_

61_mod_ = 'mod'

62_mod_op_ = _PERCENT_

63_mul_op_ = _STAR_

64_ne_op_ = _NOTEQUAL_

65_non_zero_ = 'non-zero'

66_pow_op_ = _STAR_ * 2 # _DSTAR_

67_significant_ = 'significant'

68_sub_op_ = _DASH_ # in .auxilats.auxAngle

69_threshold_ = 'threshold'

70_truediv_op_ = _SLASH_

71_divmod_op_ = _floordiv_op_ + _mod_op_

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

73

74

75 def _2delta(*ab):

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

77 '''

78 try:

79 a, b = _2sum(*ab)

80 except _OverflowError:

81 a, b = ab

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

83

84

85 def _2error(unused): # in .fstats

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

87 '''

88 raise ValueError(_not_finite_)

89

90

91 def _2finite(x):

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

93 '''

94 x = float(x)

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

96

97

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

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

100 '''

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

102 try:

103 return _2finite(v)

104 except Exception as X:

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

106

107

108 def _X_ps(X): # for _2floats only

109 return X._ps

110

111

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

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

114 '''

115 try:

116 i, x = origin, _X

117 _fin = _isfinite

118 _FsT = _Fsum_Fsum2Tuple_types

119 _isa = isinstance

120 for x in _xiterable(xs):

121 if _isa(x, _FsT):

122 for p in _X(x._Fsum):

123 yield p

124 else:

125 f = _x(x)

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

127 i += 1

128 except Exception as X:

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

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

131

132

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

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

135 '''

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

137

138

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

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

141 '''

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

143

144

145 def _2halfeven(s, r, p):

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

147 '''

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

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

150 r *= 2

151 t = s + r

152 if r == (t - s):

153 s = t

154 return s

155

156

157 def _isFsum(x): # in .fmath

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

159 '''

160 return isinstance(x, Fsum)

161

162

163 def _isFsumTuple(x): # in .fmath

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

165 '''

166 return isinstance(x, _Fsum_Fsum2Tuple_types)

167

168

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

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

171 '''

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

173

174

175 def _1primed(xs): # in .fmath

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

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

178 '''

179 yield _1_0

180 for x in xs:

181 yield x

182 yield _N_1_0

183

184

185 def _psum(ps): # PYCHOK used!

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

187 '''

188 # assert isinstance(ps, list)

189 i = len(ps) - 1

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

191 _2s = _2sum

192 while i > 0:

193 i -= 1

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

195 if r: # sum(ps) became inexact

196 if s:

197 ps[i:] = r, s

198 if i > 0:

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

200 break # return s

201 s = r # PYCHOK no cover

202 ps[i:] = s,

203 return s

204

205

206 def _Psum(ps, **name_RESIDUAL):

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

208 '''

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

210 if ps:

211 f._ps[:] = ps

212 f._n = len(f._ps)

213 return f

214

215

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

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

218 '''

219 return _Psum(ps, **name_RESIDUAL)

220

221

222 def _2scalar2(other):

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

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

225 '''

226 if _isFsumTuple(other):

227 s, r = other._fint2

228 if r:

229 s, r = other._fprs2

230 if r: # PYCHOK no cover

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

232 else:

233 r = 0

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

235 if isint(s, both=True):

236 s = int(s)

237 return s, r

238

239

240 def _s_r(s, r):

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

242 '''

243 if r:

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

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

246 else:

247 r = INT0

248 return s, r

249

250

251 def _strcomplex(s, *args):

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

253 '''

254 c = _strcomplex.__name__[4:]

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

256 t = unstr(pow, *args)

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

258

259

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

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

262 '''

263 p = _stresidual.__name__[3:]

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

265 for n, v in itemsorted(mod_ratio):

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

267 t = _COMMASPACE_(t, p)

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

269

270

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

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

273 '''

274 s = a + b

275 if _isfinite(s):

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

277 b, a = a, b

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

279 u = unstr(_2sum, a, b)

280 t = Fmt.PARENSPACED(_not_finite_, s)

281 raise _OverflowError(u, txt=t)

282

283

284 def _threshold(threshold):

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

286 '''

287 try:

288 return _2finite(threshold) # PYCHOK None

289 except Exception as x:

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

291

292

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

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

295

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

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

298 intermediate, I{running} summuation.

299

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

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

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

303

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

305 Python's C{math.fsum}.

306

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

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

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

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

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

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

313 '''

314 _math_fsum = None

315 _n = 0

316# _ps = [] # partial sums

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

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

319

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

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

322

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

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

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

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

327

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

329 '''

330 if name_RESIDUAL:

331

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

333 return name, RESIDUAL

334

335 n, R = _n_R(**name_RESIDUAL)

336 if R is not None:

337 self.RESIDUAL(R)

338 if n:

339 self.name = n

340

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

342 if xs:

343 self._facc_1(xs, up=False)

344

345 def __abs__(self):

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

347 '''

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

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

350

351 def __add__(self, other):

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

353

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

355

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

357

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

359 '''

360 f = self._copy_2(self.__add__)

361 return f._fadd(other, _add_op_)

362

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

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

365 '''

366 s, r = self._fprs2

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

368

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

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

371

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

373

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

375 '''

376 return self.ceil

377

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

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

380

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

382

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

384 '''

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

386 return _signOf(s, 0)

387

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

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

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

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

392

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

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

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

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

397

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

399 B{C{RESIDUAL}}.

400

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

402 '''

403 f = self._copy_2(self.__divmod__)

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

405

406 def __eq__(self, other):

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

408 '''

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

410

411 def __float__(self):

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

413

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

415 '''

416 return float(self._fprs)

417

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

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

420

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

422

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

424 '''

425 return self.floor

426

427 def __floordiv__(self, other):

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

429

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

431

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

433

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

435 '''

436 f = self._copy_2(self.__floordiv__)

437 return f._floordiv(other, _floordiv_op_)

438

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

440 '''Not implemented.'''

441 return _NotImplemented(self, *other)

442

443 def __ge__(self, other):

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

445 '''

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

447

448 def __gt__(self, other):

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

450 '''

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

452

453 def __hash__(self): # PYCHOK no cover

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

455 '''

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

457

458 def __iadd__(self, other):

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

460

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

462 an iterable of several of the former.

463

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

465

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

467 C{scalar} nor L{Fsum}.

468

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

470 '''

471 try:

472 return self._fadd(other, _iadd_op_)

473 except TypeError:

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

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} value or

582 an iterable of several of the former.

583

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

585

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

587

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

589 '''

590 try:

591 return self._fsub(other, _isub_op_)

592 except TypeError:

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

594

595 def __iter__(self):

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

597 '''

598 return iter(self.partials)

599

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

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

602

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

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

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

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

607

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

609

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

611

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

613 B{C{RESIDUAL}}.

614

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

616

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

618

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

620

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

622 '''

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

624

625 def __le__(self, other):

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

627 '''

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

629

630 def __len__(self):

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

632 '''

633 return self._n

634

635 def __lt__(self, other):

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

637 '''

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

639

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

641 '''Not implemented.'''

642 return _NotImplemented(self, other)

643

644 def __mod__(self, other):

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

646

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

648 '''

649 f = self._copy_2(self.__mod__)

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

651

652 def __mul__(self, other):

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

654

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

656 '''

657 f = self._copy_2(self.__mul__)

658 return f._fmul(other, _mul_op_)

659

660 def __ne__(self, other):

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

662 '''

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

664

665 def __neg__(self):

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

667 '''

668 f = self._copy_2(self.__neg__)

669 return f._fset(self._neg)

670

671 def __pos__(self):

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

673 '''

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

675

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

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

678

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

680 '''

681 f = self._copy_2(self.__pow__)

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

683

684 def __radd__(self, other):

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

686

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

688 '''

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

690 return f._fadd(self, _add_op_)

691

692 def __rdivmod__(self, other):

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

694 C{(quotient, remainder)}.

695

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

697 '''

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

699 return f._fdivmod2(self, _divmod_op_)

700

701# def __repr__(self):

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

703# '''

704# return self.toRepr(lenc=True)

705

706 def __rfloordiv__(self, other):

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

708

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

710 '''

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

712 return f._floordiv(self, _floordiv_op_)

713

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

715 '''Not implemented.'''

716 return _NotImplemented(self, other)

717

718 def __rmod__(self, other):

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

720

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

722 '''

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

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

725

726 def __rmul__(self, other):

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

728

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

730 '''

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

732 return f._fmul(self, _mul_op_)

733

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

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

736

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

738 '''

739 f = self._copy_2(self.__round__)

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

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

742

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

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

745

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

747 '''

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

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

750

751 def __rsub__(self, other):

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

753

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

755 '''

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

757 return f._fsub(self, _sub_op_)

758

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

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

761

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

763 '''

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

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

766

767 def __str__(self):

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

769 '''

770 return self.toStr(lenc=True)

771

772 def __sub__(self, other):

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

774

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

776

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

778

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

780 '''

781 f = self._copy_2(self.__sub__)

782 return f._fsub(other, _sub_op_)

783

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

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

786

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

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

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

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

791

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

793

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

795 B{C{RESIDUAL}}.

796

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

798 '''

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

800

801 __trunc__ = __int__

802

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

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

805 __div__ = __truediv__

806 __idiv__ = __itruediv__

807 __long__ = __int__

808 __nonzero__ = __bool__

809 __rdiv__ = __rtruediv__

810

811 def as_integer_ratio(self):

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

813

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

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

816 non-zero, positive.

817

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

819 '''

820 n, r = self._fint2

821 if r:

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

823 n *= d

824 n += i

825 else: # PYCHOK no cover

826 d = 1

827 return n, d

828

829 @property_RO

830 def as_iscalar(self):

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

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

833 '''

834 s, r = self._fprs2

835 return self if r else s

836

837 @property_RO

838 def ceil(self):

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

840 C{float} in Python 2-).

841

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

843

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

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

846 '''

847 s, r = self._fprs2

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

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

850 c += 1

851 return c # _ceil(self._n_d)

852

853 cmp = __cmp__

854

855 def _cmp_0(self, other, op):

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

857 '''

858 if _isFsumTuple(other):

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

860 elif self._scalar(other, op):

861 s = self._ps_1sum(other)

862 else:

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

864 return s

865

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

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

868

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

870 '''

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

872 if f._ps is self._ps:

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

874 if not deep:

875 f._n = 1

876 # assert f._Fsum is f

877 return f

878

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

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

881 '''

882 n = name or which.__name__

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

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

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

886 # assert f._n == self._n

887 # assert f._Fsum is f

888 return f

889

890 def _copy_2r(self, other, which):

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

892 '''

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

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

895

896# def _copy_RESIDUAL(self, other):

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

898# '''

899# R = other._RESIDUAL

900# if R is not Fsum._RESIDUAL:

901# self._RESIDUAL = R

902

903 divmod = __divmod__

904

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

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

907 '''

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

909

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

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

912 '''

913 E, t = _xError2(X)

914 if mod:

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

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

917

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

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

920 '''

921 E, t = _xError2(X)

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

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

924

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

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

927 '''

928 if xs:

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

930 ps = self._ps

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

932 return self

933

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

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

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

937 '''

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

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

940

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

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

943 '''

944 try:

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

946 except Exception as X:

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

948

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

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

951 '''

952 def _N(X):

953 return X._ps_neg

954

955 def _n(x):

956 return -float(x)

957

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

959

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

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

962 '''

963 def _Pow4(p):

964 r = 0

965 if _isFsumTuple(p):

966 s, r = p._fprs2

967 if r:

968 m = Fsum._pow

969 else: # scalar

970 return _Pow4(s)

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

972 p = s = int(p)

973 m = Fsum._pow_int

974 else:

975 p = s = _2float(power=p)

976 m = Fsum._pow_scalar

977 return m, p, s, r

978

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

980 if p: # and xs:

981 op = which.__name__

982 _flt = float

983 _Fs = Fsum

984 _isa = isinstance

985 _pow = self._pow_2_3

986

987 def _P(X):

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

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

990

991 def _p(x):

992 x = _flt(x)

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

994 if f and r:

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

996 return f

997

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

999 else:

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

1001 return f

1002

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

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

1005 '''

1006 if xs:

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

1008 return self

1009

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

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

1012 '''

1013 if xs:

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

1015 return self

1016

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

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

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

1020# '''

1021# ps = self._ps

1022# while len(ps) > 1:

1023# p = ps.pop()

1024# if p:

1025# n = self._n

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

1027# self._n = n

1028# break

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

1030

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

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

1033

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

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

1036

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

1038

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

1040

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

1042

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

1044 '''

1045 if _isFsumTuple(xs):

1046 self._facc_scalar(xs._ps)

1047 elif isscalar(xs): # for backward compatibility

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

1049 elif xs: # _xiterable(xs)

1050 self._facc(xs)

1051 return self

1052

1053 def fadd_(self, *xs):

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

1055

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

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

1058

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

1060 '''

1061 return self._facc_1(xs)

1062

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

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

1065 '''

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

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

1068 elif _isFsumTuple(other):

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

1070 elif self._scalar(other, op):

1071 self._facc_scalar_(other, **up)

1072 return self

1073

1074 fcopy = copy # for backward compatibility

1075 fdiv = __itruediv__

1076 fdivmod = __divmod__

1077

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

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

1080 '''

1081 # result mostly follows CPython function U{float_divmod

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

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

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

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

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

1087

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

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

1090 self += other

1091 q -= 1

1092# t = self.signOf()

1093# if t and t != s:

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

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

1096

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

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

1099 '''

1100 if _isfinite(other):

1101 return other

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

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

1104

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

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

1107

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

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

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

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

1112

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

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

1115

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

1117 B{C{RESIDUAL}}.

1118

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

1120 '''

1121 i, r = self._fint2

1122 if r:

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

1124 if R:

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

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

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

1128 return f._fset(i)

1129

1130 def fint2(self, **name):

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

1132 I{integer} residual.

1133

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

1135

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

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

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

1139 '''

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

1141

1142 @Property_RO

1143 def _fint2(self): # see ._fset

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

1145 '''

1146 s, r = self._fprs2

1147 i = int(s)

1148 n = len(self._ps)

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

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

1151

1152 @deprecated_property_RO

1153 def float_int(self): # PYCHOK no cover

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

1155 return self.int_float() # raiser=False

1156

1157 @property_RO

1158 def floor(self):

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

1160 C{float} in Python 2-).

1161

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

1163

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

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

1166 '''

1167 s, r = self._fprs2

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

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

1170 f -= 1

1171 return f # _floor(self._n_d)

1172

1173# ffloordiv = __ifloordiv__ # for naming consistency

1174# floordiv = __floordiv__ # for naming consistency

1175

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

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

1178 '''

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

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

1181

1182 fmul = __imul__

1183

1184 def _fmul(self, other, op):

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

1186 '''

1187 if _isFsumTuple(other):

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

1189 f = self._mul_Fsum(other, op)

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

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

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

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

1194 else:

1195 s = self._scalar(other, op)

1196 f = self._mul_scalar(s, op)

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

1198

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

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

1201

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

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

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

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

1206

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

1208

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

1210 B{C{RESIDUAL}}.

1211

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

1213 '''

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

1215

1216 fpow = __ipow__

1217

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

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

1220 '''

1221 if mod:

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

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

1224 elif self.is_integer():

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

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

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

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

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

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

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

1232 else: # pow(self, other)

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

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

1235

1236 @Property_RO

1237 def _fprs(self):

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

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

1240

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

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

1243 '''

1244 s, _ = self._fprs2

1245 return s # ._fprs2.fsum

1246

1247 @Property_RO

1248 def _fprs2(self):

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

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

1251 '''

1252 ps = self._ps

1253 n = len(ps) - 2

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

1255 s = _psum(ps)

1256 n = len(ps) - 2

1257 if n > 0:

1258 r = self._ps_1sum(s)

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

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

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

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

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

1264 s, r = ps[0], INT0

1265 else: # len(ps) == 0

1266 s, r = _0_0, INT0

1267 ps[:] = s,

1268 # assert self._ps is ps

1269 return Fsum2Tuple(s, r)

1270

1271 def fset_(self, *xs):

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

1273

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

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

1276 all positional.

1277

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

1279

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

1281 '''

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

1283 Fsum(*xs) if xs else _0_0)

1284 return self._fset(f)

1285

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

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

1288 '''

1289 if other is self:

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

1291 elif _isFsumTuple(other):

1292 self._ps[:] = other._ps

1293 self._n = n or other._n

1294# self._copy_RESIDUAL(other)

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

1296 Fsum._fint2._update_from(self, other)

1297 Fsum._fprs ._update_from(self, other)

1298 Fsum._fprs2._update_from(self, other)

1299 elif isscalar(other):

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

1301 self._ps[:] = s,

1302 self._n = n or 1

1303 if up:

1304 i = int(s) # see ._fint2

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

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

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

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

1309 else: # PYCHOK no cover

1310 op = _xkwds_get(op, op=_fset_op_)

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

1312 return self

1313

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

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

1316 '''

1317 if _isFsumTuple(other):

1318 self._ps[:] = other._ps

1319 self._n = n or other._n

1320 else: # assert isscalar(other)

1321 self._ps[:] = other,

1322 self._n = n or 1

1323 return self

1324

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

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

1327

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

1329 '''

1330 return self._facc_neg(xs)

1331

1332 def fsub_(self, *xs):

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

1334

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

1336 '''

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

1338 self._facc_neg(xs, origin=1)

1339

1340 def _fsub(self, other, op):

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

1342 '''

1343 if _isFsumTuple(other):

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

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

1346 elif other._ps:

1347 self._facc_scalar(other._ps_neg)

1348 elif self._scalar(other, op):

1349 self._facc_scalar_(-other)

1350 return self

1351

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

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

1354 current precision running sum.

1355

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

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

1358

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

1360

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

1362

1363 @note: Accumulation can continue after summation.

1364 '''

1365 return self._facc(xs)._fprs

1366

1367 def fsum_(self, *xs):

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

1369 current precision running sum.

1370

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

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

1373

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

1375

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

1377 '''

1378 return self._facc_1(xs)._fprs

1379

1380 @property_RO

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

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

1383

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

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

1386

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

1388

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

1390 '''

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

1392

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

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

1395

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

1397

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

1399 '''

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

1401

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

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

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

1405

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

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

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

1409

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

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

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

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

1414 to be I{exact}.

1415

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

1417 '''

1418 t = self._facc(xs)._fprs2

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

1420

1421 def fsum2_(self, *xs):

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

1423 precision running sum and the I{differential}.

1424

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

1426 L{Fsum2Tuple} instance), all positional.

1427

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

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

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

1431

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

1433 '''

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

1435

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

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

1438 '''

1439 p, q = self._fprs2

1440 if xs:

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

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

1443 else:

1444 return p, _0_0

1445

1446 def fsumf_(self, *xs):

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

1448 '''

1449 return self._facc_scalar(xs)._fprs

1450

1451 def Fsumf_(self, *xs):

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

1453 '''

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

1455

1456 def fsum2f_(self, *xs):

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

1458 '''

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

1460

1461# ftruediv = __itruediv__ # for naming consistency?

1462

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

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

1465 '''

1466 n = _1_0

1467 if _isFsumTuple(other):

1468 if other is self or self == other:

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

1470 d, r = other._fprs2

1471 if r:

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

1473 if R:

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

1475 d, n = other.as_integer_ratio()

1476 else:

1477 d = self._scalar(other, op)

1478 try:

1479 s = n / d

1480 except Exception as X:

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

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

1483 return self._fset(f)

1484

1485 @property_RO

1486 def imag(self):

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

1488

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

1490 '''

1491 return _0_0

1492

1493 def int_float(self, **raiser_RESIDUAL):

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

1495

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

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

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

1499

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

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

1502 zero or not significant.

1503

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

1505 B{C{RESIDUAL}}.

1506

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

1508 property L{Fsum.as_iscalar}.

1509 '''

1510 s, r = self._fint2

1511 if r:

1512 s, r = self._fprs2

1513 if r: # PYCHOK no cover

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

1515 if R:

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

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

1518 s = float(s)

1519 return s

1520

1521 def is_exact(self):

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

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

1524 '''

1525 return self.residual is INT0

1526

1527 def is_integer(self):

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

1529

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

1531 '''

1532 _, r = self._fint2

1533 return False if r else True

1534

1535 def is_math_fsum(self):

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

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

1538 C{math.fsum} or not.

1539

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

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

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

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

1544 none are.

1545 '''

1546 f = Fsum._math_fsum

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

1548

1549 def is_scalar(self, **raiser_RESIDUAL):

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

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

1552

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

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

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

1556

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

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

1559

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

1561 B{C{RESIDUAL}}.

1562

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

1564 L{Fsum.as_iscalar}.

1565 '''

1566 s, r = self._fprs2

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

1568

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

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

1571 '''

1572 # assert _isFsumTuple(other)

1573 if self._ps and other._ps:

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

1575 else:

1576 f = _0_0

1577 return f

1578

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

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

1581 '''

1582 # assert isscalar(factor)

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

1584 f = self if factor == _1_0 else (

1585 self._neg if factor == _N_1_0 else

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

1587 else:

1588 f = _0_0

1589 return f

1590

1591# @property_RO

1592# def _n_d(self):

1593# n, d = self.as_integer_ratio()

1594# return n / d

1595

1596 @property_RO

1597 def _neg(self):

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

1599 '''

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

1601

1602 @property_RO

1603 def partials(self):

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

1605 '''

1606 return tuple(self._ps)

1607

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

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

1610

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

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

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

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

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

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

1617

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

1619 result (L{Fsum}).

1620

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

1622 B{C{RESIDUAL}}.

1623

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

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

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

1627

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

1629 and L{Fsum.root}.

1630 '''

1631 f = self._copy_2(self.pow)

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

1633

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

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

1636 '''

1637 if _isFsumTuple(other):

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

1639 elif self._scalar(other, op):

1640 x = self._finite(other, op)

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

1642 else:

1643 f = self._pow_0_1(0, other)

1644 return f

1645

1646 def _pow_0_1(self, x, other):

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

1648 '''

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

1650

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

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

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

1654 '''

1655

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

1657 m = mod[0]

1658 # assert _isFsumTuple(b)

1659

1660 def _s(s, r):

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

1662 if R:

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

1664 return s

1665

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

1667 x = _s(*_2scalar2(x))

1668

1669 try:

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

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

1672 if iscomplex(s):

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

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

1675 return self._finite(s)

1676 except Exception as X:

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

1678

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

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

1681 '''

1682 # assert _isFsumTuple(other)

1683 x, r = other._fprs2

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

1685 if f and r:

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

1687 return f

1688

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

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

1691 '''

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

1693 ps = self._ps

1694 if len(ps) > 1:

1695 _mul_Fsum = Fsum._mul_Fsum

1696 if x > 4:

1697 p = self

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

1699 m = x >> 1 # // 2

1700 while m:

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

1702 if (m & 1):

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

1704 m >>= 1 # //= 2

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

1706 f = _mul_Fsum(self, self, op)

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

1708 p = self if x < 4 else f

1709 f = _mul_Fsum(f, p, op)

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

1711 f = self._pow_0_1(x, other)

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

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

1714 else: # PYCHOK no cover

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

1716 f = 0 if x else 1

1717 return f

1718

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

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

1721 '''

1722 s, r = self._fprs2

1723 if r:

1724 # assert s != 0

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

1726 x = int(x)

1727 y = abs(x)

1728 if y > 1:

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

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

1731 return f # Fsum or scalar

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

1733 if _isFsum(f):

1734 s, r = f._fprs2

1735 if r:

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

1737 else: # scalar

1738 s = f

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

1740 # float_pow error iff s is zero

1741 x = -1

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

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

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

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

1746 else: # self**fractional

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

1748 if R:

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

1750 n, d = self.as_integer_ratio()

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

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

1753 s = n / d

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

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

1756

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

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

1759 '''

1760 n = 0

1761 _2s = _2sum

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

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

1764 if x:

1765 i = 0

1766 for p in ps:

1767 x, p = _2s(x, p)

1768 if p:

1769 ps[i] = p

1770 i += 1

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

1772 n += 1

1773 if n:

1774 self._n += n

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

1776 if up:

1777 self._update()

1778 return ps

1779

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

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

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

1783 '''

1784 def _pfs(ps, fs):

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

1786 ps, fs = fs, ps

1787 _fin = _isfinite

1788 for f in fs:

1789 for p in ps:

1790 p *= f

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

1792

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

1794

1795 @property_RO

1796 def _ps_neg(self):

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

1798 '''

1799 for p in self._ps:

1800 yield -p

1801

1802 def _ps_1sum(self, *less):

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

1804 '''

1805 def _1pls(ps, ls):

1806 yield _1_0

1807 for p in ps:

1808 yield p

1809 for p in ls:

1810 yield -p

1811 yield _N_1_0

1812

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

1814

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

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

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

1818 negative respectively positive C{RESIDUAL} threshold)?

1819 '''

1820 if r and raiser:

1821 t = self._RESIDUAL

1822 if RESIDUAL:

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

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

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

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

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

1828 return {}

1829

1830 rdiv = __rtruediv__

1831

1832 @property_RO

1833 def real(self):

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

1835

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

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

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

1839 '''

1840 return float(self._fprs)

1841

1842 @property_RO

1843 def residual(self):

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

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

1846

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

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

1849

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

1851 '''

1852 return self._fprs2.residual

1853

1854 def RESIDUAL(self, *threshold):

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

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

1857

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

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

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

1861 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

1862 current setting.

1863

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

1865

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

1867

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

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

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

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

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

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

1874 testing without I{significant}.

1875 '''

1876 r = self._RESIDUAL

1877 if threshold:

1878 t = threshold[0]

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

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

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

1882 return r

1883

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

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

1886 '''

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

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

1889 if mod is None else _integer_

1890

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

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

1893

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

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

1896

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

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

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

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

1901

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

1903

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

1905 B{C{RESIDUAL}}.

1906

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

1908 '''

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

1910 f = self._copy_2(self.root)

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

1912

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

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

1915 '''

1916 if isscalar(other):

1917 return other

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

1919

1920 def signOf(self, res=True):

1921 '''Determine the sign of this instance.

1922

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

1924 ignore the residual (C{bool}).

1925

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

1927 '''

1928 s, r = self._fprs2

1929 r = (-r) if res else 0

1930 return _signOf(s, r)

1931

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

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

1934

1935 @kwarg lenc_prec_sep_fmt: Optional keyword arguments

1936 for method L{Fsum.toStr}.

1937

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

1939 '''

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

1941

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

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

1944

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

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

1947 @kwarg prec_sep_fmt: Optional keyword arguments for method

1948 L{Fsum2Tuple.toStr}.

1949

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

1951 '''

1952 p = self.classname

1953 if lenc:

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

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

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

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

1958

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

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

1961 '''

1962 f = self._copy_2(self.__truediv__)

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

1964

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

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

1967 '''

1968 if updated:

1969 _pop = self.__dict__.pop

1970 for p in _ROs:

1971 _ = _pop(p, None)

1972# Fsum._fint2._update(self)

1973# Fsum._fprs ._update(self)

1974# Fsum._fprs2._update(self)

1975 return self # for .fset_

1976

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

1978

1979

1980 def _Float_Int(arg, **name_Error):

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

1982 '''

1983 U = Int if isint(arg) else Float

1984 return U(arg, **name_Error)

1985

1986

1987 class DivMod2Tuple(_NamedTuple):

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

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

1990

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

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

1993 '''

1994 _Names_ = (_div_, _mod_)

1995 _Units_ = (_Float_Int, Fsum)

1996

1997

1998 class Fsum2Tuple(_NamedTuple): # in .fstats

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

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

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

2002

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

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

2005 '''

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

2007 _Units_ = (_Float_Int, _Float_Int)

2008

2009 def __abs__(self): # in .fmath

2010 return self._Fsum.__abs__()

2011

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

2013 return bool(self._Fsum)

2014

2015 def __eq__(self, other):

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

2017

2018 def __float__(self):

2019 return self._Fsum.__float__()

2020

2021 def __ge__(self, other):

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

2023

2024 def __gt__(self, other):

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

2026

2027 def __le__(self, other):

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

2029

2030 def __lt__(self, other):

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

2032

2033 def __int__(self):

2034 return self._Fsum.__int__()

2035

2036 def __ne__(self, other):

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

2038

2039 def __neg__(self):

2040 return self._Fsum.__neg__()

2041

2042 __nonzero__ = __bool__ # Python 2-

2043

2044 def __pos__(self):

2045 return self._Fsum.__pos__()

2046

2047 def as_integer_ratio(self):

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

2049

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

2051 '''

2052 return self._Fsum.as_integer_ratio()

2053

2054 @property_RO

2055 def _fint2(self):

2056 return self._Fsum._fint2

2057

2058 @property_RO

2059 def _fprs2(self):

2060 return self._Fsum._fprs2

2061

2062 @Property_RO

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

2064 s, r = _s_r(*self)

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

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

2067

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

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

2070 '''

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

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

2073

2074 def is_exact(self):

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

2076 '''

2077 return self._Fsum.is_exact()

2078

2079 def is_integer(self):

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

2081 '''

2082 return self._Fsum.is_integer()

2083

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

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

2086

2087 @property_RO

2088 def _n(self):

2089 return self._Fsum._n

2090

2091 def _other_op(self, other, which):

2092 C, s = (tuple, self) if isinstance(other, tuple) else (Fsum, self._Fsum)

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

2094

2095 @property_RO

2096 def _ps(self):

2097 return self._Fsum._ps

2098

2099 @property_RO

2100 def _ps_neg(self):

2101 return self._Fsum._ps_neg

2102

2103 def signOf(self, **res):

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

2105 '''

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

2107

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

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

2110

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

2112 @kwarg prec_sep: Optional keyword arguments for function

2113 L{fstr<streprs.fstr>}.

2114 '''

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

2116

2117_Fsum_Fsum2Tuple_types = Fsum, Fsum2Tuple # PYCHOK lines

2118

2119

2120 class ResidualError(_ValueError):

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

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

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

2124

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

2126 '''

2127 pass

2128

2129

2130 try:

2131 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+

2132

2133 # make sure _fsum works as expected (XXX check

2134 # float.__getformat__('float')[:4] == 'IEEE'?)

2135 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover

2136 del _fsum # nope, remove _fsum ...

2137 raise ImportError # ... use _fsum below

2138

2139 Fsum._math_fsum = _sum = _fsum # PYCHOK exported

2140 except ImportError:

2141 _sum = sum # Fsum(NAN) exception fall-back, in .elliptic

2142

2143 def _fsum(xs):

2144 '''(INTERNAL) Precision summation, Python 2.5-.

2145 '''

2146 F = Fsum()

2147 F.name = _fsum.__name__

2148 return F._facc(xs, up=False)._fprs2.fsum

2149

2150

2151 def fsum(xs, floats=False):

2152 '''Precision floating point summation based on/like Python's C{math.fsum}.

2153

2154 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

2155 instance).

2156 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2157 be scalar} (C{bool}).

2158

2159 @return: Precision C{fsum} (C{float}).

2160

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

2162

2163 @raise TypeError: Non-scalar B{C{xs}} item.

2164

2165 @raise ValueError: Invalid or non-finite B{C{xs}} item.

2166

2167 @note: Exception and I{non-finite} handling may differ if not based

2168 on Python's C{math.fsum}.

2169

2170 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.

2171 '''

2172 return _fsum(xs if floats is True else _2floats(xs)) if xs else _0_0 # PYCHOK yield

2173

2174

2175 def fsum_(*xs, **floats):

2176 '''Precision floating point summation of all positional items.

2177

2178 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),

2179 all positional.

2180 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2181 be scalar} (C{bool}).

2182

2183 @see: Function L{fsum<fsums.fsum>} for further details.

2184 '''

2185 return _fsum(xs if _xkwds_get(floats, floats=False) is True else

2186 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield

2187

2188

2189 def fsumf_(*xs):

2190 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.

2191

2192 @see: Function L{fsum_<fsums.fsum_>} for further details.

2193 '''

2194 return _fsum(xs) if xs else _0_0

2195

2196

2197 def fsum1(xs, floats=False):

2198 '''Precision floating point summation, 1-primed.

2199

2200 @arg xs: Iterable of items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

2201 instance).

2202 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2203 be scalar} (C{bool}).

2204

2205 @see: Function L{fsum<fsums.fsum>} for further details.

2206 '''

2207 return _fsum(_1primed(xs if floats is True else _2floats(xs))) if xs else _0_0 # PYCHOK yield

2208

2209

2210 def fsum1_(*xs, **floats):

2211 '''Precision floating point summation, 1-primed of all positional items.

2212

2213 @arg xs: Items to add (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),

2214 all positional.

2215 @kwarg floats: Use C{B{floats}=True} iff I{all} B{C{xs}} items are I{known to

2216 be scalar} (C{bool}).

2217

2218 @see: Function L{fsum_<fsums.fsum_>} for further details.

2219 '''

2220 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) is True else

2221 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield

2222

2223

2224 def fsum1f_(*xs):

2225 '''Precision floating point summation iff I{all} C{B{xs}} items are I{known to be scalar}.

2226

2227 @see: Function L{fsum_<fsums.fsum_>} for further details.

2228 '''

2229 return _fsum(_1primed(xs)) if xs else _0_0

2230

2231

2232 if __name__ == '__main__':

2233

2234 # usage: [env _psum=fsum] python3 -m pygeodesy.fsums

2235

2236 if _getenv(_psum.__name__, NN) == _fsum.__name__:

2237 _psum = _fsum

2238

2239 def _test(n):

2240 # copied from Hettinger, see L{Fsum} reference

2241 from pygeodesy import frandoms, printf

2242

2243 printf(_fsum.__name__, end=_COMMASPACE_)

2244 printf(_psum.__name__, end=_COMMASPACE_)

2245

2246 F = Fsum()

2247 if F.is_math_fsum():

2248 for t in frandoms(n, seeded=True):

2249 assert float(F.fset_(*t)) == _fsum(t)

2250 printf(_DOT_, end=NN)

2251 printf(NN)

2252

2253 _test(128)

2254

2255# **) MIT License

2256#

2257# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

2258#

2259# Permission is hereby granted, free of charge, to any person obtaining a

2260# copy of this software and associated documentation files (the "Software"),

2261# to deal in the Software without restriction, including without limitation

2262# the rights to use, copy, modify, merge, publish, distribute, sublicense,

2263# and/or sell copies of the Software, and to permit persons to whom the

2264# Software is furnished to do so, subject to the following conditions:

2265#

2266# The above copyright notice and this permission notice shall be included

2267# in all copies or substantial portions of the Software.

2268#

2269# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

2270# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

2271# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

2272# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

2273# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

2274# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

2275# OTHER DEALINGS IN THE SOFTWARE.