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 for the

21 threshold to throw a L{ResidualError} in division or exponention of an L{Fsum}

22 instance with a I{relative} C{residual} exceeding the threshold, see methods

23 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, map1, neg, \

29 signOf, _signOf

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

31 _0_0, _1_0, _N_1_0

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_, _LANGLE_, _negative_, \

37 _NOTEQUAL_, _not_finite_, _not_scalar_, \

38 _PERCENT_, _PLUS_, _R_, _RANGLE_, _SLASH_, \

39 _SPACE_, _STAR_, _UNDER_

40 from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys, _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

46

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

48

49__all__ = _ALL_LAZY.fsums

50__version__ = '23.03.19'

51

52_add_op_ = _PLUS_

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_

69_truediv_op_ = _SLASH_

70_divmod_op_ = _floordiv_op_ + _mod_op_

71

72_pos_self = _1_0.__pos__() is _1_0 # in .vector3dBase

73

74

75 def _2float(index=None, **name_value):

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

77 '''

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

79 try:

80 v = float(v)

81 if _isfinite(v):

82 return v

83 E, t = _ValueError, _not_finite_

84 except Exception as X:

85 E, t = _xError2(X)

86 if index is not None:

87 n = Fmt.SQUARE(n, index)

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

89

90

91 def _2floats(xs, origin=0, primed=False, sub=False, floats=False):

92 '''(INTERNAL) Yield all B{C{xs}} as C{float}s.

93 '''

94 _2f = _2float

95 if primed:

96 yield _1_0

97 i = origin

98 for x in xs:

99 if floats:

100 yield x

101 elif isinstance(x, Fsum):

102 ps = x._ps

103 if ps:

104 if sub:

105 ps = map(neg, ps)

106 for x in ps:

107 yield x

108 else:

109 x = _2f(index=i, xs=x)

110 if x:

111 yield (-x) if sub else x

112 i += 1

113 if primed:

114 yield _N_1_0

115

116

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

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

119 '''

120 i = None

121 s = 2 == power

122 _2f = _2float

123 try:

124 for i, x in enumerate(xs):

125 if isinstance(x, Fsum):

126 T = x._mul_Fsum(x) if s else x.pow(power)

127 for t in T._ps:

128 yield t

129 else:

130 t = _2f(_=x)

131 if t:

132 yield _2f(__=t**power)

133 except Exception as X:

134 E, t = _xError2(X)

135 if i is None:

136 i = Fmt.PARENSPACED(xs=xs)

137 else:

138 i = Fmt.SQUARE(xs=i + origin)

139 i = Fmt.PARENSPACED(i, x)

140 raise E(i, txt=t)

141

142

143 def _psum(ps): # PYCHOK used!

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

145 '''

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

147 s = ps[i]

148 _2s = _2sum

149 while i > 0:

150 i -= 1

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

152 if r: # sum(ps) became inexact

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

154 if i > 0:

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

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

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

158 r *= 2

159 t = s + r

160 if r == (t - s):

161 s = t

162 break

163 ps[i:] = [s]

164 return s

165

166

167 def _2scalar(other, _raiser=None):

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

169 '''

170 if isinstance(other, Fsum):

171 s, r = other._fint2

172 if r:

173 s, r = other._fprs2

174 if r: # PYCHOK no cover

175 if _raiser and _raiser(r, s):

176 raise ValueError(_stresidual(_non_zero_, r))

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

178 else:

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

180 if isint(s, both=True):

181 s = int(s)

182 return s

183

184

185 def _strcomplex(s, *args):

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

187 '''

188 c = iscomplex.__name__[2:]

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

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

191 return unstr(t, *args)

192

193

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

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

196 '''

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

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

199 for n, v in itemsorted(name_values):

200 n = n.replace(_UNDER_, _SPACE_)

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

202 t = _COMMASPACE_(t, p)

203 return t

204

205

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

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

