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 an empty string (or anything

18 other than C{"fsum"}) for backward compatible summation of L{Fsum} partials.

19

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

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

22 exponention of an L{Fsum} instance with a I{relative} C{residual} exceeding

23 the threshold, see methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}

24 and L{Fsum.__itruediv__}.

25'''

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

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

28

29 from pygeodesy.basics import iscomplex, isint, isscalar, signOf, _signOf

30 from pygeodesy.constants import INT0, _isfinite, isinf, isnan, _pos_self, \

31 _0_0, _1_0, _N_1_0, Float, Int

32 from pygeodesy.errors import itemsorted, _OverflowError, _TypeError, \

33 _ValueError, _xError2, _xkwds_get, _xkwds_get_, \

34 _ZeroDivisionError

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

36 _exceeds_, _from_, _iadd_op_, _LANGLE_, \

37 _negative_, _NOTEQUAL_, _not_finite_, \

38 _not_scalar_, _PERCENT_, _PLUS_, _R_, _RANGLE_, \

39 _SLASH_, _SPACE_, _STAR_, _UNDER_

40 from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2

41 from pygeodesy.named import _Named, _NamedTuple, _NotImplemented, Fmt, unstr

42 from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \

43 Property_RO, property_RO

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

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

46

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

48

49__all__ = _ALL_LAZY.fsums

50__version__ = '23.08.27'

51

52_add_op_ = _PLUS_ # in .auxilats.auxAngle

53_eq_op_ = _EQUAL_ * 2 # _DEQUAL_

54_COMMASPACE_R_ = _COMMASPACE_ + _R_

55_exceeds_R_ = _SPACE_ + _exceeds_(_R_)

56_floordiv_op_ = _SLASH_ * 2 # _DSLASH_

57_fset_op_ = _EQUAL_

58_ge_op_ = _RANGLE_ + _EQUAL_

59_gt_op_ = _RANGLE_

60_integer_ = 'integer'

61_le_op_ = _LANGLE_ + _EQUAL_

62_lt_op_ = _LANGLE_

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 _2float(index=None, **name_value): # in .fmath, .fstats

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

76 '''

77 n, v = name_value.popitem() # _xkwds_popitem(name_value)

78 try:

79 v = float(v)

80 if _isfinite(v):

81 return v

82 E, t = _ValueError, _not_finite_

83 except Exception as e:

84 E, t = _xError2(e)

85 if index is not None:

86 n = Fmt.SQUARE(n, index)

87 raise E(n, v, txt=t)

88

89

90 def _2floats(xs, origin=0, sub=False):

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

92 '''

93 try:

94 i, x = origin, None

95 _fin = _isfinite

96 _Fsum = Fsum

97 for x in xs:

98 if isinstance(x, _Fsum):

99 for p in x._ps:

100 yield (-p) if sub else p

101 else:

102 f = float(x)

103 if not _fin(f):

104 raise ValueError(_not_finite_)

105 if f:

106 yield (-f) if sub else f

107 i += 1

108 except Exception as e:

109 E, t = _xError2(e)

110 n = Fmt.SQUARE(xs=i)

111 raise E(n, x, txt=t)

112

113

114 def _Powers(power, xs, origin=1): # in .fmath

115 '''(INTERNAL) Yield each C{xs} as C{float(x**power)}.

116 '''

117 if not isscalar(power):

118 raise _TypeError(power=power, txt=_not_scalar_)

119 try:

120 i, x = origin, None

121 _fin = _isfinite

122 _Fsum = Fsum

123 _pow = pow # XXX math.pow

124 for x in xs:

125 if isinstance(x, _Fsum):

126 P = x.pow(power)

127 for p in P._ps:

128 yield p

129 else:

130 p = _pow(float(x), power)

131 if not _fin(p):

132 raise ValueError(_not_finite_)

133 yield p

134 i += 1

135 except Exception as e:

136 E, t = _xError2(e)

137 n = Fmt.SQUARE(xs=i)

138 raise E(n, x, txt=t)

139

140

141 def _1primed(xs):

142 '''(INTERNAL) 1-Prime the summation of C{xs}

143 arguments I{known} to be C{finite float}.

144 '''

145 yield _1_0

146 for x in xs:

147 if x:

148 yield x

149 yield _N_1_0

150

151

152 def _psum(ps): # PYCHOK used!

153 '''(INTERNAL) Partials summation updating C{ps}, I{overridden below}.

154 '''

155 i = len(ps) - 1 # len(ps) > 2

156 s = ps[i]

157 _2s = _2sum

158 while i > 0:

159 i -= 1

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

161 if r: # sum(ps) became inexact

162 ps[i:] = [s, r] if s else [r]

163 if i > 0:

164 p = ps[i-1] # round half-even

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

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

167 r *= 2

168 t = s + r

169 if r == (t - s):

170 s = t

171 break

172 ps[i:] = [s]

173 return s

174

175

176 def _2scalar(other, _raiser=None):

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

178 '''

179 if isinstance(other, Fsum):

180 s, r = other._fint2

181 if r:

182 s, r = other._fprs2

183 if r: # PYCHOK no cover

184 if _raiser and _raiser(r, s):

185 raise ValueError(_stresidual(_non_zero_, r))

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

187 else:

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

189 if isint(s, both=True):

190 s = int(s)

191 return s

192

193

194 def _strcomplex(s, *args):

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

