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_PARTIALS} to string C{"fsum"}) for summation

18 of L{Fsum} partials by Python function C{math.fsum}.

19

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

21 C{"0.0"} as the threshold to throw a L{ResidualError} in division or exponention

22 of an L{Fsum} instance with a I{relative} C{residual} exceeding the threshold,

23 see methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__} and L{Fsum.__itruediv__}.

24'''

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

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

27

28 from pygeodesy.basics import iscomplex, isint, isscalar, itemsorted, \

29 signOf, _signOf

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

31 _0_0, _1_0, _N_1_0, Float, Int

32 from pygeodesy.errors import _OverflowError, _TypeError, _ValueError, _xError, \

33 _xError2, _xkwds_get, _ZeroDivisionError

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

35 _exceeds_, _from_, _iadd_op_, _LANGLE_, _negative_, \

36 _NOTEQUAL_, _not_finite_, _PERCENT_, _PLUS_, _R_, \

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, Fmt, unstr

40 from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \

41 Property_RO, property_RO

42# from pygeodesy.streprs import Fmt, unstr # from .named

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.04.18'

49

50_add_op_ = _PLUS_ # in .auxilats.auxAngle

51_eq_op_ = _EQUAL_ * 2 # _DEQUAL_

52_COMMASPACE_R_ = _COMMASPACE_ + _R_

53_div_ = 'div'

54_exceeds_R_ = _SPACE_ + _exceeds_(_R_)

55_floordiv_op_ = _SLASH_ * 2 # _DSLASH_

56_fset_op_ = _EQUAL_

57_ge_op_ = _RANGLE_ + _EQUAL_

58_gt_op_ = _RANGLE_

59_integer_ = 'integer'

60_le_op_ = _LANGLE_ + _EQUAL_

61_lt_op_ = _LANGLE_

62_mod_ = 'mod'

63_mod_op_ = _PERCENT_

64_mul_op_ = _STAR_

65_ne_op_ = _NOTEQUAL_

66_non_zero_ = 'non-zero'

67_pow_op_ = _STAR_ * 2 # _DSTAR_, in .fmath

68_sub_op_ = _DASH_ # in .auxilats.auxAngle, .fsums

69_truediv_op_ = _SLASH_

70_divmod_op_ = _floordiv_op_ + _mod_op_

71_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle, .fsums

72

73

74 def _2delta(*ab):

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

76 '''

77 try:

78 a, b = _2sum(*ab)

79 except _OverflowError:

80 a, b = ab

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

82

83

84 def _2error(unused):

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

86 '''

87 raise ValueError(_not_finite_)

88

89

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

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

92 '''

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

94 try:

95 v = float(v)

96 return v if _isfinite(v) else _2error(v)

97 except Exception as X:

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

99

100

101 def _X_ps(X): # for _2floats only

102 return X._ps

103

104

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

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

107 '''

108 try:

109 i, x = origin, None

110 _fin = _isfinite

111 _Fs = Fsum

112 for x in xs:

113 if isinstance(x, _Fs):

114 for p in _X(x):

115 yield p

116 else:

117 f = _x(x)

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

119 i += 1

120 except Exception as X:

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

122

123

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

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

126 '''

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

128

129

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

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

132 '''

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

134

135

136 def _2halfeven(s, r, p):

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

138 '''

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

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

141 r *= 2

142 t = s + r

143 if r == (t - s):

144 s = t

145 return s

146

147

148 def _1primed(xs): # in .fmath

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

150 items, all I{known} to be C{finite float}.

151 '''

152 yield _1_0

153 for x in xs:

154 yield x

155 yield _N_1_0

156

157

158 def _2ps(s, r):

159 '''(INTERNAL) Return a C{s} and C{r} pair, I{ps-ordered}.

160 '''

161 return (s, r) if fabs(s) < fabs(r) else (r, s)

162

163

164 def _psum(ps): # PYCHOK used!

165 '''(INTERNAL) Partials sum, updating C{ps}, I{overridden below}.

166 '''

167 # assert isinstance(ps, list)

168 i = len(ps) - 1

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

170 _2s = _2sum

171 while i > 0:

172 i -= 1

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

174 if r: # sum(ps) became inexact

175 if s:

176 ps[i:] = r, s

177 if i > 0:

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

179 break # return s

180 s = r # PYCHOK no cover

181 ps[i:] = s,

182 return s

183

184

185 def _Psum(ps, **name):

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

187 '''

188 F = Fsum(**name) if name else Fsum()

189 if ps:

190 F._ps[:] = ps

191 F._n = len(F._ps)

192 return F

193

194

195 def _Psum_1(p=_1_0, **name):

196 '''(INTERNAL) Return an C{Fsum} from a single partial C{p}.

197 '''

198 F = Fsum(**name) if name else Fsum()

199 F._ps[:] = p,

200 F._n = 1 # len(F._ps)

201 return F

202

203

204 def _2scalar(other, _raiser=None, **mod):

205 '''(INTERNAL) Return B{C{other}} as C{int}, C{float} or C{as-is}.

206 '''

207 if isinstance(other, Fsum):

208 s, r = other._fint2

209 if r:

210 s, r = other._fprs2

211 if r: # PYCHOK no cover

212 if _raiser and _raiser(r, s):

213 t = _stresidual(_non_zero_, r, **mod)

214 raise ResidualError(t, txt=None)

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

216 else:

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

218 if isint(s, both=True):

219 s = int(s)

220 return s

221

222

223 def _strcomplex(s, *args):

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

225 '''

226 c = _strcomplex.__name__[4:]

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

228 t = unstr(pow, *args)

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

230

231

232 def _stresidual(prefix, residual, **name_values):

233 '''(INTERNAL) Residual error as C{str}.

234 '''

235 p = _stresidual.__name__[3:]

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

237 for n, v in itemsorted(name_values):

238 n = n.replace(_UNDER_, _SPACE_)

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

240 t = _COMMASPACE_(t, p)

241 return _SPACE_(prefix, t)

242

243

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

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

246 '''

247 s = a + b

248 if _isfinite(s):

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

250 b, a = a, b

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

252 u = unstr(_2sum, a, b)

253 t = Fmt.PARENSPACED(_not_finite_, s)

254 raise _OverflowError(u, txt=t)

255

256

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

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

259

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

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