208 '''

209 s = a + b

210 if not _isfinite(s):

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

212 t = Fmt.PARENSPACED(_not_finite_, s)

213 raise _OverflowError(u, txt=t)

214 r = (a - (s - b)) if fabs(a) < fabs(b) else \

215 (b - (s - a)) # fabs(a) >= fabs(b)

216 return s, r

217

218

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

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

221

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

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

224 intermediate, I{running} summuation.

225

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

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

228 method C{__float__}.

229

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

231 Python's C{math.fsum}.

232

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

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

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

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

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

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

239 '''

240 _math_fsum = None

241 _n = 0

242# _ps = [] # partial sums

243# _px = 0

244 _ratio = None

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

246

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

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

249

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

251 L{Fsum} instance).

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

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

254 L{ResidualError} threshold.

255

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

257 '''

258 if name_RESIDUAL:

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

260 if n: # set name ...

261 self.name = n

262 if r is not None:

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

264# self._n = 0

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

266 if len(xs) > 1:

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

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

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

270 self._n = 1

271

272 def __abs__(self):

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

274 '''

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

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

277 self._copy_2(self.__abs__)

278

279 def __add__(self, other):

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

281

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

283

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

285

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

287 '''

288 f = self._copy_2(self.__add__)

289 return f._fadd(other, _add_op_)

290

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

292 '''Return C{True} if this instance is non-zero.

293 '''

294 return self != 0

295

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

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

298

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

300

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

302 '''

303 return self.ceil

304

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

306 '''Compare this with an other instance or scalar.

307

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

309

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

311 '''

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

313 return -1 if s < 0 else (+1 if s > 0 else 0)

314

315 cmp = __cmp__

316

317 def __divmod__(self, other):

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

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

320 and an L{Fsum}.

321

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

323

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

325 '''

326 f = self._copy_2(self.__divmod__)

327 return f._fdivmod2(other, _divmod_op_)

328

329 def __eq__(self, other):

330 '''Compare this with an other instance or scalar.

331 '''

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

333

334 def __float__(self):

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

336

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

338 '''

339 return float(self._fprs)

340

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

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

343

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

345

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

347 '''

348 return self.floor

349

350 def __floordiv__(self, other):

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

352

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

354

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

356

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

358 '''

359 f = self._copy_2(self.__floordiv__)

360 return f._floordiv(other, _floordiv_op_)

361

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

363 '''Not implemented.'''

364 return _NotImplemented(self, *other)

365

366 def __ge__(self, other):

367 '''Compare this with an other instance or scalar.

368 '''

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

370

371 def __gt__(self, other):

372 '''Compare this with an other instance or scalar.

373 '''

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

375

376 def __hash__(self): # PYCHOK no cover

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

378 '''

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

380

381 def __iadd__(self, other):

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

383

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

385

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

387

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

389 C{scalar} nor L{Fsum}.

390

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

392 '''

393 return self._fadd(other, _iadd_)

394

395 def __ifloordiv__(self, other):

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

397

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

399

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

401

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

403

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

405

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

407

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

409

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

411 '''

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

413

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

415 '''Not implemented.'''

416 return _NotImplemented(self, other)

417

418 def __imod__(self, other):

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

420

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

422

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

424

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

426 '''

427 self._fdivmod2(other, _mod_op_ + _fset_op_)

428 return self

429

430 def __imul__(self, other):

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

432

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

434

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

436

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

438

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

440

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

442 '''

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

444

445 def __int__(self):

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

447

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

449 and L{Fsum.__floor__} and properties

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

451 '''

452 i, _ = self._fint2

453 return i

454

455 def __invert__(self): # PYCHOK no cover

456 '''Not implemented.'''

457 # Luciano Ramalho, "Fluent Python", 2nd Ed, page 567, O'Reilly, 2022

458 return _NotImplemented(self)

459

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

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

462

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

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

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