196 '''

197 c = iscomplex.__name__[2:]

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

199 t = _SPACE_(c, s, _from_, n, pow.__name__)

200 return unstr(t, *args)

201

202

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

204 '''(INTERNAL) Residual error C{str}.

205 '''

206 p = _SPACE_(prefix, Fsum.residual.name)

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

208 for n, v in itemsorted(name_values):

209 n = n.replace(_UNDER_, _SPACE_)

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

211 t = _COMMASPACE_(t, p)

212 return t

213

214

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

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

217 '''

218 s = a + b

219 if not _isfinite(s):

220 u = unstr(_2sum.__name__, a, b)

221 t = Fmt.PARENSPACED(_not_finite_, s)

222 raise _OverflowError(u, txt=t)

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

224 a, b = b, a

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

226

227

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

229 '''Precision floating point I{running} summation.

230

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

232 I{running} precision floating point summation. Accumulation may continue after

233 intermediate, I{running} summuation.

234

235 @note: Accumulated values may be L{Fsum} or C{scalar} instances with C{scalar} meaning

236 type C{float}, C{int} or any C{type} convertible to a single C{float}, having

237 method C{__float__}.

238

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

240 Python's C{math.fsum}.

241

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

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

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

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

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

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

248 '''

249 _math_fsum = None

250 _n = 0

251# _ps = [] # partial sums

252# _px = 0

253 _ratio = None

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

255

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

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

258

259 @arg xs: No, one or more initial values (each C{scalar} or an

260 L{Fsum} instance).

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

262 (C{str}) and C{B{RESIDUAL}=None} for the

263 L{ResidualError} threshold.

264

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

266 '''

267 if name_RESIDUAL:

268 n, r = _xkwds_get_(name_RESIDUAL, name=NN, RESIDUAL=None)

269 if n: # set name ...

270 self.name = n

271 if r is not None:

272 self.RESIDUAL(r) # ... for ResidualError

273# self._n = 0

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

275 if len(xs) > 1:

276 self._facc(_2floats(xs, origin=1), up=False) # PYCHOK yield

277 elif xs: # len(xs) == 1

278 self._ps = [_2float(x=xs[0])]

279 self._n = 1

280

281 def __abs__(self):

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

283 '''

284 s = _fsum(self._ps_1()) # == self._cmp_0(0, ...)

285 return self._copy_n(self.__abs__) if s < 0 else \

286 self._copy_2(self.__abs__)

287

288 def __add__(self, other):

289 '''Return the C{Fsum(B{self}, B{other})}.

290

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

292

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

294

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

296 '''

297 f = self._copy_2(self.__add__)

298 return f._fadd(other, _add_op_)

299

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

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

302 '''

303 s, r = self._fprs2

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

305

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

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

308

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

310

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

312 '''

313 return self.ceil

314

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

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

317

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

319

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

321 '''

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

323 return _signOf(s, 0)

324

325 cmp = __cmp__

326

327 def __divmod__(self, other):

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

329 remainder)}, an C{int} in Python 3+ or C{float} in Python 2-

330 and an L{Fsum}.

331

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

333

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

335 '''

336 f = self._copy_2(self.__divmod__)

337 return f._fdivmod2(other, _divmod_op_)

338

339 def __eq__(self, other):

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

341 '''

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

343

344 def __float__(self):

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

346

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

348 '''

349 return float(self._fprs)

350

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

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

353

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

355

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

357 '''

358 return self.floor

359

360 def __floordiv__(self, other):

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

362

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

364

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

366

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

368 '''

369 f = self._copy_2(self.__floordiv__)

370 return f._floordiv(other, _floordiv_op_)

371

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

373 '''Not implemented.'''

374 return _NotImplemented(self, *other)

375

376 def __ge__(self, other):

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

378 '''

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

380

381 def __gt__(self, other):

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

383 '''

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

385

386 def __hash__(self): # PYCHOK no cover

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

388 '''

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

390

391 def __iadd__(self, other):

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

393

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

395

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

397

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

399 C{scalar} nor L{Fsum}.

400

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

402 '''

403 return self._fadd(other, _iadd_op_)

404

405 def __ifloordiv__(self, other):

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

407

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

409

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

411

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

413

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

415

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

417

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

419

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

421 '''

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

423

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

425 '''Not implemented.'''

426 return _NotImplemented(self, other)

427

428 def __imod__(self, other):

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

430

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

432

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

434

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

436 '''

437 self._fdivmod2(other, _mod_op_ + _fset_op_)

438 return self

439

440 def __imul__(self, other):

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

442

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

444

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

446

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

448

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

450

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

452 '''

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

454

455 def __int__(self):

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

457

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

459 and L{Fsum.__floor__} and properties

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

461 '''

462 i, _ = self._fint2

463 return i

464

465 def __invert__(self): # PYCHOK no cover

466 '''Not implemented.'''

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

468 return _NotImplemented(self)

469

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

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

472

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

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

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

476 version.

477

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

479

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

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

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

483

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

485

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

487 env var C{PYGEODESY_FSUM_RESIDUAL}

488 set or this instance has a non-zero

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

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

491 is a negative or fractional C{scalar}.

492

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

494 C{pow} invocation failed.

495

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

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

498 is a fractional C{scalar} and this

499 instance is negative or has a non-zero

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

501

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

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

504 '''

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

506

507 def __isub__(self, other):

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

509

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

511

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

513

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

515

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

517 '''

518 return self._fsub(other, _isub_op_)

519

