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

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): # PYCHOK no cover

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

657

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

659 '''

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

661 f = Fsum(name=self.__round__.__name__)

662 f._n = 1

663 f._ps = [round(float(self), *ndigits)] # can be C{int}

664 return f

665

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

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

668

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

670 '''

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

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

673

674 def __rsub__(self, other):

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

676

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

678 '''

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

680 return f._fsub(self, _sub_op_)

681

682 def __rtruediv__(self, other):

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

684

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

686 '''

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

688 return f._ftruediv(self, _truediv_op_)

689

690 def __str__(self):

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

692 '''

693 return self.toStr(lenc=True)

694

695 def __sub__(self, other):

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

697

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

699

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

701

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

703 '''

704 f = self._copy_2(self.__sub__)

705 return f._fsub(other, _sub_op_)

706

707 def __truediv__(self, other):

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

709

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

711

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

713

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

715 '''

716 f = self._copy_2(self.__truediv__)

717 return f._ftruediv(other, _truediv_op_)

718

719 __trunc__ = __int__

720

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

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

723 __div__ = __truediv__

724 __idiv__ = __itruediv__

725 __long__ = __int__

726 __nonzero__ = __bool__

727 __rdiv__ = __rtruediv__

728

729 def as_integer_ratio(self):

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

731

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

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

734

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

736 '''

737 n, r = self._fint2

738 if r:

739 i, d = r.as_integer_ratio()

740 n *= d

741 n += i

742 else: # PYCHOK no cover

743 d = 1

744 return n, d

745

746 @property_RO

747 def ceil(self):

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

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

750

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

752

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

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

755 '''

756 s, r = self._fprs2

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

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

759 c += 1

760 return c

761

762 def _cmp_0(self, other, op):

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

764 '''

765 if isscalar(other):

766 if other:

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

768 else:

769 s, r = self._fprs2

770 s = _signOf(s, -r)

771 elif isinstance(other, Fsum):

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

773 else:

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

775 return s

776

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

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

779

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

781 '''

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

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

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

785 return f

786

787 def _copy_0(self, *xs):

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

789 '''

790 # for x in xs:

791 # assert isscalar(x)

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

793 if self.name:

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

795 return f

796

797 def _copy_2(self, which):

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

799 '''

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

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

802 # assert f._n == self._n

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

804 return f

805

806 def _copy_n(self, which):

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

808 '''

809 if self._ps:

810 f = self._Fsum(self._n)

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

812# f._facc_up(up=False)

813 else:

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

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

816 return f

817

818 def _copy_r2(self, other, which):

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

820 '''

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

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

823

824 def _copy_RESIDUAL(self, other):

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

826 '''

827 R = other._RESIDUAL

828 if R is not Fsum._RESIDUAL:

829 self._RESIDUAL = R

830

831 def _copy_up(self, _fprs2=False):

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

833 '''

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

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

836 Fsum._fprs2._update_from(f, self)

837 return f

838

839 def divmod(self, other):

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

841 remainder)}.

842

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

844

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

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

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

848

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

850 '''

851 f = self._copy_2(self.divmod)

852 return f._fdivmod2(other, _divmod_op_)

853

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

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

856 '''

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

858

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

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

861 '''

862 E, t = _xError2(X)

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

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

865

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

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

868 '''

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

870 for x in xs: # _iter()

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

872 i = 0

873 for p in ps:

874 x, p = _2s(x, p)

875 if p:

876 ps[i] = p

877 i += 1

878 ps[i:] = [x]

879 n += 1

880 # assert self._ps is ps

881 if n:

882 self._n += n

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

884 if up:

885 self._update()

886 return self

887

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

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

890 '''

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

892

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

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

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

896# '''

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

898# p = self._ps.pop()

899# if p:

900# n = self._n

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

902# self._n = n

903# break

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

905

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

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

908 to this instance.

909

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

911 L{Fsum} instances).

912

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

914

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

916

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

918 nor L{Fsum}.

919

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

921 '''

922 if isinstance(xs, Fsum):

923 self._facc(xs._ps)

924 elif isscalar(xs): # for backward compatibility

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

926 elif xs:

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

928 return self

929

930 def fadd_(self, *xs):

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

932 to this instance.

933

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

935 all positional.

936

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

938

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

940

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

942 nor L{Fsum}.

943

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

945 '''

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

947

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

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

950 '''

951 if isinstance(other, Fsum):

952 if other is self:

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

954 elif other._ps:

955 self._facc(other._ps)

956 elif not isscalar(other):

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

958 elif other:

959 self._facc_(other)

960 return self

961

962 fcopy = copy # for backward compatibility

963 fdiv = __itruediv__ # for backward compatibility

964 fdivmod = __divmod__ # for backward compatibility

965

966 def _fdivmod2(self, other, op):

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

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

969 '''