262 intermediate, I{running} summuation.

263

264 @note: Accumulated values may be L{Fsum} or C{scalar} instances, any C{type} having

265 method C{__float__} to convert the C{scalar} to a single C{float}.

266

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

268 Python's C{math.fsum}.

269

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

271 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}, U{Kahan

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

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

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

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

276 '''

277 _math_fsum = None

278 _n = 0

279# _ps = [] # partial sums

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

281 _ratio = None # see method _raiser

282 _recursive = bool(_getenv('PYGEODESY_FSUM_RECURSIVE', NN))

283 _RESIDUAL = max(float(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)), _0_0)

284

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

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

287

288 @arg xs: No, one or more initial values, all positional (each C{scalar}

289 or an L{Fsum} instance).

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

291 C{B{RESIDUAL}=None} for the L{ResidualError} threshold.

292

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

294 '''

295 if name_RESIDUAL:

296 n = _xkwds_get(name_RESIDUAL, name=NN)

297 if n: # set name before ...

298 self.name = n

299 r = _xkwds_get(name_RESIDUAL, RESIDUAL=None)

300 if r is not None:

301 self.RESIDUAL(r) # ... ResidualError

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

303 if xs:

304 self._facc(xs, origin=1, up=False)

305

306 def __abs__(self):

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

308 '''

309 s = _fsum(self._ps_1primed()) # == self._cmp_0(0, ...)

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

311

312 def __add__(self, other):

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

314

315 @arg other: An L{Fsum} or C{scalar}.

316

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

318

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

320 '''

321 f = self._copy_2(self.__add__)

322 return f._fadd(other, _add_op_)

323

324 def __bool__(self): # PYCHOK not special in Python 2-

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

326 '''

327 s, r = self._fprs2

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

329

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

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

332

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

334

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

336 '''

337 return self.ceil

338

339 def __cmp__(self, other): # Python 2-

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

341

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

343

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

345 '''

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

347 return _signOf(s, 0)

348

349 cmp = __cmp__

350

351 def __divmod__(self, other):

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

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

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

355

356 @arg other: An L{Fsum} or C{scalar} modulus.

357

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

359 '''

360 f = self._copy_2(self.__divmod__)

361 return f._fdivmod2(other, _divmod_op_)

362

363 def __eq__(self, other):

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

365 '''

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

367

368 def __float__(self):

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

370

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

372 '''

373 return float(self._fprs)

374

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

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

377

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

379

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

381 '''

382 return self.floor

383

384 def __floordiv__(self, other):

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

386

387 @arg other: An L{Fsum} or C{scalar} divisor.

388

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

390

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

392 '''

393 f = self._copy_2(self.__floordiv__)

394 return f._floordiv(other, _floordiv_op_)

395

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

397 '''Not implemented.'''

398 return _NotImplemented(self, *other)

399

400 def __ge__(self, other):

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

402 '''

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

404

405 def __gt__(self, other):

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

407 '''

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

409

410 def __hash__(self): # PYCHOK no cover

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

412 '''

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

414

415 def __iadd__(self, other):

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

417

418 @arg other: An L{Fsum} or C{scalar} instance.

419

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

421

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

423 C{scalar} nor L{Fsum}.

424

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

426 '''

427 return self._fadd(other, _iadd_op_)

428

429 def __ifloordiv__(self, other):

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

431

432 @arg other: An L{Fsum} or C{scalar} divisor.

433

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

435

436 @raise ResidualError: Non-zero residual in B{C{other}}.

437

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

439

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

441

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

443

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

445 '''

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

447

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

449 '''Not implemented.'''

450 return _NotImplemented(self, other)

451

452 def __imod__(self, other):

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

454

455 @arg other: An L{Fsum} or C{scalar} modulus.

456

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

458

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

460 '''

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

462

463 def __imul__(self, other):

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

465

466 @arg other: An L{Fsum} or C{scalar} factor.

467

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

469

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

471

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

473

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

475 '''

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

477

478 def __int__(self):

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

480

481 @see: Methods L{Fsum.int_float}, L{Fsum.__ceil__}

482 and L{Fsum.__floor__} and properties

483 L{Fsum.ceil} and L{Fsum.floor}.

484 '''

485 i, _ = self._fint2

486 return i

487

488 def __invert__(self): # PYCHOK no cover

489 '''Not implemented.'''

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

491 return _NotImplemented(self)

492

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

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

495

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

497 @arg mod: Optional modulus (C{int} or C{None}) for the

498 3-argument C{pow(B{self}, B{other}, B{mod})}

499 version.

500 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

501 (C{bool}), see also method L{RESIDUAL}.

502

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

504

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

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

507 set to C{as_integer} if B{C{mod}} given as C{None}.

508

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

510

511 @raise ResidualError: Non-zero residual in B{C{other}} and

512 env var C{PYGEODESY_FSUM_RESIDUAL}

513 set or this instance has a non-zero

514 residual and either B{C{mod}} is

515 given and non-C{None} or B{C{other}}

516 is a negative or fractional C{scalar}.

517

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

519 C{pow} invocation failed.

520

521 @raise ValueError: If B{C{other}} is a negative C{scalar}

522 and this instance is C{0} or B{C{other}}

523 is a fractional C{scalar} and this

524 instance is negative or has a non-zero

525 residual or B{C{mod}} is given and C{0}.

526

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

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

529 '''

530 return self._fpow(other, _pow_op_ + _fset_op_, *mod, **raiser)

531

532 def __isub__(self, other):

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

534

535 @arg other: An L{Fsum} or C{scalar}.

536

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

538

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

540

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

542 '''

543 return self._fsub(other, _isub_op_)

544

545 def __iter__(self):

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

547 '''

548 return iter(self.partials)

549

550 def __itruediv__(self, other, **raiser):

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

552

553 @arg other: An L{Fsum} or C{scalar} divisor.

554 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

555 (C{bool}), see also method L{RESIDUAL}.

556

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

558

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

560

561 @raise ResidualError: Non-zero residual in B{C{other}} and

562 env var C{PYGEODESY_FSUM_RESIDUAL} set.

563

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

565

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

567

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

569

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

571 '''

572 return self._ftruediv(other, _truediv_op_ + _fset_op_, **raiser)

573

574 def __le__(self, other):

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

576 '''

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

578

579 def __len__(self):

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

581 '''

582 return self._n

583

584 def __lt__(self, other):

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

586 '''

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

588

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

590 '''Not implemented.'''

591 return _NotImplemented(self, other)

592

593 def __mod__(self, other):

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

595

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

597 '''

598 f = self._copy_2(self.__mod__)

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

600

601 def __mul__(self, other):

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

603

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

605 '''

606 f = self._copy_2(self.__mul__)

607 return f._fmul(other, _mul_op_)

608

609 def __ne__(self, other):

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

611 '''

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

613

614 def __neg__(self):

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

616 '''

617 f = self._copy_2(self.__neg__)

618 return f._fset(self._neg)

619

620 def __pos__(self):

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

622 '''

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

624

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

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

627

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

629 '''

630 f = self._copy_2(self.__pow__)

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

632

633 def __radd__(self, other):

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

635

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

637 '''

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

639 return f._fadd(self, _add_op_)

640

641 def __rdivmod__(self, other):

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

643 remainder)}.