466 version.

467

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

469

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

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

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

473

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

475

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

477 env var C{PYGEODESY_FSUM_RESIDUAL}

478 set or this instance has a non-zero

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

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

481 is a negative or fractional C{scalar}.

482

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

484 C{pow} invocation failed.

485

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

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

488 is a fractional C{scalar} and this

489 instance is negative or has a non-zero

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

491

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

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

494 '''

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

496

497 def __isub__(self, other):

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

499

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

501

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

503

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

505

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

507 '''

508 return self._fsub(other, _sub_op_ + _fset_op_)

509

510 def __iter__(self):

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

512 '''

513 return iter(self.partials)

514

515 def __itruediv__(self, other):

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

517

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

519

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

521

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

523

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

525 env var C{PYGEODESY_FSUM_RESIDUAL} set.

526

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

528

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

530

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

532

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

534 '''

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

536

537 def __le__(self, other):

538 '''Compare this with an other instance or scalar.

539 '''

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

541

542 def __len__(self):

543 '''Return the I{total} number accumulations (C{int}).

544 '''

545 return self._n

546

547 def __lt__(self, other):

548 '''Compare this with an other instance or scalar.

549 '''

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

551

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

553 '''Not implemented.'''

554 return _NotImplemented(self, other)

555

556 def __mod__(self, other):

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

558

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

560 '''

561 f = self._copy_2(self.__mod__)

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

563

564 def __mul__(self, other):

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

566

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

568 '''

569 f = self._copy_2(self.__mul__)

570 return f._fmul(other, _mul_op_)

571

572 def __ne__(self, other):

573 '''Compare this with an other instance or scalar.

574 '''

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

576

577 def __neg__(self):

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

579 '''

580 return self._copy_n(self.__neg__)

581

582 def __pos__(self):

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

584 '''

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

586

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

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

589

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

591 '''

592 f = self._copy_2(self.__pow__)

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

594

595 def __radd__(self, other):

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

597

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

599 '''

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

601 return f._fadd(self, _add_op_)

602

603 def __rdivmod__(self, other):

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

605 remainder)}.

606

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

608 '''

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

610 return f._fdivmod2(self, _divmod_op_)

611

612# def __repr__(self):

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

614# '''

615# return self.toRepr(lenc=True)

616

617 def __rfloordiv__(self, other):

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

619

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

621 '''

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

623 return f._floordiv(self, _floordiv_op_)

624

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

626 '''Not implemented.'''

627 return _NotImplemented(self, other)

628

629 def __rmod__(self, other):

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

631

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

633 '''

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

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

636

637 def __rmul__(self, other):

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

639

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

641 '''

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

643 return f._fmul(self, _mul_op_)

644

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

646 '''Not implemented.'''

647 return _NotImplemented(self, ndigits=ndigits)

648

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

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

651

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

653 '''

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

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

656

657 def __rsub__(self, other):

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

659

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

661 '''

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

663 return f._fsub(self, _sub_op_)

664

665 def __rtruediv__(self, other):

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

667

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

669 '''

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

671 return f._ftruediv(self, _truediv_op_)

672

673 def __sizeof__(self): # PYCHOK not special in Python 2-

674 '''Return the current size of this instance in C{bytes}.

675 '''

676 return sum(map1(_sys.getsizeof, self._fint2,

677 self._fint2[0],

678 self._fint2[1],

679 self._fprs,

680 self._fprs2,

681 self._fprs2.fsum,

682 self._fprs2.residual,

683 self._n,

684 self._ps, *self._ps))

685

686 def __str__(self):

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

688 '''

689 return self.toStr(lenc=True)

690

691 def __sub__(self, other):

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

693

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

695

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

697

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

699 '''

700 f = self._copy_2(self.__sub__)

701 return f._fsub(other, _sub_op_)

702

703 def __truediv__(self, other):

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

705

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

707

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

709

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