970 # result mostly follows CPython function U{float_divmod

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

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

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

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

975 self -= other * q

976

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

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

979 self += other

980 q -= 1

981

982# t = self.signOf()

983# if t and t != s:

984# from pygeodesy.errors import _AssertionError

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

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

987

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

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

990 '''

991 if _isfinite(other):

992 return other

993 raise ValueError(_not_finite_) if not op else \

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

995

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

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

998

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

1000 I{integer} residual is non-zero.

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

1002

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

1004

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

1006

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

1008 '''

1009 i, r = self._fint2

1010 if r and raiser:

1011 t = _stresidual(_integer_, r)

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

1013 n = name or self.fint.__name__

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

1015

1016 def fint2(self, **name):

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

1018 the I{integer} residual.

1019

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

1021

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

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

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

1025 '''

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

1027

1028 @Property_RO

1029 def _fint2(self): # see ._fset

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

1031 '''

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

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

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

1035 return i, (r or INT0)

1036

1037 @deprecated_property_RO

1038 def float_int(self): # PYCHOK no cover

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

1040 return self.int_float() # raiser=False

1041

1042 @property_RO

1043 def floor(self):

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

1045 C{float} in Python 2-).

1046

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

1048

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

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

1051 '''

1052 s, r = self._fprs2

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

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

1055 f -= 1

1056 return f

1057

1058# floordiv = __floordiv__ # for naming consistency

1059

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

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

1062 '''

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

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

1065

1066 fmul = __imul__ # for backward compatibility

1067

1068 def _fmul(self, other, op):

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

1070 '''

1071 if isscalar(other):

1072 f = self._mul_scalar(other, op)

1073 elif not isinstance(other, Fsum):

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

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

1076 f = self._mul_Fsum(other, op)

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

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

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

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

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

1082 return self._fset(f)

1083

1084 def fover(self, over):

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

1086

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

1088

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

1090

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

1092 '''

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

1094

1095 fpow = __ipow__ # for backward compatibility

1096

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

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

1099 '''

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

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

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

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

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

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

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

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

1108 p = None

1109 if isinstance(other, Fsum):

1110 x, r = other._fprs2

1111 if r:

1112 if self._raiser(r, x):

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

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

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

1116 elif not isscalar(other):

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

1118 else:

1119 x = self._finite(other, op)

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

1121 if p is not None:

1122 s *= p

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

1124

1125 @Property_RO

1126 def _fprs(self):

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

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

1129

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

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

1132 '''

1133 ps = self._ps

1134 n = len(ps) - 1

1135 if n > 1:

1136 s = _psum(ps)

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

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

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

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

1141 s = _0_0

1142 ps[:] = [s]

1143 else: # len(ps) == 1

1144 s = ps[0]

1145 # assert self._ps is ps

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

1147 return s

1148

1149 @Property_RO

1150 def _fprs2(self):

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

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

1153 '''

1154 s = self._fprs

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

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

1157

1158# def _fpsqz(self):

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

1160# '''

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

1162# _ = self._fprs

1163# return self

1164

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

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

1167 '''

1168 if other is self:

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

1170 elif isinstance(other, Fsum):

1171 self._n = other._n

1172 self._ps[:] = other._ps

1173 self._copy_RESIDUAL(other)

1174 # use or zap the C{Property_RO} values

1175 Fsum._fint2._update_from(self, other)

1176 Fsum._fprs ._update_from(self, other)

1177 Fsum._fprs2._update_from(self, other)

1178 elif isscalar(other):

1179 s = other if asis else float(other)

1180 i = int(s) # see ._fint2

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

1182 self._n = n

1183 self._ps[:] = [s]

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

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

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

1187 else: # PYCHOK no cover

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

1189 return self

1190

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

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

1193 from this instance.

1194

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

1196 or L{Fsum} instances).

1197

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

1199

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

1201 '''

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

1203

1204 def fsub_(self, *xs):

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

1206 from this instance.

1207

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

1209 L{Fsum} instances), all positional.

1210

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

1212

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

1214 '''

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

1216

1217 def _fsub(self, other, op):

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

1219 '''

1220 if isinstance(other, Fsum):

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

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

1223 elif other._ps:

1224 self._facc(other._ps_n())

1225 elif not isscalar(other):

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

1227 elif self._finite(other, op):

1228 self._facc_(-other)

1229 return self

1230

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

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

1233 '''

1234 f = Fsum()

1235 f._n = n

1236 if ps:

1237 f._ps[:] = ps

1238 f._copy_RESIDUAL(self)

1239 return f

1240

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

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

1243

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

1245 L{Fsum} instances).

1246

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

1248

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

1250

1251 @note: Accumulation can continue after summation.

1252 '''

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

1254 return f._fprs

1255