644

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

646 '''

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

648 return f._fdivmod2(self, _divmod_op_)

649

650# def __repr__(self):

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

652# '''

653# return self.toRepr(lenc=True)

654

655 def __rfloordiv__(self, other):

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

657

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

659 '''

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

661 return f._floordiv(self, _floordiv_op_)

662

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

664 '''Not implemented.'''

665 return _NotImplemented(self, other)

666

667 def __rmod__(self, other):

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

669

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

671 '''

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

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

674

675 def __rmul__(self, other):

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

677

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

679 '''

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

681 return f._fmul(self, _mul_op_)

682

683 def __round__(self, *ndigits): # PYCHOK no cover

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

685

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

687 '''

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

689 return _Psum_1(round(float(self), *ndigits), # can be C{int}

690 name=self.__round__.__name__)

691

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

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

694

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

696 '''

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

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

699

700 def __rsub__(self, other):

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

702

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

704 '''

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

706 return f._fsub(self, _sub_op_)

707

708 def __rtruediv__(self, other, **raiser):

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

710

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

712 '''

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

714 return f._ftruediv(self, _truediv_op_, **raiser)

715

716 def __str__(self):

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

718 '''

719 return self.toStr(lenc=True)

720

721 def __sub__(self, other):

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

723

724 @arg other: An L{Fsum} or C{scalar}.

725

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

727

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

729 '''

730 f = self._copy_2(self.__sub__)

731 return f._fsub(other, _sub_op_)

732

733 def __truediv__(self, other, **raiser):

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

735

736 @arg other: An L{Fsum} or C{scalar} divisor.

737 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

738 (C{bool}), see also method L{RESIDUAL}.

739

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

741

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

743 '''

744 f = self._copy_2(self.__truediv__)

745 return f._ftruediv(other, _truediv_op_, **raiser)

746

747 __trunc__ = __int__

748

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

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

751 __div__ = __truediv__

752 __idiv__ = __itruediv__

753 __long__ = __int__

754 __nonzero__ = __bool__

755 __rdiv__ = __rtruediv__

756

757 def as_integer_ratio(self):

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

759

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

761 C{int} and with positive C{denominator}.

762

763 @see: Standard C{float.as_integer_ratio} in Python 3+.

764 '''

765 n, r = self._fint2

766 if r:

767 i, d = r.as_integer_ratio()

768 n *= d

769 n += i

770 else: # PYCHOK no cover

771 d = 1

772 return n, d

773

774 @property_RO

775 def ceil(self):

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

777 but C{float} in Python 2-).

778

779 @note: The C{ceil} takes the C{residual} into account.

780

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

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

783 '''

784 s, r = self._fprs2

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

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

787 c += 1

788 return c

789

790 def _cmp_0(self, other, op):

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

792 '''

793 if isinstance(other, Fsum):

794 s = _fsum(self._ps_1primed(*other._ps))

795 elif self._scalar(other, op):

796 s = _fsum(self._ps_1primed(other))

797 else:

798 s, r = self._fprs2

799 s = _signOf(s, -r)

800 return s

801

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

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

804

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

806 '''

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

808 if f._ps is self._ps:

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

810 if not deep:

811 f._n = 1

812 return f

813

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

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

816 '''

817 n = name or which.__name__

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

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

820 # assert f._n == self._n

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

822 return f

823

824 def _copy_2r(self, other, which):

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

826 '''

827 return other._copy_2(which) if isinstance(other, Fsum) else \

828 Fsum(other, name=which.__name__)

829

830# def _copy_RESIDUAL(self, other):

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

832# '''

833# R = other._RESIDUAL

834# if R is not Fsum._RESIDUAL:

835# self._RESIDUAL = R

836

837 def divmod(self, other, **raiser):

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

839 remainder)}.

840

841 @arg other: An L{Fsum} or C{scalar} divisor.

842 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

843 (C{bool}), see also method L{RESIDUAL}.

844

845 @return: A L{DivMod2Tuple}C{(div, mod)}, with quotient C{div}

846 an C{int} in Python 3+ or C{float} in Python 2- and

847 remainder C{mod} an L{Fsum} instance.

848

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

850 '''

851 f = self._copy_2(self.divmod)

852 return f._fdivmod2(other, _divmod_op_, **raiser)

853

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

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

856 '''

857 return Error(_SPACE_(self.toStr(), op, other), **txt_cause)

858

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

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

861 '''

862 E, t = _xError2(X)

863 if mod:

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

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

866

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

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

869 '''

870 E, t = _xError2(X)

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

872 return E(n, txt=t, cause=X)

873

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

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

876 '''

877 if xs:

878 _x = _2floats(xs, **origin_X_x) # PYCHOK yield

879 ps = self._ps

880 ps[:] = self._ps_acc(list(ps), _x, up=up)

881 return self

882

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

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

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

886 '''

887 # assert islistuple(xs)

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

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

890

891 def _facc_neg(self, xs, up=True, **origin):

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

893 '''

894 if xs:

895 def _neg(x):

896 return -x

897

898 _x = _2floats(xs, **origin) # PYCHOK yield

899 ps = self._ps

900 ps[:] = self._ps_acc(list(ps), map(_neg, _x), up=up)

901 return self

902

903 def _facc_power(self, power, xs, which, **raiser): # in .fmath

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

905 '''