711 '''

712 f = self._copy_2(self.__truediv__)

713 return f._ftruediv(other, _truediv_op_)

714

715 __trunc__ = __int__

716

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

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

719 __div__ = __truediv__

720 __idiv__ = __itruediv__

721 __long__ = __int__

722 __nonzero__ = __bool__

723 __rdiv__ = __rtruediv__

724

725 def as_integer_ratio(self):

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

727

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

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

730

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

732 '''

733 n, r = self._fint2

734 if r:

735 i, d = r.as_integer_ratio()

736 n *= d

737 n += i

738 else: # PYCHOK no cover

739 d = 1

740 return n, d

741

742 @property_RO

743 def ceil(self):

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

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

746

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

748

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

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

751 '''

752 s, r = self._fprs2

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

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

755 c += 1

756 return c

757

758 def _cmp_0(self, other, op):

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

760 '''

761 if isscalar(other):

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

763 elif isinstance(other, Fsum):

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

765 else:

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

767 return s

768

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

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

771

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

773 '''

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

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

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

777 return f

778

779 def _copy_0(self, *xs):

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

781 '''

782 # for x in xs:

783 # assert isscalar(x)

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

785 if self.name:

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

787 return f

788

789 def _copy_2(self, which):

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

791 '''

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

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

794 # assert f._n == self._n

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

796 return f

797

798 def _copy_n(self, which):

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

800 '''

801 if self._ps:

802 f = self._Fsum(self._n)

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

804# f._facc_up(up=False)

805 else:

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

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

808 return f

809

810 def _copy_r2(self, other, which):

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

812 '''

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

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

815

816 def _copy_RESIDUAL(self, other):

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

818 '''

819 R = other._RESIDUAL

820 if R is not Fsum._RESIDUAL:

821 self._RESIDUAL = R

822

823 def _copy_up(self, _fprs2=False):

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

825 '''

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

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

828 Fsum._fprs2._update_from(f, self)

829 return f

830

831 def divmod(self, other):

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

833 remainder)}.

834

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

836

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

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

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

840

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

842 '''

843 f = self._copy_2(self.divmod)

844 return f._fdivmod2(other, _divmod_op_)

845

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

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

848 '''

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

850

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

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

853 '''

854 E, t = _xError2(X)

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

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

857

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

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

860 '''

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

862 for x in xs: # _iter()

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

864 i = 0

865 for p in ps:

866 x, p = _2s(x, p)

867 if p:

868 ps[i] = p

869 i += 1

870 ps[i:] = [x]

871 n += 1

872 # assert self._ps is ps

873 if n:

874 self._n += n

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

876 if up:

877 self._update()

878 return self

879

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

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

882 '''

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

884

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

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

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

888# '''

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

890# p = self._ps.pop()

891# if p:

892# n = self._n

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

894# self._n = n

895# break

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

897

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

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

900 to this instance.

901

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

903 L{Fsum} instances).

904

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

906

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

908

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

910 nor L{Fsum}.

911

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

913 '''

914 if isinstance(xs, Fsum):

915 self._facc(xs._ps)

916 elif isscalar(xs): # for backward compatibility

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

918 elif xs:

919 self._facc(_2floats(xs))

920 return self

921

922 def fadd_(self, *xs):

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

924 to this instance.

925

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

927 all positional.

928

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

930

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

932

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

934 nor L{Fsum}.

935

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

937 '''

938 return self._facc(_2floats(xs, origin=1))

939

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

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

942 '''

943 if isinstance(other, Fsum):

944 if other is self:

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

946 elif other._ps:

947 self._facc(other._ps)

948 elif not isscalar(other):

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

950 elif other:

951 self._facc_(other)

952 return self

953

954 fcopy = copy # for backward compatibility

955 fdiv = __itruediv__ # for backward compatibility

956 fdivmod = __divmod__ # for backward compatibility

957

958 def _fdivmod2(self, other, op):

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

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

961 '''