520 def __iter__(self):

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

522 '''

523 return iter(self.partials)

524

525 def __itruediv__(self, other):

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

527

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

529

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

531

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

533

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

535 env var C{PYGEODESY_FSUM_RESIDUAL} set.

536

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

538

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

540

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

542

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

544 '''

545 return self._ftruediv(other, _truediv_op_ + _fset_op_)

546

547 def __le__(self, other):

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

549 '''

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

551

552 def __len__(self):

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

554 '''

555 return self._n

556

557 def __lt__(self, other):

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

559 '''

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

561

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

563 '''Not implemented.'''

564 return _NotImplemented(self, other)

565

566 def __mod__(self, other):

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

568

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

570 '''

571 f = self._copy_2(self.__mod__)

572 return f._fdivmod2(other, _mod_op_)[1]

573

574 def __mul__(self, other):

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

576

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

578 '''

579 f = self._copy_2(self.__mul__)

580 return f._fmul(other, _mul_op_)

581

582 def __ne__(self, other):

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

584 '''

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

586

587 def __neg__(self):

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

589 '''

590 return self._copy_n(self.__neg__)

591

592 def __pos__(self):

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

594 '''

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

596

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

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

599

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

601 '''

602 f = self._copy_2(self.__pow__)

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

604

605 def __radd__(self, other):

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

607

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

609 '''

610 f = self._copy_r2(other, self.__radd__)

611 return f._fadd(self, _add_op_)

612

613 def __rdivmod__(self, other):

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

615 remainder)}.

616

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

618 '''

619 f = self._copy_r2(other, self.__rdivmod__)

620 return f._fdivmod2(self, _divmod_op_)

621

622# def __repr__(self):

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

624# '''

625# return self.toRepr(lenc=True)

626

627 def __rfloordiv__(self, other):

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

629

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

631 '''

632 f = self._copy_r2(other, self.__rfloordiv__)

633 return f._floordiv(self, _floordiv_op_)

634

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

636 '''Not implemented.'''

637 return _NotImplemented(self, other)

638

639 def __rmod__(self, other):

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

641

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

643 '''

644 f = self._copy_r2(other, self.__rmod__)

645 return f._fdivmod2(self, _mod_op_)[1]

646

647 def __rmul__(self, other):

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

649

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

651 '''

652 f = self._copy_r2(other, self.__rmul__)

653 return f._fmul(self, _mul_op_)

654

655 def __round__(self, ndigits=None): # PYCHOK no cover

656 '''Not implemented.'''

657 return _NotImplemented(self, ndigits=ndigits)

658

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

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

661

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

663 '''

664 f = self._copy_r2(other, self.__rpow__)

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

666

667 def __rsub__(self, other):

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

669

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

671 '''

672 f = self._copy_r2(other, self.__rsub__)

673 return f._fsub(self, _sub_op_)

674

675 def __rtruediv__(self, other):

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

677

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

679 '''

680 f = self._copy_r2(other, self.__rtruediv__)

681 return f._ftruediv(self, _truediv_op_)

682

683 def __str__(self):

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

685 '''

686 return self.toStr(lenc=True)

687

688 def __sub__(self, other):

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

690

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

692

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

694

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

696 '''

697 f = self._copy_2(self.__sub__)

698 return f._fsub(other, _sub_op_)

699

700 def __truediv__(self, other):

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

702

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

704

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

706

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

708 '''

709 f = self._copy_2(self.__truediv__)

710 return f._ftruediv(other, _truediv_op_)

711

712 __trunc__ = __int__

713

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

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

716 __div__ = __truediv__

717 __idiv__ = __itruediv__

718 __long__ = __int__

719 __nonzero__ = __bool__

720 __rdiv__ = __rtruediv__

721

722 def as_integer_ratio(self):

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

724

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

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

727

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

729 '''

730 n, r = self._fint2

731 if r:

732 i, d = r.as_integer_ratio()

733 n *= d

734 n += i

735 else: # PYCHOK no cover

736 d = 1

737 return n, d

738

739 @property_RO

740 def ceil(self):

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

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

743

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

745

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

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

748 '''

749 s, r = self._fprs2

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

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

752 c += 1

753 return c

754

755 def _cmp_0(self, other, op):

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

757 '''

758 if isscalar(other):

759 if other:

760 s = _fsum(self._ps_1(other))

761 else:

762 s, r = self._fprs2

763 s = _signOf(s, -r)

764 elif isinstance(other, Fsum):

765 s = _fsum(self._ps_1(*other._ps))

766 else:

767 raise self._TypeError(op, other) # txt=_invalid_

768 return s

769

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

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

772

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

774 '''

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

776 f._n = self._n if deep else 1

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

778 return f

779

780 def _copy_0(self, *xs):

781 '''(INTERNAL) Copy with/-out overriding C{partials}.

782 '''

783 # for x in xs:

784 # assert isscalar(x)

785 f = self._Fsum(self._n + len(xs), *xs)

786 if self.name:

787 f._name = self.name # .rename calls _update_attrs

788 return f

789

790 def _copy_2(self, which):

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

792 '''

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

794 f = _Named.copy(self, deep=False, name=which.__name__)

795 # assert f._n == self._n

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

797 return f

798

799 def _copy_n(self, which):

800 '''(INTERNAL) Negated copy for I{monadic} C{__abs__} and C{__neg__}.

801 '''

802 if self._ps:

803 f = self._Fsum(self._n)