906 def _Pow4(p):

907 r = 0

908 if isinstance(p, Fsum):

909 s, r = p._fprs2

910 if r:

911 return _Pow4(s)

912 m = Fsum._pow

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

914 p = s = int(p)

915 m = Fsum._pow_int

916 else:

917 p = s = _2float(power=p)

918 m = Fsum._pow_scalar

919 return m, p, s, r

920

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

922 if p: # and xs:

923 _pow = Fsum._pow_2_3

924 _Fs = Fsum

925 _Ps = _Psum_1()._fset_ps_

926 op = which.__name__

927

928 def _X(X):

929 f = _Pow(X, p, power, op, **raiser)

930 return f._ps if isinstance(f, _Fs) else (f,)

931

932 def _x(x):

933 x = float(x)

934 X = _Ps(x)

935 f = _pow(X, x, s, power, op, **raiser)

936 if r:

937 f *= _pow(X, x, r, power, op, **raiser)

938 return f

939

940 f = self._facc(xs, origin=1, _X=_X, _x=_x)

941 else:

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

943 return f

944

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

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

947 '''

948 if xs:

949 self._ps_acc(self._ps, xs, **up)

950 return self

951

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

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

954 '''

955 if xs:

956 self._ps_acc(self._ps, xs, **up)

957 return self

958

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

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

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

962# '''

963# while len(self._ps) > 1:

964# p = self._ps.pop()

965# if p:

966# n = self._n

967# self._facc_scalar_(p, up=False)

968# self._n = n

969# break

970# return self._update() if up else self # ._fpsqz()

971

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

973 '''Add an iterable of C{scalar} or L{Fsum} instances

974 to this instance.

975

976 @arg xs: Iterable, list, tuple, etc. (C{scalar} or

977 L{Fsum} instances).

978

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

980

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

982

983 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}

984 nor L{Fsum}.

985

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

987 '''

988 if isinstance(xs, Fsum):

989 self._facc_scalar(xs._ps) # tuple

990 elif isscalar(xs): # for backward compatibility

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

992 elif xs: # assert isiterable(xs)

993 self._facc(xs)

994 return self

995

996 def fadd_(self, *xs):

997 '''Add all positional C{scalar} or L{Fsum} instances

998 to this instance.

999

1000 @arg xs: Values to add (C{scalar} or L{Fsum} instances),

1001 all positional.

1002

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

1004

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

1006

1007 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}

1008 nor L{Fsum}.

1009

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

1011 '''

1012 return self._facc_1(xs)

1013

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

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

1016 '''

1017 if isinstance(other, Fsum):

1018 self._facc_scalar(other._ps, **up) # tuple

1019 elif self._scalar(other, op):

1020 self._facc_scalar_(other, **up)

1021 return self

1022

1023 fcopy = copy # for backward compatibility

1024 fdiv = __itruediv__ # for backward compatibility

1025 fdivmod = __divmod__ # for backward compatibility

1026

1027 def _fdivmod2(self, other, op, **raiser):

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

1029 '''

1030 # result mostly follows CPython function U{float_divmod

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

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

1033 f = self._copy_2(self._fdivmod2)

1034 q = f._ftruediv(other, op, **raiser).floor

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

1036 self -= other * q

1037

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

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

1040 self += other

1041 q -= 1

1042# t = self.signOf()

1043# if t and t != s:

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

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

1046

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

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

1049 '''

1050 if _isfinite(other):

1051 return other

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

1053 self._ValueError(op, other, txt=_not_finite_)

1054

1055 def fint(self, raiser=True, **name):

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

1057

1058 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

1059 (C{bool}), see also method L{RESIDUAL}.

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

1061

1062 @return: The C{integer} (L{Fsum}).

1063

1064 @raise ResidualError: Non-zero I{integer} residual.

1065

1066 @see: Methods L{Fsum.int_float} and L{Fsum.is_integer}.

1067 '''

1068 i, r = self._fint2

1069 if r and raiser:

1070 t = _stresidual(_integer_, r)

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

1072 f = self._copy_2(self.fint, **name)

1073 return f._fset(i)

1074

1075 def fint2(self, **name):

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

1077 the I{integer} residual.

1078

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

1080

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

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

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

1084 '''

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

1086

1087 @Property_RO

1088 def _fint2(self): # see ._fset

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

1090 '''

1091 s, r = self._fprs2

1092 i = int(s)

1093 r = _fsum(self._ps_1primed(i)) if r else float(s - i)

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

1095

1096 @deprecated_property_RO

1097 def float_int(self): # PYCHOK no cover

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

1099 return self.int_float() # raiser=False

1100

1101 @property_RO

1102 def floor(self):

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

1104 C{float} in Python 2-).

1105

1106 @note: The C{floor} takes the C{residual} into account.

1107

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

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

1110 '''

1111 s, r = self._fprs2

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

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

1114 f -= 1

1115 return f

1116

1117# floordiv = __floordiv__ # for naming consistency

1118

1119 def _floordiv(self, other, op, **raiser): # rather _ffloordiv?

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

1121 '''

1122 q = self._ftruediv(other, op, **raiser) # == self

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

1124

1125 fmul = __imul__ # for backward compatibility

1126

1127 def _fmul(self, other, op):

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

1129 '''

1130 if isinstance(other, Fsum):

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

1132 f = self._mul_Fsum(other, op)

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

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

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

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

1137 else:

1138 s = self._scalar(other, op)

1139 f = self._mul_scalar(s, op)

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

1141

1142 def fover(self, over, **raiser):

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

1144

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

1146 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

1147 (C{bool}), see also method L{RESIDUAL}.

1148

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

1150

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

1152 '''

1153 return float(self.fdiv(over, **raiser)._fprs)

1154

1155 fpow = __ipow__ # for backward compatibility

1156

1157 def _fpow(self, other, op, *mod, **raiser):

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

1159 '''

1160 if mod:

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

1162 f = self._pow_2_3(self, other, other, op, *mod, **raiser)

1163 elif self.is_integer():

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

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

1166 x = _2scalar(other) # C{int}, C{float} or other

1167 f = self._pow_2_3(i, x, other, op, **raiser) if isscalar(x) else \

1168 _Psum_1(i)._pow( x, other, op, **raiser) # x is Fsum

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

1170 f = self._pow(other, other, op, **raiser)

1171 else: # pow(self, other)

1172 f = self._pow(other, other, op, **raiser)

1173 return self._fset(f, asis=isint(f)) # n=max(len(self), 1)

1174

1175 @Property_RO

1176 def _fprs(self):

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

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

1179

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

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

1182 '''