962 # result mostly follows CPython function U{float_divmod

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

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

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

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

967 self -= other * q

968

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

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

971 self += other

972 q -= 1

973

974# t = self.signOf()

975# if t and t != s:

976# from pygeodesy.errors import _AssertionError

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

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

979

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

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

982 '''

983 if _isfinite(other):

984 return other

985 raise ValueError(_not_finite_) if not op else \

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

987

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

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

990

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

992 I{integer} residual is non-zero.

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

994

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

996

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

998

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

1000 '''

1001 i, r = self._fint2

1002 if r and raiser:

1003 t = _stresidual(_integer_, r)

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

1005 n = name or self.fint.__name__

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

1007

1008 def fint2(self, **name):

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

1010 the I{integer} residual.

1011

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

1013

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

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

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

1017 '''

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

1019

1020 @Property_RO

1021 def _fint2(self): # see ._fset

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

1023 '''

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

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

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

1027 return i, (r or INT0)

1028

1029 @deprecated_property_RO

1030 def float_int(self): # PYCHOK no cover

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

1032 return self.int_float() # raiser=False

1033

1034 @property_RO

1035 def floor(self):

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

1037 C{float} in Python 2-).

1038

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

1040

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

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

1043 '''

1044 s, r = self._fprs2

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

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

1047 f -= 1

1048 return f

1049

1050# floordiv = __floordiv__ # for naming consistency

1051

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

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

1054 '''

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

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

1057

1058 fmul = __imul__ # for backward compatibility

1059

1060 def _fmul(self, other, op):

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

1062 '''

1063 if isscalar(other):

1064 f = self._mul_scalar(other, op)

1065 elif not isinstance(other, Fsum):

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

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

1068 f = self._mul_Fsum(other, op)

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

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

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

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

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

1074 return self._fset(f)

1075

1076 def fover(self, over):

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

1078

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

1080

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

1082

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

1084 '''

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

1086

1087 fpow = __ipow__ # for backward compatibility

1088

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

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

1091 '''

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

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

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

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

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

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

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

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

1100 p = None

1101 if isinstance(other, Fsum):

1102 x, r = other._fprs2

1103 if r:

1104 if self._raiser(r, x):

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

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

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

1108 elif not isscalar(other):

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

1110 else:

1111 x = self._finite(other, op)

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

1113 if p is not None:

1114 s *= p

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

1116

1117 @Property_RO

1118 def _fprs(self):

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

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

1121

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

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

1124 '''

1125 ps = self._ps

1126 n = len(ps) - 1

1127 if n > 1:

1128 s = _psum(ps)

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

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

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

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

1133 s = _0_0

1134 ps[:] = [s]

1135 else: # len(ps) == 1

1136 s = ps[0]

1137 # assert self._ps is ps

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

1139 return s

1140

1141 @Property_RO

1142 def _fprs2(self):

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

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

1145 '''

1146 s = self._fprs

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

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

1149

1150# def _fpsqz(self):

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

1152# '''

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

1154# _ = self._fprs

1155# return self

1156

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

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

1159 '''

1160 if other is self:

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

1162 elif isinstance(other, Fsum):

1163 self._n = other._n

1164 self._ps[:] = other._ps

1165 self._copy_RESIDUAL(other)

1166 # use or zap the C{Property_RO} values

1167 Fsum._fint2._update_from(self, other)

1168 Fsum._fprs ._update_from(self, other)

1169 Fsum._fprs2._update_from(self, other)

1170 elif isscalar(other):

1171 s = other if asis else float(other)

1172 i = int(s) # see ._fint2

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

1174 self._n = n

1175 self._ps[:] = [s]

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

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

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

1179 else: # PYCHOK no cover

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

1181 return self

1182

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

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

1185 from this instance.

1186

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

1188 or L{Fsum} instances).

1189

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

1191

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

1193 '''