804 f._ps[:] = self._ps_n()

805# f._facc_up(up=False)

806 else:

807 f = self._Fsum(self._n, _0_0)

808 f._name = which.__name__ # .rename calls _update_attrs

809 return f

810

811 def _copy_r2(self, other, which):

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

813 '''

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

815 Fsum(other, name=which.__name__) # see ._copy_2

816

817 def _copy_RESIDUAL(self, other):

818 '''(INTERNAL) Copy C{other._RESIDUAL}.

819 '''

820 R = other._RESIDUAL

821 if R is not Fsum._RESIDUAL:

822 self._RESIDUAL = R

823

824 def _copy_up(self, _fprs2=False):

825 '''(INTERNAL) Minimal, anonymous copy.

826 '''

827 f = self._Fsum(self._n, *self._ps)

828 if _fprs2: # only the ._fprs2 2-tuple

829 Fsum._fprs2._update_from(f, self)

830 return f

831

832 def divmod(self, other):

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

834 remainder)}.

835

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

837

838 @return: 2-Tuple C{(quotient, remainder)}, with the C{quotient}

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

840 the C{remainder} an L{Fsum} instance.

841

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

843 '''

844 f = self._copy_2(self.divmod)

845 return f._fdivmod2(other, _divmod_op_)

846

847 def _Error(self, op, other, Error, **txt):

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

849 '''

850 return Error(_SPACE_(self.toRepr(), op, repr(other)), **txt)

851

852 def _ErrorX(self, X, xs, **kwds): # in .fmath

853 '''(INTERNAL) Format a caught exception.

854 '''

855 E, t = _xError2(X)

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

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

858

859 def _facc(self, xs, up=True): # from .elliptic._Defer.Fsum

860 '''(INTERNAL) Accumulate more known C{scalar}s.

861 '''

862 n, ps, _2s = 0, self._ps, _2sum

863 for x in xs: # _iter()

864 # assert isscalar(x) and isfinite(x)

865 i = 0

866 for p in ps:

867 x, p = _2s(x, p)

868 if p:

869 ps[i] = p

870 i += 1

871 ps[i:] = [x]

872 n += 1

873 # assert self._ps is ps

874 if n:

875 self._n += n

876 # Fsum._px = max(Fsum._px, len(ps))

877 if up:

878 self._update()

879 return self

880

881 def _facc_(self, *xs, **up):

882 '''(INTERNAL) Accumulate all positional C{scalar}s.

883 '''

884 return self._facc(xs, **up) if xs else self

885

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

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

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

889# '''

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

891# p = self._ps.pop()

892# if p:

893# n = self._n

894# self._facc_(p, up=False)

895# self._n = n

896# break

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

898

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

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

901 to this instance.

902

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

904 L{Fsum} instances).

905

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

907

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

909

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

911 nor L{Fsum}.

912

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

914 '''

915 if isinstance(xs, Fsum):

916 self._facc(xs._ps)

917 elif isscalar(xs): # for backward compatibility

918 self._facc_(_2float(x=xs)) # PYCHOK no cover

919 elif xs:

920 self._facc(_2floats(xs)) # PYCHOK yield

921 return self

922

923 def fadd_(self, *xs):

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

925 to this instance.

926

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

928 all positional.

929

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

931

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

933

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

935 nor L{Fsum}.

936

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

938 '''

939 return self._facc(_2floats(xs, origin=1)) # PYCHOK yield

940

941 def _fadd(self, other, op): # in .fmath.Fhorner

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

943 '''

944 if isinstance(other, Fsum):

945 if other is self:

946 self._facc_(*other._ps) # == ._facc(tuple(other._ps))

947 elif other._ps:

948 self._facc(other._ps)

949 elif not isscalar(other):

950 raise self._TypeError(op, other) # txt=_invalid_

951 elif other:

952 self._facc_(other)

953 return self

954

955 fcopy = copy # for backward compatibility

956 fdiv = __itruediv__ # for backward compatibility

957 fdivmod = __divmod__ # for backward compatibility

958

959 def _fdivmod2(self, other, op):

960 '''(INTERNAL) C{divmod(B{self}, B{other})} as 2-tuple

961 (C{int} or C{float}, remainder C{self}).

962 '''

963 # result mostly follows CPython function U{float_divmod

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

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

966 q = self._copy_up(_fprs2=True)._ftruediv(other, op).floor

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

968 self -= other * q

969

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

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

972 self += other

973 q -= 1

974

975# t = self.signOf()

976# if t and t != s:

977# from pygeodesy.errors import _AssertionError

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

979 return q, self # q is C{int} in Python 3+, but C{float} in Python 2-

980

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

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

983 '''

984 if _isfinite(other):

985 return other

986 raise ValueError(_not_finite_) if not op else \

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

988

989 def fint(self, raiser=True, name=NN):

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

991

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

993 I{integer} residual is non-zero.

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

995

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

997

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

999

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

1001 '''

1002 i, r = self._fint2

1003 if r and raiser:

1004 t = _stresidual(_integer_, r)

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

1006 n = name or self.fint.__name__

1007 return Fsum(name=n)._fset(i, asis=True)

1008

1009 def fint2(self, **name):

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

1011 the I{integer} residual.

1012

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

1014

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

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

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

1018 '''

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

1020

1021 @Property_RO

1022 def _fint2(self): # see ._fset

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