1183 return self._fprs2.fsum

1184

1185 @Property_RO

1186 def _fprs2(self):

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

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

1189 '''

1190 ps = self._ps

1191 n = len(ps) - 2

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

1193 s = _psum(ps)

1194 n = len(ps) - 2

1195 if n > 0:

1196 r = _fsum(self._ps_1primed(s)) or INT0

1197 return Fsum2Tuple(s, r)

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

1199 ps[:] = _2ps(*_2sum(*ps))

1200 r, s = (INT0, ps[0]) if len(ps) != 2 else ps

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

1202 s, r = ps[0], INT0

1203 else: # len(ps) == 0

1204 s, r = _0_0, INT0

1205 ps[:] = s,

1206 # assert self._ps is ps

1207 return Fsum2Tuple(s, r)

1208

1209# def _fpsqz(self):

1210# '''(INTERNAL) Compress, squeeze the C{partials}.

1211# '''

1212# if len(self._ps) > 2:

1213# _ = self._fprs2

1214# return self

1215

1216 def fset_(self, *xs):

1217 '''Replace this instance' value with C{xs}.

1218

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

1220 instances), all positional.

1221

1222 @return: This instance (C{Fsum}).

1223

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

1225 '''

1226 self._ps[:] = 0,

1227 self._n = 0

1228 return self.fadd(xs) if xs else self._update()

1229

1230 def _fset(self, other, asis=True, n=0):

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

1232 '''

1233 if other is self:

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

1235 elif isinstance(other, Fsum):

1236 self._ps[:] = other._ps

1237 self._n = n or other._n

1238# self._copy_RESIDUAL(other)

1239 # use or zap the C{Property_RO} values

1240 Fsum._fint2._update_from(self, other)

1241 Fsum._fprs ._update_from(self, other)

1242 Fsum._fprs2._update_from(self, other)

1243 elif isscalar(other):

1244 s = other if asis else float(other)

1245 i = int(s) # see ._fint2

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

1247 self._ps[:] = s,

1248 self._n = n or 1

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

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

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

1252 else: # PYCHOK no cover

1253 raise self._TypeError(_fset_op_, other) # AssertionError

1254 return self

1255

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

1257 '''(INTERNAL) Set partials from a known C{Fsum} or C{scalar}.

1258 '''

1259 if isinstance(other, Fsum):

1260 self._ps[:] = other._ps

1261 self._n = n or other._n

1262 else: # assert isscalar(other)

1263 self._ps[:] = other,

1264 self._n = n or 1

1265 return self

1266

1267 def _fset_ps_(self, *xs):

1268 '''(INTERNAL) Set partials to all known scalar C{xs}.

1269 '''

1270 self._ps[:] = xs

1271 self.n = len(xs)

1272 return self

1273

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

1275 '''Subtract an iterable of C{scalar} or L{Fsum} instances from

1276 this instance.

1277

1278 @arg xs: Iterable, list, tuple. etc. (C{scalar} or L{Fsum}

1279 instances).

1280

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

1282

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

1284 '''

1285 return self._facc_neg(xs)

1286

1287 def fsub_(self, *xs):

1288 '''Subtract all positional C{scalar} or L{Fsum} instances from

1289 this instance.

1290

1291 @arg xs: Values to subtract (C{scalar} or L{Fsum} instances),

1292 all positional.

1293

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

1295

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

1297 '''

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

1299 self._facc_neg(xs, origin=1)

1300

1301 def _fsub(self, other, op):

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

1303 '''

1304 if isinstance(other, Fsum):

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

1306 self._fset(_0_0) # n=len(self) * 2, self -= self

1307 elif other._ps:

1308 self._facc_scalar(other._ps_neg)

1309 elif self._scalar(other, op):

1310 self._facc_scalar_(-self._finite(other, op))

1311 return self

1312

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

1314 '''Add more C{scalar} or L{Fsum} instances and summate.

1315

1316 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or

1317 L{Fsum} instances).

1318

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

1320

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

1322

1323 @note: Accumulation can continue after summation.

1324 '''

1325 return self._facc(xs)._fprs

1326

1327 def fsum_(self, *xs):

1328 '''Add all positional C{scalar} or L{Fsum} instances and summate.

1329

1330 @arg xs: Values to add (C{scalar} or L{Fsum} instances), all

1331 positional.

1332

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

1334

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

1336 '''

1337 return self._facc_1(xs)._fprs

1338

1339 def Fsum_(self, *xs):

1340 '''Like method L{Fsum.fsum_} but returning an L{Fsum}.

1341

1342 @return: Current, precision running sum (L{Fsum}).

1343 '''

1344 return self._facc_1(xs)._copy_2(self.Fsum_)

1345

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

1347 '''Add more C{scalar} or L{Fsum} instances and return the

1348 current precision running sum and the C{residual}.

1349

1350 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or L{Fsum}

1351 instances).

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

1353

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

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

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

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

1358 to be I{exact}.

1359

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

1361 '''

1362 t = self._facc(xs)._fprs2

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

1364

1365 def fsum2_(self, *xs):

1366 '''Add any positional C{scalar} or L{Fsum} instances and return

1367 the precision running sum and the C{differential}.

1368

1369 @arg xs: Values to add (C{scalar} or L{Fsum} instances), all

1370 positional.

1371

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

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

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

1375

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

1377 '''

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

1379

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

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

1382 '''

1383 p, q = self._fprs2

1384 if xs:

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

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

1387 else:

1388 return p, _0_0

1389

1390 def fsumf_(self, *xs):

1391 '''Like method L{Fsum.fsum_} but only for C{B{xs}}, I{known to be scalar}.

1392 '''

1393 return self._facc_scalar(xs)._fprs

1394

1395 def Fsumf_(self, *xs):

1396 '''Like method L{Fsum.Fsum_} but only for C{B{xs}}, I{known to be scalar}.

1397 '''

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

1399

1400 def fsum2f_(self, *xs):

1401 '''Like method L{Fsum.fsum2_} but only for C{B{xs}}, I{known to be scalar}.