1194 return self._facc(_2floats(xs, sub=True)) if xs else self

1195

1196 def fsub_(self, *xs):

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

1198 from this instance.

1199

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

1201 L{Fsum} instances), all positional.

1202

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

1204

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

1206 '''

1207 return self._facc(_2floats(xs, origin=1, sub=True)) if xs else self

1208

1209 def _fsub(self, other, op):

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

1211 '''

1212 if isinstance(other, Fsum):

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

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

1215 elif other._ps:

1216 self._facc(other._ps_n())

1217 elif not isscalar(other):

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

1219 elif self._finite(other, op):

1220 self._facc_(-other)

1221 return self

1222

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

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

1225 '''

1226 f = Fsum()

1227 f._n = n

1228 if ps:

1229 f._ps[:] = ps

1230 f._copy_RESIDUAL(self)

1231 return f

1232

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

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

1235

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

1237 L{Fsum} instances).

1238

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

1240

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

1242

1243 @note: Accumulation can continue after summation.

1244 '''

1245 f = self._facc(_2floats(xs)) if xs else self

1246 return f._fprs

1247

1248 def fsum_(self, *xs):

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

1250

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

1252 all positional.

1253

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

1255

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

1257 '''

1258 f = self._facc(_2floats(xs, origin=1)) if xs else self

1259 return f._fprs

1260

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

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

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

1264

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

1266 L{Fsum} instances).

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

1268

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

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

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

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

1273 to be I{exact}.

1274

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

1276 '''

1277 f = self._facc(_2floats(xs)) if xs else self

1278 t = f._fprs2

1279 if name:

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

1281 return t

1282

1283 def fsum2_(self, *xs):

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

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

1286

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

1288 all positional.

1289

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

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

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

1293

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

1295 '''

1296 p, r = self._fprs2

1297 if xs:

1298 s, t = self._facc(_2floats(xs, origin=1))._fprs2

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

1300 else: # PYCHOK no cover

1301 return p, _0_0

1302

1303# ftruediv = __itruediv__ # for naming consistency

1304

1305 def _ftruediv(self, other, op):

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

1307 '''

1308 n = _1_0

1309 if isinstance(other, Fsum):

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

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

1312 d, r = other._fprs2

1313 if r:

1314 if not d: # PYCHOK no cover

1315 d = r

1316 elif self._raiser(r, d):

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

1318 else:

1319 d, n = other.as_integer_ratio()

1320 elif isscalar(other):

1321 d = other

1322 else: # PYCHOK no cover

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

1324 try:

1325 s = 0 if isinf(d) else (

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

1327 except Exception as x:

1328 E, t = _xError2(x)

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

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

1331 return self._fset(f)

1332

1333 @property_RO

1334 def imag(self):

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

1336

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

1338 '''

1339 return _0_0

1340

1341 def int_float(self, raiser=False):

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

1343

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

1345 residual is non-zero.

1346

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

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

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

1350

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

1352

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

1354 '''

1355 s, r = self._fint2

1356 if r:

1357 s, r = self._fprs2

1358 if r and raiser: # PYCHOK no cover

1359 t = _stresidual(_non_zero_, r)

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

1361 s = float(s) # redundant

1362 return s

1363

1364 def is_exact(self):

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

1366 be exact? (C{bool}).

1367 '''

1368 return self.residual is INT0

1369

1370 def is_integer(self):

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

1372

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

1374 '''

1375 _, r = self._fint2

1376 return False if r else True

1377

1378 def is_math_fsum(self):

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

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

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

1382

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

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

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

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

1387 none are.

1388 '''

1389 f = Fsum._math_fsum

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

1391

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

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

1394 '''

1395 # assert isinstance(other, Fsum)

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

1397

1398 def _mul_scalar(self, factor, op):

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

1400 '''

1401 # assert isscalar(factor)

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

1403 if factor == _1_0:

1404 return self

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

1406 else:

1407 f = self._copy_0(_0_0)

1408 return f

1409

1410 @property_RO

1411 def partials(self):

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

1413 '''

1414 return tuple(self._ps)

1415

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

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

1418

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

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

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

1422

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

1424 result (L{Fsum}).

1425

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

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

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

1429

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

1431 '''

1432 f = self._copy_2(self.pow)

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

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

1435 else:

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

1437 return f

1438

1439 def _pow_0_1(self, x, other):

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

1441 '''

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

1443

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

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

1446 '''

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

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

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

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

1451 if not iscomplex(s):

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

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

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

1455 except Exception as x:

1456 E, t = _xError2(x)

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

1458

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

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

1461 '''

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

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

1464 t = _non_zero_ if mod is None else _integer_

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

1466 else:

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

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

1469 s = pow(b, x, mod)

1470 if not iscomplex(s):

1471 return self._finite(s)

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

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

1474 except Exception as x:

1475 E, t = _xError2(x)

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

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

1478

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

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

1481 '''

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

1483 if len(self._ps) > 1:

1484 if x > 2:

1485 p = self._copy_up()

1486 m = 1 # single-bit mask

1487 if x & m:

1488 x -= m # x ^= m

1489 f = p._copy_up()

1490 else:

1491 f = self._copy_0(_1_0)

1492 while x:

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

1494 m += m # m <<= 1

1495 if x & m:

1496 x -= m # x ^= m

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

1498 elif x > 1: # self**2

1499 f = self._mul_Fsum(self, op)

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

1501 f = self._pow_0_1(x, other)

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

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

1504 else: # PYCHOK no cover

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

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

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

1508

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

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

1511 '''

1512 s, r = self._fprs2

1513 if isint(x, both=True):

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

1515 y = abs(x)

1516 if y > 1:

1517 if r:

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

1519 if x > 0: # > 1

1520 return f

1521 # assert x < 0 # < -1

1522 s, r = f._fprs2

1523 if r:

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

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

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

1527 x = -1

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

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

1530# if x < 0:

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

1532# return f

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

1534 if r:

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

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

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

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

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

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

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

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

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

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

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

1546

1547 def _ps_1(self, *less):

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

1549 '''

1550 yield _1_0

1551 for p in self._ps:

1552 if p:

1553 yield p

1554 for p in less:

1555 if p:

1556 yield -p

1557 yield _N_1_0

1558

1559 def _ps_n(self):

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

1561 '''

1562 for p in self._ps:

1563 if p:

1564 yield -p

1565

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

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

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

1569 '''

1570 ps = self._ps

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

1572 ps, factors = factors, ps

1573 _f = _isfinite

1574 for f in factors:

1575 for p in ps:

1576 p *= f

1577 if _f(p):

1578 yield p

1579 else: # PYCHOK no cover

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

1581

1582 @property_RO

1583 def real(self):

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

1585

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

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

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

1589 '''

1590 return float(self._fprs)

1591

1592 @property_RO

1593 def residual(self):

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

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

1596

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

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

1599

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

1601 '''

1602 return self._fprs2.residual

1603

1604 def _raiser(self, r, s):

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

1606 '''

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

1608 return t > self._RESIDUAL

1609

1610 def RESIDUAL(self, *threshold):

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

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

1613

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

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

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

1617 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

1618 current setting.

1619

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

1621

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

1623

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

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

1626 '''

1627 r = self._RESIDUAL

1628 if threshold:

1629 t = threshold[0]

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

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

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

1633 if t < 0:

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

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

1636 self._RESIDUAL = t

1637 return r

1638

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

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

1641 '''

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

1643 RESIDUAL=self._RESIDUAL)

1644 t = t.replace(_COMMASPACE_R_, _exceeds_R_)

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

1646

1647 def signOf(self, res=True):