1024 '''

1025 i = int(self._fprs) # int(self)

1026 r = _fsum(self._ps_1(i)) if len(self._ps) > 1 else (

1027 (self._ps[0] - i) if self._ps else -i)

1028 return i, (r or INT0)

1029

1030 @deprecated_property_RO

1031 def float_int(self): # PYCHOK no cover

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

1033 return self.int_float() # raiser=False

1034

1035 @property_RO

1036 def floor(self):

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

1038 C{float} in Python 2-).

1039

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

1041

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

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

1044 '''

1045 s, r = self._fprs2

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

1047 while r < (f - s): # (s + r) < f

1048 f -= 1

1049 return f

1050

1051# floordiv = __floordiv__ # for naming consistency

1052

1053 def _floordiv(self, other, op): # rather _ffloordiv?

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

1055 '''

1056 q = self._ftruediv(other, op) # == self

1057 return self._fset(q.floor, asis=True) # floor(q)

1058

1059 fmul = __imul__ # for backward compatibility

1060

1061 def _fmul(self, other, op):

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

1063 '''

1064 if isscalar(other):

1065 f = self._mul_scalar(other, op)

1066 elif not isinstance(other, Fsum):

1067 raise self._TypeError(op, other) # txt=_invalid_

1068 elif len(self._ps) != 1:

1069 f = self._mul_Fsum(other, op)

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

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

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

1073 s = self._finite(self._ps[0] * other._ps[0])

1074 return self._fset(s, asis=True, n=len(self) + 1)

1075 return self._fset(f)

1076

1077 def fover(self, over):

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

1079

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

1081

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

1083

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

1085 '''

1086 return float(self.fdiv(over)._fprs)

1087

1088 fpow = __ipow__ # for backward compatibility

1089

1090 def _fpow(self, other, op, *mod):

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

1092 '''

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

1094 s = self._pow_3(other, mod[0], op)

1095 elif mod and mod[0] is None and self.is_integer():

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

1097 i = self._copy_0(self._fint2[0]) # assert _fint2[1] == 0

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

1099 s = i._pow_2(x, other, op) if isscalar(x) else i._fpow(x, op)

1100 else: # pow(self, other) == pow(self, other, None)

1101 p = None

1102 if isinstance(other, Fsum):

1103 x, r = other._fprs2

1104 if r:

1105 if self._raiser(r, x):

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

1107 p = self._pow_scalar(r, other, op)

1108# p = _2scalar(p) # _raiser = None

1109 elif not isscalar(other):

1110 raise self._TypeError(op, other) # txt=_invalid_

1111 else:

1112 x = self._finite(other, op)

1113 s = self._pow_scalar(x, other, op)

1114 if p is not None:

1115 s *= p

1116 return self._fset(s, asis=isint(s), n=max(len(self), 1))

1117

1118 @Property_RO

1119 def _fprs(self):

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

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

1122

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

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

1125 '''

1126 ps = self._ps

1127 n = len(ps) - 1

1128 if n > 1:

1129 s = _psum(ps)

1130 elif n > 0: # len(ps) == 2

1131 s, p = _2sum(*ps) if ps[1] else ps

1132 ps[:] = ([p, s] if s else [p]) if p else [s]

1133 elif n < 0: # see L{Fsum.__init__}

1134 s = _0_0

1135 ps[:] = [s]

1136 else: # len(ps) == 1

1137 s = ps[0]

1138 # assert self._ps is ps

1139 # assert Fsum._fprs2.name not in self.__dict__

1140 return s

1141

1142 @Property_RO

1143 def _fprs2(self):

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

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

1146 '''

1147 s = self._fprs

1148 r = _fsum(self._ps_1(s)) if len(self._ps) > 1 else INT0

1149 return Fsum2Tuple(s, r) # name=Fsum.fsum2.__name__

1150

1151# def _fpsqz(self):

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

1153# '''

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

1155# _ = self._fprs

1156# return self

1157

1158 def _fset(self, other, asis=False, n=1):

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

1160 '''

1161 if other is self:

1162 pass # from ._fmul, ._ftruediv and ._pow_scalar

1163 elif isinstance(other, Fsum):

1164 self._n = other._n

1165 self._ps[:] = other._ps

1166 self._copy_RESIDUAL(other)

1167 # use or zap the C{Property_RO} values

1168 Fsum._fint2._update_from(self, other)

1169 Fsum._fprs ._update_from(self, other)

1170 Fsum._fprs2._update_from(self, other)

1171 elif isscalar(other):

1172 s = other if asis else float(other)

1173 i = int(s) # see ._fint2

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

1175 self._n = n

1176 self._ps[:] = [s]

1177 # Property_RO _fint2, _fprs and _fprs2 can't be a Property:

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

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

1180 else: # PYCHOK no cover

1181 raise self._TypeError(_fset_op_, other) # txt=_invalid_

1182 return self

1183

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

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

1186 from this instance.

1187

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

1189 or L{Fsum} instances).

1190

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

1192

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

1194 '''

1195 return self._facc(_2floats(xs, sub=True)) if xs else self # PYCHOK yield

1196

1197 def fsub_(self, *xs):

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

1199 from this instance.

1200

1201 @arg xs: Values to subtract (C{scalar} or

1202 L{Fsum} instances), all positional.

1203

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

1205

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

1207 '''

1208 return self._facc(_2floats(xs, origin=1, sub=True)) if xs else self # PYCHOK yield

1209

1210 def _fsub(self, other, op):

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

1212 '''