1402 '''

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

1404

1405# ftruediv = __itruediv__ # for naming consistency?

1406

1407 def _ftruediv(self, other, op, **raiser):

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

1409 '''

1410 n = _1_0

1411 if isinstance(other, Fsum):

1412 if other is self or other == self:

1413 return self._fset(n) # n=len(self)

1414 d, r = other._fprs2

1415 if r:

1416 if d:

1417 if self._raiser(r, d, **raiser):

1418 raise self._ResidualError(op, other, r)

1419 d, n = other.as_integer_ratio()

1420 else: # PYCHOK no cover

1421 d = r

1422 else:

1423 d = self._scalar(other, op)

1424 try:

1425 s = n / d

1426 except Exception as X:

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

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

1429 return self._fset(f) # asis=False

1430

1431 @property_RO

1432 def imag(self):

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

1434

1435 @see: Properties L{Fsum.ceil}, L{Fsum.floor} and L{Fsum.real}.

1436 '''

1437 return _0_0

1438

1439 def int_float(self, raiser=False):

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

1441

1442 @kwarg raiser: If C{True} throw a L{ResidualError} if the

1443 residual is non-zero (C{bool}).

1444

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

1446 otherwise return the C{float} sum if the residual

1447 is zero or if C{B{raiser}=False}.

1448

1449 @raise ResidualError: Non-zero residual and C{B{raiser}=True}.

1450

1451 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.

1452 '''

1453 s, r = self._fint2

1454 if r:

1455 s, r = self._fprs2

1456 if r and raiser: # PYCHOK no cover

1457 t = _stresidual(_non_zero_, r)

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

1459 s = float(s) # redundant

1460 return s

1461

1462 def is_exact(self):

1463 '''Is this instance' running C{fsum} considered to be exact? (C{bool}).

1464 '''

1465 return self.residual is INT0

1466

1467 def is_integer(self):

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

1469

1470 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.

1471 '''

1472 _, r = self._fint2

1473 return False if r else True

1474

1475 def is_math_fsum(self):

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

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

1478 C{math.fsum} or not.

1479

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

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

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

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

1484 none are.

1485 '''

1486 f = Fsum._math_fsum

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

1488

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

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

1491 '''

1492 # assert isinstance(other, Fsum)

1493 if self._ps and other._ps:

1494 f = self._ps_mul(op, *other._ps) # NO ._2scalar

1495 else:

1496 f = _0_0

1497 return f

1498

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

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

1501 '''

1502 # assert isscalar(factor)

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

1504 f = self if factor == _1_0 else (

1505 self._neg if factor == _N_1_0 else

1506 self._ps_mul(op, factor)._2scalar)

1507 else:

1508 f = _0_0

1509 return f

1510

1511 @property_RO

1512 def _neg(self):

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

1514 '''

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

1516

1517 @property_RO

1518 def partials(self):

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

1520 '''

1521 return tuple(self._ps)

1522

1523 def pow(self, x, *mod, **raiser):

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

1525

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

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

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

1529 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

1530 (C{bool}), see also method L{RESIDUAL}.

1531

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

1533 result (L{Fsum}).

1534

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

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

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

1538

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

1540 and L{Fsum.root}.

1541 '''

1542 f = self._copy_2(self.pow)

1543 return f._fpow(x, _pow_op_, *mod, **raiser) # f = pow(f, x, *mod)

1544

1545 def _pow(self, other, unused, op, **raiser):

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

1547 '''

1548 if isinstance(other, Fsum):

1549 x, r = other._fprs2

1550 if r and self._raiser(r, x, **raiser):

1551 raise self._ResidualError(op, other, r)

1552 f = self._pow_scalar(x, other, op, **raiser)

1553 if r:

1554 f *= self._pow_scalar(r, other, op, **raiser)

1555 elif self._scalar(other, op):

1556 x = self._finite(other, op)

1557 f = self._pow_scalar(x, other, op, **raiser)

1558 else:

1559 f = self._pow_0_1(0, other)

1560 return f

1561

1562 def _pow_0_1(self, x, other):

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

1564 '''

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

1566

1567 def _pow_2_3(self, b, x, other, op, *mod, **raiser):

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

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

1570 '''

1571 try:

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

1573 m = mod[0]

1574 b, r = b._fprs2 if m is None else b._fint2

1575 if r and self._raiser(r, b, **raiser):

1576 t = _non_zero_ if m is None else _integer_

1577 raise ResidualError(_stresidual(t, r, mod=m), txt=None)

1578 x = _2scalar(x, _raiser=self._raiser, mod=m)

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

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

1581 if iscomplex(s):

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

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

1584 return self._finite(s)

1585 except Exception as X:

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

1587

1588 def _pow_int(self, x, other, op, **raiser):

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

1590 '''

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

1592 ps = self._ps

1593 if len(ps) > 1:

1594 _mul_Fsum = Fsum._mul_Fsum

1595 if x > 4:

1596 p = self

1597 f = self if (x & 1) else _Psum_1()

1598 m = x >> 1 # // 2

1599 while m:

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

1601 if (m & 1):

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

1603 m >>= 1 # //= 2

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

1605 f = _mul_Fsum(self, self, op)

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

1607 p = self if x < 4 else f

1608 f = _mul_Fsum(f, p, op)._2scalar

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

1610 f = self._pow_0_1(x, other)

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

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

1613 else: # PYCHOK no cover

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

1615 f = 0 if x else 1

1616 return f

1617

1618 def _pow_scalar(self, x, other, op, **raiser):

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

1620 '''

1621 s, r = self._fprs2

1622 if isint(x, both=True):

1623 x = int(x) # Fsum**int

1624 y = abs(x)

1625 if y > 1:

1626 if r:

1627 f = self._pow_int(y, other, op, **raiser)

1628 if x > 0: # > 1

1629 return f

1630 # assert x < 0 # < -1

1631 s, r = f._fprs2 if isinstance(f, Fsum) else (f, 0)

1632 if r:

1633 return _Psum_1()._ftruediv(f, op, **raiser)

1634 # use **= -1 for the CPython float_pow

1635 # error if s is zero, and not s = 1 / s

1636 x = -1

1637 elif x < 0: # == -1: self**(-1) == 1 / self

1638 if r:

1639 return _Psum_1()._ftruediv(self, op, **raiser)

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

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

1642 elif r and self._raiser(r, s, **raiser): # non-zero residual**fractional

1643 # raise self._ResidualError(op, other, r, fractional_power=x)

1644 t = _stresidual(_non_zero_, r, fractional_power=x)

1645 raise self._Error(op, other, ResidualError, txt=t)

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

1647 return self._pow_2_3(s, x, other, op, **raiser)

1648

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

1650 '''(INTERNAL) Accumulate all scalar C{xs} into C{ps}.

1651 '''

1652 n = 0

1653 _2s = _2sum

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

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

1656 if x:

1657 i = 0

1658 for p in ps:

1659 x, p = _2s(x, p)

1660 if p:

1661 ps[i] = p

1662 i += 1

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

1664 n += 1

1665 if n:

1666 self._n += n

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

1668 if up:

1669 self._update()

1670 return ps

1671

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

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

1674 each of the scalar B{C{factors}} and accumulate.

1675 '''

1676 def _pfs(ps, fs):

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

1678 ps, fs = fs, ps

1679 _fin = _isfinite

1680 for f in fs:

1681 for p in ps:

1682 p *= f

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

1684

1685 return _Psum(self._ps_acc([], _pfs(self._ps, factors)))

1686

1687 @property_RO

1688 def _ps_neg(self):

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

1690 '''

1691 for p in self._ps:

1692 yield -p

1693

1694 def _ps_1primed(self, *less):

1695 '''(INTERNAL) Yield partials, 1-primed and subtract any C{less} scalars.

1696 '''

1697 yield _1_0

1698 for p in self._ps:

1699 yield p

1700 for p in less:

1701 yield -p

1702 yield _N_1_0

1703

1704 def _raiser(self, r, s, raiser=True):

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

1706 '''

1707 self._ratio = t = fabs(r / s) if s else 0 # _0_0

1708 return raiser and (t > self._RESIDUAL)

1709

1710 @property_RO

1711 def real(self):

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

1713

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

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

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

1717 '''

1718 return float(self._fprs)

1719

1720 @property_RO

1721 def residual(self):

1722 '''Get this instance' residual (C{float} or C{int}), the

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

1724

1725 @note: If the C{residual is INT0}, the precision running

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

1727

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

1729 '''

1730 return self._fprs2.residual

1731

1732 def RESIDUAL(self, *threshold):

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

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

1735

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

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

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

1739 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

1740 current setting.

1741

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

1743

1744 @raise ValueError: Negative B{C{threshold}}.

1745

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

1747 C{residual / fsum} exceeds the B{C{threshold}}.

1748 '''

1749 r = self._RESIDUAL

1750 if threshold:

1751 t = threshold[0]

1752 t = Fsum._RESIDUAL if t is None else (

1753 float(t) if isscalar(t) else ( # for backward ...

1754 _0_0 if bool(t) else _1_0)) # ... compatibility

1755 if t < 0:

1756 u = _DOT_(self, unstr(self.RESIDUAL, *threshold))

1757 raise _ValueError(u, RESIDUAL=t, txt=_negative_)

1758 self._RESIDUAL = t

1759 return r

1760

1761 def _ResidualError(self, op, other, residual):

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

1763 '''

1764 t = _stresidual(_non_zero_, residual, ratio=self._ratio,

1765 RESIDUAL=self._RESIDUAL)

1766 t = t.replace(_COMMASPACE_R_, _exceeds_R_)

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

1768

1769 def root(self, root, **raiser):

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

1771

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

1773 @kwarg raiser: Use C{B{raiser}=False} to ignore L{ResidualError}s

1774 (C{bool}), see also method L{RESIDUAL}.

1775

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

1777

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

1779 '''

1780 _root_ = self.root.__name__

1781 if isinstance(root, Fsum):

1782 x = root.__rtruediv__(_1_0, **raiser)

1783 else:

1784 try:

1785 x = _1_0 / _2float(root=root)

1786 except Exception as X:

1787 E, t = _xError2(X)

1788 n = _SPACE_(_1_0, _truediv_op_, _root_)

1789 raise E(n, root, txt=t, cause=X)

1790 f = self._copy_2(self.root)

1791 return f._fpow(x, _root_, **raiser) # == pow(f, x)

1792

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

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

1795 '''

1796 if isscalar(other):

1797 return other

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

1799

1800 @property_RO

1801 def _2scalar(self):

1802 '''(INTERNAL) Get this instance as C{scalar} or C{as-is}.

1803 '''

1804 s, r = self._fprs2

1805 return self if r else s

1806

1807 def signOf(self, res=True):

1808 '''Determine the sign of this instance.

1809

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

1811 ignore the residual (C{bool}).

1812

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

1814 '''

1815 s, r = self._fprs2

1816 return _signOf(s, (-r) if res else 0)

1817

1818 def toRepr(self, **prec_sep_fmt_lenc): # PYCHOK signature

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

1820

1821 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

1822 method L{Fsum2Tuple.toRepr} plus C{B{lenc}=True}

1823 (C{bool}) to in-/exclude the current C{[len]}

1824 of this L{Fsum} enclosed in I{[brackets]}.

1825

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

1827 '''

1828 return self._toT(self._fprs2.toRepr, **prec_sep_fmt_lenc)

1829

1830 def toStr(self, **prec_sep_fmt_lenc): # PYCHOK signature

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

1832

1833 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

1834 method L{Fsum2Tuple.toStr} plus C{B{lenc}=True}

1835 (C{bool}) to in-/exclude the current C{[len]}

1836 of this L{Fsum} enclosed in I{[brackets]}.

1837

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

1839 '''

1840 return self._toT(self._fprs2.toStr, **prec_sep_fmt_lenc)

1841

1842 def _toT(self, toT, fmt=Fmt.g, lenc=True, **kwds):

1843 '''(INTERNAL) Helper for C{toRepr} and C{toStr}.

1844 '''

1845 n = self.named3

1846 if lenc:

1847 n = Fmt.SQUARE(n, len(self))

1848 return _SPACE_(n, toT(fmt=fmt, **kwds))

1849

1850 def _TypeError(self, op, other, **txt): # PYCHOK no cover

1851 '''(INTERNAL) Return a C{TypeError}.

1852 '''