1256 def fsum_(self, *xs):

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

1258

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

1260 all positional.

1261

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

1263

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

1265 '''

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

1267 return f._fprs

1268

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

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

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

1272

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

1274 L{Fsum} instances).

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

1276

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

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

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

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

1281 to be I{exact}.

1282

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

1284 '''

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

1286 t = f._fprs2

1287 if name:

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

1289 return t

1290

1291 def fsum2_(self, *xs):

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

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

1294

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

1296 all positional.

1297

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

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

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

1301

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

1303 '''

1304 p, r = self._fprs2

1305 if xs:

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

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

1308 else: # PYCHOK no cover

1309 return p, _0_0

1310

1311# ftruediv = __itruediv__ # for naming consistency

1312

1313 def _ftruediv(self, other, op):

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

1315 '''

1316 n = _1_0

1317 if isinstance(other, Fsum):

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

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

1320 d, r = other._fprs2

1321 if r:

1322 if not d: # PYCHOK no cover

1323 d = r

1324 elif self._raiser(r, d):

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

1326 else:

1327 d, n = other.as_integer_ratio()

1328 elif isscalar(other):

1329 d = other

1330 else: # PYCHOK no cover

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

1332 try:

1333 s = 0 if isinf(d) else (

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

1335 except Exception as x:

1336 E, t = _xError2(x)

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

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

1339 return self._fset(f)

1340

1341 @property_RO

1342 def imag(self):

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

1344

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

1346 '''

1347 return _0_0

1348

1349 def int_float(self, raiser=False):

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

1351

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

1353 residual is non-zero.

1354

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

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

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

1358

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

1360

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

1362 '''

1363 s, r = self._fint2

1364 if r:

1365 s, r = self._fprs2

1366 if r and raiser: # PYCHOK no cover

1367 t = _stresidual(_non_zero_, r)

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

1369 s = float(s) # redundant

1370 return s

1371

1372 def is_exact(self):

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

1374 be exact? (C{bool}).

1375 '''

1376 return self.residual is INT0

1377

1378 def is_integer(self):

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

1380

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

1382 '''

1383 _, r = self._fint2

1384 return False if r else True

1385

1386 def is_math_fsum(self):

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

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

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

1390

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

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

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

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

1395 none are.

1396 '''

1397 f = Fsum._math_fsum

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

1399

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

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

1402 '''

1403 # assert isinstance(other, Fsum)

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

1405

1406 def _mul_scalar(self, factor, op):

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

1408 '''

1409 # assert isscalar(factor)

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

1411 if factor == _1_0:

1412 return self

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

1414 else:

1415 f = self._copy_0(_0_0)

1416 return f

1417

1418 @property_RO

1419 def partials(self):

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

1421 '''

1422 return tuple(self._ps)

1423

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

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

1426

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

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

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

1430

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

1432 result (L{Fsum}).

1433

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

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

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

1437

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

1439 '''

1440 f = self._copy_2(self.pow)

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

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

1443 else:

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

1445 return f

1446

1447 def _pow_0_1(self, x, other):

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

1449 '''

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

1451

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

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

1454 '''

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

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

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

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

1459 if not iscomplex(s):

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

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

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

1463 except Exception as x:

1464 E, t = _xError2(x)

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

1466

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

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

1469 '''

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

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

1472 t = _non_zero_ if mod is None else _integer_

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

1474 else:

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

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

1477 s = pow(b, x, mod)

1478 if not iscomplex(s):

1479 return self._finite(s)

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

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

1482 except Exception as x:

1483 E, t = _xError2(x)

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

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

1486

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

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

1489 '''

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

1491 if len(self._ps) > 1:

1492 if x > 2:

1493 p = self._copy_up()

1494 m = 1 # single-bit mask

1495 if x & m:

1496 x -= m # x ^= m

1497 f = p._copy_up()

1498 else:

1499 f = self._copy_0(_1_0)

1500 while x:

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

1502 m += m # m <<= 1

1503 if x & m:

1504 x -= m # x ^= m

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

1506 elif x > 1: # self**2

1507 f = self._mul_Fsum(self, op)

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

1509 f = self._pow_0_1(x, other)

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

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

1512 else: # PYCHOK no cover

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

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

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

1516

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

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

1519 '''

1520 s, r = self._fprs2

1521 if isint(x, both=True):

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

1523 y = abs(x)

1524 if y > 1:

1525 if r:

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

1527 if x > 0: # > 1

1528 return f

1529 # assert x < 0 # < -1

1530 s, r = f._fprs2

1531 if r:

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

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

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

1535 x = -1

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

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

1538# if x < 0:

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

1540# return f

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

1542 if r:

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

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

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

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

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

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

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

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

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

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

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

1554

1555 def _ps_1(self, *less):

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

1557 '''

1558 yield _1_0

1559 for p in self._ps:

1560 if p:

1561 yield p

1562 for p in less:

1563 if p:

1564 yield -p

1565 yield _N_1_0

1566

1567 def _ps_n(self):

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

1569 '''

1570 for p in self._ps:

1571 if p:

1572 yield -p

1573

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

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

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

1577 '''

1578 ps = self._ps

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

1580 ps, factors = factors, ps

1581 _f = _isfinite

1582 for f in factors:

1583 for p in ps:

1584 p *= f

1585 if _f(p):

1586 yield p

1587 else: # PYCHOK no cover

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

1589

1590 @property_RO

1591 def real(self):

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

1593

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

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

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

1597 '''

1598 return float(self._fprs)

1599

1600 @property_RO

1601 def residual(self):

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

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

1604

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

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

1607

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

1609 '''

1610 return self._fprs2.residual

1611

1612 def _raiser(self, r, s):

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

1614 '''

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

1616 return t > self._RESIDUAL

1617

1618 def RESIDUAL(self, *threshold):

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

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

1621

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

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

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

1625 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the

1626 current setting.

1627

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

1629

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

1631

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

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

1634 '''

1635 r = self._RESIDUAL

1636 if threshold:

1637 t = threshold[0]

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

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

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

1641 if t < 0:

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

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

1644 self._RESIDUAL = t

1645 return r

1646

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

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

1649 '''

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

1651 RESIDUAL=self._RESIDUAL)