1213 if isinstance(other, Fsum):

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

1215 self._fset(_0_0, asis=True, n=len(self) * 2) # self -= self

1216 elif other._ps:

1217 self._facc(other._ps_n())

1218 elif not isscalar(other):

1219 raise self._TypeError(op, other) # txt=_invalid_

1220 elif self._finite(other, op):

1221 self._facc_(-other)

1222 return self

1223

1224 def _Fsum(self, n, *ps):

1225 '''(INTERNAL) New L{Fsum} instance.

1226 '''

1227 f = Fsum()

1228 f._n = n

1229 if ps:

1230 f._ps[:] = ps

1231 f._copy_RESIDUAL(self)

1232 return f

1233

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

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

1236

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

1238 L{Fsum} instances).

1239

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

1241

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

1243

1244 @note: Accumulation can continue after summation.

1245 '''

1246 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield

1247 return f._fprs

1248

1249 def fsum_(self, *xs):

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

1251

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

1253 all positional.

1254

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

1256

1257 @see: Method L{Fsum.fsum}.

1258 '''

1259 f = self._facc(_2floats(xs, origin=1)) if xs else self # PYCHOK yield

1260 return f._fprs

1261

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

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

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

1265

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

1267 L{Fsum} instances).

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

1269

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

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

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

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

1274 to be I{exact}.

1275

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

1277 '''

1278 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield

1279 t = f._fprs2

1280 if name:

1281 t = t.dup(name=_xkwds_get(name, name=NN))

1282 return t

1283

1284 def fsum2_(self, *xs):

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

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

1287

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

1289 all positional.

1290

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

1292 running C{fsum} and C{delta}, the difference with

1293 the previous running C{fsum} (C{float}s).

1294

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

1296 '''

1297 p, r = self._fprs2

1298 if xs:

1299 s, t = self._facc(_2floats(xs, origin=1))._fprs2 # PYCHOK yield

1300 return s, _fsum((s, -p, r, -t)) # ((s - p) + (r - t))

1301 else: # PYCHOK no cover

1302 return p, _0_0

1303

1304# ftruediv = __itruediv__ # for naming consistency

1305

1306 def _ftruediv(self, other, op):

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

1308 '''

1309 n = _1_0

1310 if isinstance(other, Fsum):

1311 if other is self or other._fprs2 == self._fprs2:

1312 return self._fset(_1_0, asis=True, n=len(self))

1313 d, r = other._fprs2

1314 if r:

1315 if not d: # PYCHOK no cover

1316 d = r

1317 elif self._raiser(r, d):

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

1319 else:

1320 d, n = other.as_integer_ratio()

1321 elif isscalar(other):

1322 d = other

1323 else: # PYCHOK no cover

1324 raise self._TypeError(op, other) # txt=_invalid_

1325 try:

1326 s = 0 if isinf(d) else (

1327 d if isnan(d) else self._finite(n / d))

1328 except Exception as x:

1329 E, t = _xError2(x)

1330 raise self._Error(op, other, E, txt=t)

1331 f = self._mul_scalar(s, _mul_op_) # handles 0, NAN, etc.

1332 return self._fset(f)

1333

1334 @property_RO

1335 def imag(self):

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

1337

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

1339 '''

1340 return _0_0

1341

1342 def int_float(self, raiser=False):

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

1344

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

1346 residual is non-zero.

1347

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

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

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

1351

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

1353

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

1355 '''

1356 s, r = self._fint2

1357 if r:

1358 s, r = self._fprs2

1359 if r and raiser: # PYCHOK no cover

1360 t = _stresidual(_non_zero_, r)

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

1362 s = float(s) # redundant

1363 return s

1364

1365 def is_exact(self):

1366 '''Is this instance' current running C{fsum} considered to

1367 be exact? (C{bool}).

1368 '''

1369 return self.residual is INT0

1370

1371 def is_integer(self):

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

1373

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

1375 '''

1376 _, r = self._fint2

1377 return False if r else True

1378

1379 def is_math_fsum(self):

1380 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1}

1381 and L{fsum1_} plus partials summation are based on

1382 Python's C{math.fsum} or not.

1383

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

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

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

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

1388 none are.

1389 '''

1390 f = Fsum._math_fsum

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

1392

1393 def _mul_Fsum(self, other, op=_mul_op_):

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

1395 '''

1396 # assert isinstance(other, Fsum)

1397 return self._copy_0()._facc(self._ps_x(op, *other._ps), up=False)

1398

1399 def _mul_scalar(self, factor, op):

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

1401 '''

1402 # assert isscalar(factor)

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

1404 if factor == _1_0:

1405 return self

1406 f = self._copy_0()._facc(self._ps_x(op, factor), up=False)

1407 else:

1408 f = self._copy_0(_0_0)

1409 return f

1410

1411 @property_RO

1412 def partials(self):

1413 '''Get this instance' current partial sums (C{tuple} of C{float}s and/or C{int}s).

1414 '''

1415 return tuple(self._ps)

1416

1417 def pow(self, x, *mod):

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

1419

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

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

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

1423

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

1425 result (L{Fsum}).

1426

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

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

1429 or set C{integer} with L{Fsum.fint}.

1430

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

1432 '''

1433 f = self._copy_2(self.pow)

1434 if f and isint(x) and x >= 0 and not mod:

1435 f._pow_int(x, x, _pow_op_) # f **= x

1436 else:

1437 f._fpow(x, _pow_op_, *mod) # f = pow(f, x, *mod)

1438 return f

1439

1440 def _pow_0_1(self, x, other):

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

1442 '''

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

1444

1445 def _pow_2(self, x, other, op):

1446 '''(INTERNAL) 2-arg C{pow(B{self}, scalar B{x})} embellishing errors.

1447 '''

1448 # assert len(self._ps) == 1 and isscalar(x)

1449 b = self._ps[0] # assert isscalar(b)

1450 try: # type(s) == type(x) if x in (_1_0, 1)

1451 s = pow(b, x) # -1**2.3 == -(1**2.3)

1452 if not iscomplex(s):

1453 return self._finite(s) # 0**INF == 0.0, 1**INF==1.0

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

1455 E, t = _ValueError, _strcomplex(s, b, x) # PYCHOK no cover

1456 except Exception as x:

1457 E, t = _xError2(x)

1458 raise self._Error(op, other, E, txt=t)

1459

1460 def _pow_3(self, other, mod, op):

1461 '''(INTERNAL) 3-arg C{pow(B{self}, B{other}, int B{mod} or C{None})}.

1462 '''

1463 b, r = self._fprs2 if mod is None else self._fint2

1464 if r and self._raiser(r, b):

1465 t = _non_zero_ if mod is None else _integer_

1466 E, t = ResidualError, _stresidual(t, r, mod=mod)

1467 else:

1468 try: # b, other, mod all C{int}, unless C{mod} is C{None}

1469 x = _2scalar(other, _raiser=self._raiser)

1470 s = pow(b, x, mod)

1471 if not iscomplex(s):

1472 return self._finite(s)

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

1474 E, t = _ValueError, _strcomplex(s, b, x, mod) # PYCHOK no cover

1475 except Exception as x:

1476 E, t = _xError2(x)

1477 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod), t)

1478 raise self._Error(op, other, E, txt=t)

1479

1480 def _pow_int(self, x, other, op):

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

1482 '''

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

1484 if len(self._ps) > 1:

1485 if x > 2:

1486 p = self._copy_up()

1487 m = 1 # single-bit mask

1488 if x & m:

1489 x -= m # x ^= m

1490 f = p._copy_up()

1491 else:

1492 f = self._copy_0(_1_0)

1493 while x:

1494 p = p._mul_Fsum(p, op) # p **= 2

1495 m += m # m <<= 1

1496 if x & m:

1497 x -= m # x ^= m

1498 f = f._mul_Fsum(p, op) # f *= p

1499 elif x > 1: # self**2

1500 f = self._mul_Fsum(self, op)

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

1502 f = self._pow_0_1(x, other)

1503 elif self._ps: # self._ps[0]**x

1504 f = self._pow_2(x, other, op)

1505 else: # PYCHOK no cover

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

1507 f = 0 if x else 1 # like ._fprs

1508 return self._fset(f, asis=isint(f), n=len(self))

1509

1510 def _pow_scalar(self, x, other, op):

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

1512 '''

1513 s, r = self._fprs2

1514 if isint(x, both=True):

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

1516 y = abs(x)

1517 if y > 1:

1518 if r:

1519 f = self._copy_up()._pow_int(y, other, op)

1520 if x > 0: # > 1

1521 return f

1522 # assert x < 0 # < -1

1523 s, r = f._fprs2

1524 if r:

1525 return self._copy_0(_1_0)._ftruediv(f, op)

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

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

1528 x = -1

1529# elif y > 1: # self**2 or self**-2

1530# f = self._mul_Fsum(self, op)

1531# if x < 0:

1532# f = f._copy_0(_1_0)._ftruediv(f, op)

1533# return f

1534 elif x < 0: # self**-1 == 1 / self

1535 if r:

1536 return self._copy_0(_1_0)._ftruediv(self, op)

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

1538 return self._pow_0_1(x, other) # self or 0.0

1539 elif not isscalar(x): # assert ...

1540 raise self._TypeError(op, other, txt=_not_scalar_)

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

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

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

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

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

1546 return self._copy_0(s)._pow_2(x, other, op)

1547

1548 def _ps_1(self, *less):

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

1550 '''

1551 yield _1_0

1552 for p in self._ps:

1553 if p:

1554 yield p

1555 for p in less:

1556 if p:

1557 yield -p

1558 yield _N_1_0

1559

1560 def _ps_n(self):

1561 '''(INTERNAL) Yield partials, negated.

1562 '''

1563 for p in self._ps:

1564 if p:

1565 yield -p

1566

1567 def _ps_x(self, op, *factors): # see .fmath.Fhorner

1568 '''(INTERNAL) Yield all C{partials} times each B{C{factor}},

1569 in total, up to C{len(partials) * len(factors)} items.

1570 '''

1571 ps = self._ps

1572 if len(ps) < len(factors):

1573 ps, factors = factors, ps

1574 _f = _isfinite

1575 for f in factors:

1576 for p in ps:

1577 p *= f

1578 if _f(p):

1579 yield p

1580 else: # PYCHOK no cover

1581 self._finite(p, op) # throw ValueError

1582

1583 @property_RO

1584 def real(self):

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

1586

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

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

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

1590 '''

1591 return float(self._fprs)

1592

1593 @property_RO

1594 def residual(self):

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

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

1597

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

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

1600

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

1602 '''

1603 return self._fprs2.residual

1604

1605 def _raiser(self, r, s):

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