1853 return self._Error(op, other, _TypeError, **txt)

1854

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

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

1857 '''

1858 if updated:

1859 _pop = self.__dict__.pop

1860 for p in _ROs:

1861 _ = _pop(p, None)

1862# Fsum._fint2._update(self)

1863# Fsum._fprs ._update(self)

1864# Fsum._fprs2._update(self)

1865 return self # for .fset_

1866

1867 def _ValueError(self, op, other, **txt): # PYCHOK no cover

1868 '''(INTERNAL) Return a C{ValueError}.

1869 '''

1870 return self._Error(op, other, _ValueError, **txt)

1871

1872 def _ZeroDivisionError(self, op, other, **txt): # PYCHOK no cover

1873 '''(INTERNAL) Return a C{ZeroDivisionError}.

1874 '''

1875 return self._Error(op, other, _ZeroDivisionError, **txt)

1876

1877_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK assert, see Fsum._fset, -._update

1878

1879

1880 def _Float_Int(arg, **name_Error):

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

1882 '''

1883 U = Int if isint(arg) else Float

1884 return U(arg, **name_Error)

1885

1886

1887 class DivMod2Tuple(_NamedTuple):

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

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

1890

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

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

1893 '''

1894 _Names_ = (_div_, _mod_)

1895 _Units_ = (_Float_Int, Fsum)

1896

1897

1898 class Fsum2Tuple(_NamedTuple):

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

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

1901 item is either C{float} or C{int}.

1902

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

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

1905 '''

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

1907 _Units_ = (_Float_Int, _Float_Int)

1908

1909 @Property_RO

1910 def _Fsum(self):

1911 '''(INTERNAL) Get this L{Fsum2Tuple} as an L{Fsum}.

1912 '''

1913 s, r = map(float, self)

1914 return _Psum(_2ps(s, r), name=self.name)

1915

1916 def is_exact(self):

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

1918 '''

1919 return self._Fsum.is_exact()

1920

1921 def is_integer(self):

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

1923 '''

1924 return self._Fsum.is_integer()

1925

1926

1927 class ResidualError(_ValueError):

1928 '''Error raised for an operation involving a L{pygeodesy.sums.Fsum}

1929 instance with a non-zero C{residual}, I{integer} or otherwise.

1930

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

1932 '''

1933 pass

1934

1935

1936 try:

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

1938

1939 # make sure _fsum works as expected (XXX check

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

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

1942 del _fsum # nope, remove _fsum ...

1943 raise ImportError # ... use _fsum below

1944

1945 Fsum._math_fsum = _sum = _fsum # PYCHOK exported

1946

1947 if _getenv('PYGEODESY_FSUM_PARTIALS', NN) == _fsum.__name__:

1948 _psum = _fsum # PYCHOK re-def

1949

1950 except ImportError:

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

1952

1953 def _fsum(xs):

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

1955 '''

1956 f = Fsum()

1957 f.name = _fsum.__name__

1958 return f.fsum(xs)

1959

1960

1961 def fsum(xs, floats=False):

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

1963

1964 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum}

1965 instances).

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

1967 to be C{float} scalars (C{bool}).

1968

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

1970

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

1972

1973 @raise TypeError: Non-scalar B{C{xs}} value.

1974

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

1976

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

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

1979

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

1981 '''

1982 return _fsum(xs if floats else _2floats(xs)) if xs else _0_0 # PYCHOK yield

1983

1984

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

1986 '''Precision floating point summation of all positional arguments.

1987

1988 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all

1989 positional.

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

1991 to be scalar} (C{bool}).

1992

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

1994

1995 @see: Function C{fsum}.

1996 '''

1997 return _fsum(xs if _xkwds_get(floats, floats=False) else

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

1999

2000

2001 def fsumf_(*xs):

2002 '''Precision floating point summation, L{fsum_}C{(*B{xs}, floats=True)},

2003 but only for C{B{xs}} I{known to be scalar}.

2004 '''

2005 return _fsum(xs) if xs else _0_0

2006

2007

2008 def fsum1(xs, floats=False):

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

2010

2011 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum}

2012 instances).

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

2014 to be C{float}.

2015

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

2017

2018 @see: Function C{fsum}.

2019 '''

2020 return _fsum(_1primed(xs if floats else _2floats(xs))) if xs else _0_0 # PYCHOK yield

2021

2022

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

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

2025

2026 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all

2027 positional.

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

2029 to be scalar} (C{bool}).

2030

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

2032

2033 @see: Function C{fsum}

2034 '''

2035 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) else

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

2037

2038

2039 def fsum1f_(*xs):

2040 '''Precision floating point summation, L{fsum1_}C{(*B{xs}, floats=True)},

2041 but only for C{B{xs}} I{known to be scalar}.

2042 '''

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

2044

2045

2046 if __name__ == '__main__':

2047

2048 # usage: [env PYGEODESY_FSUM_PARTIALS=fsum] python3 -m pygeodesy.fsums

2049

2050 def _test(n):

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

2052 from pygeodesy import printf

2053 from random import gauss, random, shuffle

2054

2055 printf(_fsum.__name__, end=_COMMASPACE_)

2056 printf(_psum.__name__, end=_COMMASPACE_)

2057

2058 F = Fsum()

2059 if F.is_math_fsum():

2060 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 10

2061 for _ in range(n):

2062 t = list(c)

2063 s = 0

2064 for _ in range(n * 8):

2065 v = gauss(0, random())**7 - s

2066 t.append(v)

2067 s += v

2068 shuffle(t)

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

2070 printf(_DOT_, end=NN)

2071 printf(NN)

2072

2073 _test(128)

2074

2075# **) MIT License

2076#

2077# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

2078#

2079# Permission is hereby granted, free of charge, to any person obtaining a

2080# copy of this software and associated documentation files (the "Software"),

2081# to deal in the Software without restriction, including without limitation

2082# the rights to use, copy, modify, merge, publish, distribute, sublicense,

2083# and/or sell copies of the Software, and to permit persons to whom the

2084# Software is furnished to do so, subject to the following conditions:

2085#

2086# The above copyright notice and this permission notice shall be included

2087# in all copies or substantial portions of the Software.

2088#

2089# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

2090# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

2091# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

2092# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

2093# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

2094# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

2095# OTHER DEALINGS IN THE SOFTWARE.