1652 t = t.replace(_COMMASPACE_R_, _exceeds_R_)

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

1654

1655 def signOf(self, res=True):

1656 '''Determine the sign of this instance.

1657

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

1659 ignore the residual (C{bool}).

1660

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

1662 '''

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

1664 return _signOf(s, -r)

1665

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

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

1668

1669 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

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

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

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

1673

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

1675 '''

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

1677

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

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

1680

1681 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for

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

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

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

1685

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

1687 '''

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

1689

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

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

1692 '''

1693 n = self.named3

1694 if lenc:

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

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

1697

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

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

1700 '''

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

1702

1703 def _update(self): # see ._fset

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

1705 '''

1706 Fsum._fint2._update(self)

1707 Fsum._fprs ._update(self)

1708 Fsum._fprs2._update(self)

1709 return self

1710

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

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

1713 '''

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

1715

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

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

1718 '''

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

1720

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

1722

1723

1724 def _Float_Int(arg, **name_Error):

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

1726 '''

1727 U = Int if isint(arg) else Float

1728 return U(arg, **name_Error)

1729

1730

1731 class Fsum2Tuple(_NamedTuple):

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

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

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

1735

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

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

1738 '''

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

1740 _Units_ = (_Float_Int, _Float_Int)

1741

1742 @Property_RO

1743 def Fsum(self):

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

1745 '''

1746 f = Fsum(name=self.name)

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

1748

1749 def is_exact(self):

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

1751 '''

1752 return self.Fsum.is_exact()

1753

1754 def is_integer(self):

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

1756 '''

1757 return self.Fsum.is_integer()

1758

1759

1760 class ResidualError(_ValueError):

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

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

1763

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

1765 '''

1766 pass

1767

1768

1769 try:

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

1771

1772 # make sure _fsum works as expected (XXX check

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

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

1775 del _fsum # nope, remove _fsum ...

1776 raise ImportError # ... use _fsum below

1777

1778 Fsum._math_fsum = _sum = _fsum # PYCHOK exported

1779

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

1781 _psum = _fsum # PYCHOK redef

1782

1783 except ImportError:

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

1785

1786 def _fsum(xs):

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

1788 '''

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

1790

1791

1792 def fsum(xs, floats=False):

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

1794

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

1796 L{Fsum} instances).

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

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

1799

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

1801

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

1803

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

1805

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

1807

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

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

1810

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

1812 '''

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

1814

1815

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

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

1818

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

1820 all positional.

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

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

1823

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

1825

1826 @see: Function C{fsum}.

1827 '''

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

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

1830

1831

1832 def fsumf_(*xs):

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

1834 '''

1835 return _fsum(xs) if xs else _0_0

1836

1837

1838 def fsum1(xs, floats=False):

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

1840

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

1842 L{Fsum} instances).

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

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

1845

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

1847

1848 @see: Function C{fsum}.

1849 '''

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

1851

1852

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

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

1855

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

1857 all positional.

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

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

1860

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

1862

1863 @see: Function C{fsum}

1864 '''

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

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

1867

1868

1869 def fsum1f_(*xs):

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

1871 '''

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

1873

1874

1875# **) MIT License

1876#

1877# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

1878#

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

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

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

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

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

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

1885#

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

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

1888#

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

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

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

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

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

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

1895# OTHER DEALINGS IN THE SOFTWARE.