1607 '''

1608 self._ratio = t = fabs((r / s) if s else r)

1609 return t > self._RESIDUAL

1610

1611 def RESIDUAL(self, *threshold):

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

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

1614

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

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

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

1618 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

1619 current setting.

1620

1621 @return: The previous C{RESIDUAL} setting (C{float}).

1622

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

1624

1625 @note: A L{ResidualError} is thrown if the non-zero I{ratio}

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

1627 '''

1628 r = self._RESIDUAL

1629 if threshold:

1630 t = threshold[0]

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

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

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

1634 if t < 0:

1635 u = self._unstr(self.RESIDUAL, *threshold)

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

1637 self._RESIDUAL = t

1638 return r

1639

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

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

1642 '''

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

1644 RESIDUAL=self._RESIDUAL)

1645 t = t.replace(_COMMASPACE_R_, _exceeds_R_)

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

1647

1648 def signOf(self, res=True):

1649 '''Determine the sign of this instance.

1650

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

1652 ignore the residual (C{bool}).

1653

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

1655 '''

1656 s, r = self._fprs2 if res else (self._fprs, 0)

1657 return _signOf(s, -r)

1658

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

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

1661

1662 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

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

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

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

1666

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

1668 '''

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

1670

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

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

1673

1674 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

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

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

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

1678

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

1680 '''

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

1682

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

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

1685 '''

1686 n = self.named3

1687 if lenc:

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

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

1690

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

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

1693 '''

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

1695

1696 def _update(self): # see ._fset

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

1698 '''

1699 Fsum._fint2._update(self)

1700 Fsum._fprs ._update(self)

1701 Fsum._fprs2._update(self)

1702 return self

1703

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

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

1706 '''

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

1708

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

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

1711 '''

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

1713

1714_allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK assert, see Fsum._fset, -._update

1715

1716

1717 def _Float_Int(arg, **name_Error):

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

1719 '''

1720 U = Int if isint(arg) else Float

1721 return U(arg, **name_Error)

1722

1723

1724 class Fsum2Tuple(_NamedTuple):

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

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

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

1728

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

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

1731 '''

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

1733 _Units_ = (_Float_Int, _Float_Int)

1734

1735 @Property_RO

1736 def Fsum(self):

1737 '''Get this L{Fsum2Tuple} as an L{Fsum}.

1738 '''

1739 f = Fsum(name=self.name)

1740 return f._copy_0(*(s for s in reversed(self) if s))

1741

1742 def is_exact(self):

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

1744 '''

1745 return self.Fsum.is_exact()

1746

1747 def is_integer(self):

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

1749 '''

1750 return self.Fsum.is_integer()

1751

1752

1753 class ResidualError(_ValueError):

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

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

1756

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

1758 '''

1759 pass

1760

1761

1762 try:

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

1764

1765 # make sure _fsum works as expected (XXX check

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

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

1768 del _fsum # nope, remove _fsum ...

1769 raise ImportError # ... use _fsum below

1770

1771 Fsum._math_fsum = _sum = _fsum # PYCHOK exported

1772

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

1774 _psum = _fsum # PYCHOK redef

1775

1776 except ImportError:

1777 _sum = sum # Fsum(NAN) exception fall-back

1778

1779 def _fsum(xs):

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

1781 '''

1782 return Fsum(name=_fsum.__name__)._facc(xs, up=False)._fprs

1783

1784

1785 def fsum(xs, floats=False):

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

1787

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

1789 L{Fsum} instances).

1790 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}

1791 B{C{xs}} are known to be C{float}.

1792

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

1794

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

1796

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

1798

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

1800

1801 @note: Exceptions and I{non-finite} handling may differ if not

1802 based on Python's C{math.fsum}.

1803

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

1805 '''

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

1807

1808

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

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

1811

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

1813 all positional.

1814 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}

1815 B{C{xs}} are known to be C{float}.

1816

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

1818

1819 @see: Function C{fsum}.

1820 '''

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

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

1823

1824

1825 def fsumf_(*xs):

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

1827 '''

1828 return _fsum(xs) if xs else _0_0

1829

1830

1831 def fsum1(xs, floats=False):

1832 '''Precision floating point summation of a few arguments, 1-primed.

1833

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

1835 L{Fsum} instances).

1836 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}

1837 B{C{xs}} are known to be C{float}.

1838

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

1840

1841 @see: Function C{fsum}.

1842 '''

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

1844

1845

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

1847 '''Precision floating point summation of a few arguments, 1-primed.

1848

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

1850 all positional.

1851 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all}

1852 B{C{xs}} are known to be C{float}.

1853

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

1855

1856 @see: Function C{fsum}

1857 '''

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

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

1860

1861

1862 def fsum1f_(*xs):

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

1864 '''

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

1866

1867

1868# **) MIT License

1869#

1870# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

1871#

1872# Permission is hereby granted, free of charge, to any person obtaining a

1873# copy of this software and associated documentation files (the "Software"),

1874# to deal in the Software without restriction, including without limitation

1875# the rights to use, copy, modify, merge, publish, distribute, sublicense,

1876# and/or sell copies of the Software, and to permit persons to whom the

1877# Software is furnished to do so, subject to the following conditions:

1878#

1879# The above copyright notice and this permission notice shall be included

1880# in all copies or substantial portions of the Software.

1881#

1882# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

1883# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

1884# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

1885# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

1886# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

1887# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

1888# OTHER DEALINGS IN THE SOFTWARE.