1648 '''Determine the sign of this instance.

1649

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

1651 ignore the residual (C{bool}).

1652

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

1654 '''

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

1656 return _signOf(r, -s)

1657

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

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

1660

1661 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

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

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

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

1665

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

1667 '''

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

1669

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

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

1672

1673 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

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

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

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

1677

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

1679 '''

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

1681

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

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

1684 '''

1685 n = self.named3

1686 if lenc:

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

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

1689

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

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

1692 '''

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

1694

1695 def _update(self): # see ._fset

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

1697 '''

1698 Fsum._fint2._update(self)

1699 Fsum._fprs ._update(self)

1700 Fsum._fprs2._update(self)

1701 return self

1702

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

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

1705 '''

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

1707

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

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

1710 '''

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

1712

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

1714

1715

1716 def _Float_Int(arg, **name_Error):

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

1718 '''

1719 U = Int if isint(arg) else Float

1720 return U(arg, **name_Error)

1721

1722

1723 class Fsum2Tuple(_NamedTuple):

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

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

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

1727

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

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

1730 '''

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

1732 _Units_ = (_Float_Int, _Float_Int)

1733

1734 @Property_RO

1735 def Fsum(self):

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

1737 '''

1738 f = Fsum(name=self.name)

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

1740

1741 def is_exact(self):

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

1743 '''

1744 return self.Fsum.is_exact()

1745

1746 def is_integer(self):

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

1748 '''

1749 return self.Fsum.is_integer()

1750

1751

1752 class ResidualError(_ValueError):

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

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

1755

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

1757 '''

1758 pass

1759

1760

1761 try:

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

1763

1764 # make sure _fsum works as expected (XXX check

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

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

1767 del _fsum # nope, remove _fsum ...

1768 raise ImportError # ... use _fsum below

1769

1770 Fsum._math_fsum = _fsum

1771

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

1773 _psum = _fsum # PYCHOK redef

1774

1775 except ImportError:

1776

1777 def _fsum(xs):

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

1779 '''

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

1781

1782

1783 def fsum(xs, floats=False):

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

1785

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

1787 L{Fsum} instances).

1788 @kwarg floats: Optionally, set C{B{floats}=True} iff I{all}

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

1790

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

1792

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

1794

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

1796

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

1798

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

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

1801

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

1803 '''

1804 return _fsum(_2floats(xs, floats=floats)) if xs else _0_0

1805

1806

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

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

1809

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

1811 all positional.

1812 @kwarg floats: Optionally, set C{B{floats}=True} iff I{all}

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

1814

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

1816

1817 @see: Function C{fsum}.

1818 '''

1819 if xs:

1820 f = _xkwds_get(floats, floats=False)

1821 return _fsum(_2floats(xs, origin=1, floats=f))

1822 else: # PYCHOK no cover

1823 return _0_0

1824

1825

1826 def fsum1(xs, floats=False):

1827 '''Precision floating point summation of a few values, 1-primed.

1828

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

1830 L{Fsum} instances).

1831 @kwarg floats: Optionally, set C{B{floats}=True} iff I{all}

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

1833

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

1835

1836 @see: Function C{fsum}.

1837 '''

1838 return _fsum(_2floats(xs, primed=True, floats=floats)) if xs else _0_0

1839

1840

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

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

1843

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

1845 all positional.

1846 @kwarg floats: Optionally, set C{B{floats}=True} iff I{all}

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

1848

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

1850

1851 @see: Function C{fsum}

1852 '''

1853 if xs:

1854 f = _xkwds_get(floats, floats=False)

1855 return _fsum(_2floats(xs, origin=1, primed=True, floats=f))

1856 else: # PYCHOK no cover

1857 return _0_0

1858

1859# **) MIT License

1860#

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

1862#

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

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

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

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

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

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

1869#

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

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

1872#

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

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

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

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

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

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

1879# OTHER DEALINGS IN THE SOFTWARE.