1

2# -*- coding: utf-8 -*-

3

4 u'''Utilities using precision floating point summation.

5'''

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

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

8

9 from pygeodesy.basics import _copysign, copysign0, isbool, isint, isscalar, \

10 len2, map1, _xiterable

11 from pygeodesy.constants import EPS0, EPS02, EPS1, NAN, PI, PI_2, PI_4, \

12 _0_0, _0_125, _1_6th, _0_25, _1_3rd, _0_5, _1_0, \

13 _1_5, _copysign_0_0, isfinite, remainder

14 from pygeodesy.errors import _IsnotError, LenError, _TypeError, _ValueError, \

15 _xError, _xkwds, _xkwds_pop2, _xsError

16 from pygeodesy.fsums import _2float, Fsum, fsum, _isFsum_2Tuple, Fmt, unstr

17 from pygeodesy.interns import MISSING, _negative_, _not_scalar_

18 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

19# from pygeodesy.streprs import Fmt, unstr # from .fsums

20 from pygeodesy.units import Int_, _isHeight, _isRadius, Float_ # PYCHOK for .heights

21

22 from math import fabs, sqrt # pow

23 import operator as _operator # in .datums, .trf, .utm

24

25__all__ = _ALL_LAZY.fmath

26__version__ = '24.11.08'

27

28# sqrt(2) - 1 <https://WikiPedia.org/wiki/Square_root_of_2>

29_0_4142 = 0.41421356237309504880 # ... ~ 3730904090310553 / 9007199254740992

30_2_3rd = _1_3rd * 2

31_h_lt_b_ = 'abs(h) < abs(b)'

32

33

34 class Fdot(Fsum):

35 '''Precision dot product.

36 '''

37 def __init__(self, a, *b, **start_name_f2product_nonfinites_RESIDUAL):

38 '''New L{Fdot} precision dot product M{sum(a[i] * b[i] for i=0..len(a)-1)}.

39

40 @arg a: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

41 @arg b: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all

42 positional.

43 @kwarg start_name_f2product_nonfinites_RESIDUAL: Optional bias C{B{start}=0}

44 (C{scalar}, an L{Fsum} or L{Fsum2Tuple}), C{B{name}=NN} (C{str})

45 and other settings, see class L{Fsum<Fsum.__init__>}.

46

47 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.

48

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

50

51 @raise TypeError: Invalid B{C{x}}.

52

53 @raise ValueError: Non-finite B{C{x}}.

54

55 @see: Function L{fdot} and method L{Fsum.fadd}.

56 '''

57 s, kwds = _xkwds_pop2(start_name_f2product_nonfinites_RESIDUAL, start=_0_0)

58 Fsum.__init__(self, **kwds)

59 self(s)

60

61 n = len(b)

62 if len(a) != n: # PYCHOK no cover

63 raise LenError(Fdot, a=len(a), b=n)

64 self._facc_dot(n, a, b, **kwds)

65

66

67 class Fhorner(Fsum):

68 '''Precision polynomial evaluation using the Horner form.

69 '''

70 def __init__(self, x, *cs, **incx_name_f2product_nonfinites_RESIDUAL):

71 '''New L{Fhorner} form evaluation of polynomial M{sum(cs[i] * x**i for

72 i=0..n)} with in- or decreasing exponent M{sum(... i=n..0)}, where C{n

73 = len(cs) - 1}.

74

75 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

76 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),

77 all positional.

78 @kwarg incx_name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str}),

79 C{B{incx}=True} for in-/decreasing exponents (C{bool}) and other

80 settings, see class L{Fsum<Fsum.__init__>}.

81

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

83

84 @raise TypeError: Invalid B{C{x}}.

85

86 @raise ValueError: Non-finite B{C{x}}.

87

88 @see: Function L{fhorner} and methods L{Fsum.fadd} and L{Fsum.fmul}.

89 '''

90 incx, kwds = _xkwds_pop2(incx_name_f2product_nonfinites_RESIDUAL, incx=True)

91 Fsum.__init__(self, **kwds)

92 self._fhorner(x, cs, Fhorner, incx=incx)

93

94

95 class Fhypot(Fsum):

96 '''Precision summation and hypotenuse, default C{root=2}.

97 '''

98 def __init__(self, *xs, **root_name_f2product_nonfinites_RESIDUAL_raiser):

99 '''New L{Fhypot} hypotenuse of (the I{root} of) several components (raised

100 to the power I{root}).

101

102 @arg xs: Components (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all

103 positional.

104 @kwarg root_name_f2product_nonfinites_RESIDUAL_raiser: Optional, exponent

105 and C{B{root}=2} order (C{scalar}), C{B{name}=NN} (C{str}),

106 C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s and

107 other settings, see class L{Fsum<Fsum.__init__>} and method

108 L{root<Fsum.root>}.

109 '''

110 r = None # _xkwds_pop2 error

111 try:

112 r, kwds = _xkwds_pop2(root_name_f2product_nonfinites_RESIDUAL_raiser, root=2)

113 r, kwds = _xkwds_pop2(kwds, power=r) # for backward compatibility

114 t, kwds = _xkwds_pop2(kwds, raiser=True)

115 Fsum.__init__(self, **kwds)

116 self(_0_0)

117 if xs:

118 self._facc_power(r, xs, Fhypot, raiser=t)

119 self._fset(self.root(r, raiser=t))

120 except Exception as X:

121 raise self._ErrorXs(X, xs, root=r)

122

123

124 class Fpolynomial(Fsum):

125 '''Precision polynomial evaluation.

126 '''

127 def __init__(self, x, *cs, **name_f2product_nonfinites_RESIDUAL):

128 '''New L{Fpolynomial} evaluation of the polynomial M{sum(cs[i] * x**i for

129 i=0..len(cs)-1)}.

130

131 @arg x: Polynomial argument (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

132 @arg cs: Polynomial coeffients (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),

133 all positional.

134 @kwarg name_f2product_nonfinites_RESIDUAL: Optional C{B{name}=NN} (C{str})

135 and other settings, see class L{Fsum<Fsum.__init__>}.

136

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

138

139 @raise TypeError: Invalid B{C{x}}.

140

141 @raise ValueError: Non-finite B{C{x}}.

142

143 @see: Class L{Fhorner}, function L{fpolynomial} and method L{Fsum.fadd}.

144 '''

145 Fsum.__init__(self, **name_f2product_nonfinites_RESIDUAL)

146 n = len(cs) - 1

147 self(_0_0 if n < 0 else cs[0])

148 self._facc_dot(n, cs[1:], _powers(x, n), **name_f2product_nonfinites_RESIDUAL)

149

150

151 class Fpowers(Fsum):

152 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.

153 '''

154 def __init__(self, power, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):

155 '''New L{Fpowers} sum of (the I{power} of) several bases.

156

157 @arg power: The exponent (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

158 @arg xs: One or more bases (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all

159 positional.

160 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}

161 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s

162 and other settings, see class L{Fsum<Fsum.__init__>} and method

163 L{fpow<Fsum.fpow>}.

164 '''

165 try:

166 t, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)

167 Fsum.__init__(self, **kwds)

168 self(_0_0)

169 if xs:

170 self._facc_power(power, xs, Fpowers, raiser=t) # x**0 == 1

171 except Exception as X:

172 raise self._ErrorXs(X, xs, power=power)

173

174

175 class Froot(Fsum):

176 '''The root of a precision summation.

177 '''

178 def __init__(self, root, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):

179 '''New L{Froot} root of a precision sum.

180

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

182 @arg xs: Items to summate (each a C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all

183 positional.

184 @kwarg name_f2product_nonfinites_RESIDUAL_raiser: Optional C{B{name}=NN}

185 (C{str}), C{B{raiser}=True} (C{bool}) for raising L{ResidualError}s

186 and other settings, see class L{Fsum<Fsum.__init__>} and method

187 L{fpow<Fsum.fpow>}.

188 '''

189 try:

190 raiser, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)

191 Fsum.__init__(self, **kwds)

192 self(_0_0)

193 if xs:

194 self.fadd(xs)

195 self(self.root(root, raiser=raiser))

196 except Exception as X:

197 raise self._ErrorXs(X, xs, root=root)

198

199

200 class Fcbrt(Froot):

201 '''Cubic root of a precision summation.

202 '''

203 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):

204 '''New L{Fcbrt} cubic root of a precision sum.

205

206 @see: Class L{Froot<Froot.__init__>} for further details.

207 '''

208 Froot.__init__(self, 3, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)

209

210

211 class Fsqrt(Froot):

212 '''Square root of a precision summation.

213 '''

214 def __init__(self, *xs, **name_f2product_nonfinites_RESIDUAL_raiser):

215 '''New L{Fsqrt} square root of a precision sum.

216

217 @see: Class L{Froot<Froot.__init__>} for further details.

218 '''

219 Froot.__init__(self, 2, *xs, **name_f2product_nonfinites_RESIDUAL_raiser)

220

221

222 def bqrt(x):

223 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)},

224 preserving C{type(B{x})}.

225

226 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

227

228 @return: I{Quartic} root (C{float} or an L{Fsum}).

229

230 @raise TypeeError: Invalid B{C{x}}.

231

232 @raise ValueError: Negative B{C{x}}.

233

234 @see: Functions L{zcrt} and L{zqrt}.

235 '''

236 return _root(x, _0_25, bqrt)

237

238

239 try:

240 from math import cbrt as _cbrt # Python 3.11+

241

242 except ImportError: # Python 3.10-

243

244 def _cbrt(x):

245 '''(INTERNAL) Compute the I{signed}, cube root M{x**(1/3)}.

246 '''

247 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>

248 # simpler and more accurate than Ken Turkowski's CubeRoot, see

249 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>

250 return _copysign(pow(fabs(x), _1_3rd), x) # to avoid complex

251

252

253 def cbrt(x):

254 '''Compute the cube root M{x**(1/3)}, preserving C{type(B{x})}.

255

256 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

257

258 @return: Cubic root (C{float} or L{Fsum}).

259

260 @see: Functions L{cbrt2} and L{sqrt3}.

261 '''

262 if _isFsum_2Tuple(x):

263 r = abs(x).fpow(_1_3rd)

264 if x.signOf() < 0:

265 r = -r

266 else:

267 r = _cbrt(x)

268 return r # cbrt(-0.0) == -0.0

269

270

271 def cbrt2(x): # PYCHOK attr

272 '''Compute the cube root I{squared} M{x**(2/3)}, preserving C{type(B{x})}.

273

274 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

275

276 @return: Cube root I{squared} (C{float} or L{Fsum}).

277

278 @see: Functions L{cbrt} and L{sqrt3}.

279 '''

280 return abs(x).fpow(_2_3rd) if _isFsum_2Tuple(x) else _cbrt(x**2)

281

282

283 def euclid(x, y):

284 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by M{max(abs(x),

285 abs(y)) + min(abs(x), abs(y)) * 0.4142...}.

286

287 @arg x: X component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

288 @arg y: Y component (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

289

290 @return: Appoximate norm (C{float} or L{Fsum}).

291

292 @see: Function L{euclid_}.

293 '''

294 x, y = abs(x), abs(y) # NOT fabs!

295 if y > x:

296 x, y = y, x

297 return x + y * _0_4142 # * _0_5 before 20.10.02

298

299

300 def euclid_(*xs):

301 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))} by cascaded

302 L{euclid}.

303

304 @arg xs: X arguments (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}),

305 all positional.

306

307 @return: Appoximate norm (C{float} or L{Fsum}).

308

309 @see: Function L{euclid}.

310 '''

311 e = _0_0

312 for x in sorted(map(abs, xs)): # NOT fabs, reverse=True!

313 # e = euclid(x, e)

314 if e < x:

315 e, x = x, e

316 if x:

317 e += x * _0_4142

318 return e

319

320

321 def facos1(x):

322 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}, scalar.

323

324 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/

325 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.

326 '''

327 a = fabs(x)

328 if a < EPS0:

329 r = PI_2

330 elif a < EPS1:

331 r = _fast(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)

332 r *= sqrt(_1_0 - a)

333 if x < 0:

334 r = PI - r

335 else:

336 r = PI if x < 0 else _0_0

337 return r

338

339

340 def fasin1(x): # PYCHOK no cover

341 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}, scalar.

342

343 @see: L{facos1}.

344 '''

345 return PI_2 - facos1(x)

346

347

348 def _fast(x, *cs):

349 '''(INTERNAL) Horner form for C{facos1} and C{fatan1}.

350 '''

351 h = 0

352 for c in reversed(cs):

353 h = _fma(x, h, c) if h else c

354 return h

355

356

357 def fatan(x):

358 '''Fast approximation of C{atan(B{x})}, scalar.

359 '''

360 a = fabs(x)

361 if a < _1_0:

362 r = fatan1(a) if a else _0_0

363 elif a > _1_0:

364 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)

365 else:

366 r = PI_4

367 if x < 0: # copysign0(r, x)

368 r = -r

369 return r

370

371

372 def fatan1(x):

373 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} < 1}, I{unchecked}.

374

375 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/

376 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations

377 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/

378 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},

379 IEEE Signal Processing Magazine, 111, May 2006.

380 '''

381 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1

382 # == PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x < 1

383 # == x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))

384 return _fast(x, _0_0, 1.0300981634, -0.1784, -0.0663)

385

386

387 def fatan2(y, x):

388 '''Fast approximation of C{atan2(B{y}, B{x})}, scalar.

389

390 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/

391 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}

392 and L{fatan1}.

393 '''

394 a, b = fabs(x), fabs(y)

395 if b > a:

396 r = (PI_2 - fatan1(a / b)) if a else PI_2

397 elif a > b:

398 r = fatan1(b / a) if b else _0_0

399 elif a: # a == b != 0

400 r = PI_4

401 else: # a == b == 0

402 return _0_0

403 if x < 0:

404 r = PI - r

405 if y < 0: # copysign0(r, y)

406 r = -r

407 return r

408

409

410 def favg(a, b, f=_0_5, nonfinites=True):

411 '''Return the precise average of two values.

412

413 @arg a: One (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

414 @arg b: Other (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

415 @kwarg f: Optional fraction (C{float}).

416 @kwarg nonfinites: Optional setting, see function L{fma}.

417

418 @return: M{a + f * (b - a)} (C{float}).

419 '''

420 F = fma(f, (b - a), a, nonfinites=nonfinites)

421 return float(F)

422

423

424 def fdot(xs, *ys, **start_f2product_nonfinites):

425 '''Return the precision dot product M{sum(xs[i] * ys[i] for i in range(len(xs)))}.

426

427 @arg xs: Iterable of values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

428 @arg ys: Other values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all

429 positional.

430 @kwarg start_f2product_nonfinites: Optional bias C{B{start}=0} (C{scalar}, an

431 L{Fsum} or L{Fsum2Tuple}) and settings C{B{f2product}=None} (C{bool})

432 and C{B{nonfinites=True}} (C{bool}), see class L{Fsum<Fsum.__init__>}.

433

434 @return: Dot product (C{float}).

435

436 @raise LenError: Unequal C{len(B{xs})} and C{len(B{ys})}.

437

438 @see: Class L{Fdot}, U{Algorithm 5.10 B{DotK}

439 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>} and function

440 C{math.sumprod} in Python 3.12 and later.

441 '''

442 D = Fdot(xs, *ys, **_xkwds(start_f2product_nonfinites, nonfinites=True))

443 return float(D)

444

445

446 def fdot_(*xys, **start_f2product_nonfinites):

447 '''Return the (precision) dot product M{sum(xys[i] * xys[i+1] for i in range(0, len(xys), B{2}))}.

448

449 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all positional.

450

451 @see: Function L{fdot} for further details.

452

453 @return: Dot product (C{float}).

454 '''

455 return fdot(xys[0::2], *xys[1::2], **start_f2product_nonfinites)

456

457

458 def fdot3(xs, ys, zs, **start_f2product_nonfinites):

459 '''Return the (precision) dot product M{start + sum(xs[i] * ys[i] * zs[i] for i in range(len(xs)))}.

460

461 @arg xs: Iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

462 @arg ys: Iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

463 @arg zs: Iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

464

465 @see: Function L{fdot} for further details.

466

467 @return: Dot product (C{float}).

468

469 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})} and/or C{len(B{zs})}.

470 '''

471 n = len(xs)

472 if not n == len(ys) == len(zs):

473 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))

474

475 D = Fdot((), **_xkwds(start_f2product_nonfinites, nonfinites=True))

476 kwds = dict(f2product=D.f2product(), nonfinites=D.nonfinites())

477 _f = Fsum(**kwds)

478 D = D._facc(_f(x).f2mul_(y, z, **kwds) for x, y, z in zip(xs, ys, zs))

479 return float(D)

480

481

482 def fhorner(x, *cs, **incx):

483 '''Horner form evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)} as

484 in- or decreasing exponent M{sum(... i=n..0)}, where C{n = len(cs) - 1}.

485

486 @return: Horner sum (C{float}).

487

488 @see: Class L{Fhorner<Fhorner.__init__>} for further details.

489 '''

490 H = Fhorner(x, *cs, **incx)

491 return float(H)

492

493

494 def fidw(xs, ds, beta=2):

495 '''Interpolate using U{Inverse Distance Weighting

496 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).

497

498 @arg xs: Known values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

499 @arg ds: Non-negative distances (each C{scalar}, an L{Fsum} or

500 L{Fsum2Tuple}).

501 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).

502

503 @return: Interpolated value C{x} (C{float}).

504

505 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.

506

507 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.

508

509 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or

510 weighted B{C{ds}} below L{EPS}.

511

512 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.

513 '''

514 n, xs = len2(xs)

515 if n > 1:

516 b = -Int_(beta=beta, low=0, high=3)

517 if b < 0:

518 try: # weighted

519 _d, W, X = (Fsum() for _ in range(3))

520 for i, d in enumerate(_xiterable(ds)):

521 x = xs[i]

522 D = _d(d)

523 if D < EPS0:

524 if D < 0:

525 raise ValueError(_negative_)

526 x = float(x)

527 i = n

528 break

529 if D.fpow(b):

530 W += D

531 X += D.fmul(x)

532 else:

533 x = X.fover(W, raiser=False)

534 i += 1 # len(xs) >= len(ds)

535 except IndexError:

536 i += 1 # len(xs) < i < len(ds)

537 except Exception as X:

538 _I = Fmt.INDEX

539 raise _xError(X, _I(xs=i), x,

540 _I(ds=i), d)

541 else: # b == 0

542 x = fsum(xs) / n # fmean(xs)

543 i = n

544 elif n:

545 x = float(xs[0])

546 i = n

547 else:

548 x = _0_0

549 i, _ = len2(ds)

550 if i != n:

551 raise LenError(fidw, xs=n, ds=i)

552 return x

553

554

555 try:

556 from math import fma as _fma

557 except ImportError: # PYCHOK DSPACE!

558

559 def _fma(x, y, z): # no need for accuracy

560 return x * y + z

561

562

563 def fma(x, y, z, **nonfinites): # **raiser

564 '''Fused-multiply-add, using C{math.fma(x, y, z)} in Python 3.13+

565 or an equivalent implementation.

566

567 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

568 @arg y: Multiplier (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

569 @arg z: Addend (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

570 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False},

571 to override default L{nonfiniterrors}

572 (C{bool}), see method L{Fsum.fma}.

573

574 @return: C{(x * y) + z} (C{float} or L{Fsum}).

575 '''

576 F, raiser = _Fm2(x, **nonfinites)

577 return F.fma(y, z, **raiser).as_iscalar

578

579

580 def _Fm2(x, nonfinites=None, **raiser):

581 '''(INTERNAL) Handle C{fma} and C{f2mul} DEPRECATED C{raiser=False}.

582 '''

583 return Fsum(x, nonfinites=nonfinites), raiser

584

585

586 def fmean(xs):

587 '''Compute the accurate mean M{sum(xs) / len(xs)}.

588

589 @arg xs: Values (each C{scalar}, or L{Fsum} or L{Fsum2Tuple}).

590

591 @return: Mean value (C{float}).

592

593 @raise LenError: No B{C{xs}} values.

594

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

596 '''

597 n, xs = len2(xs)

598 if n < 1:

599 raise LenError(fmean, xs=xs)

600 M = Fsum(*xs, nonfinites=True)

601 return M.fover(n) if n > 1 else float(M)

602

603

604 def fmean_(*xs, **nonfinites):

605 '''Compute the accurate mean M{sum(xs) / len(xs)}.

606

607 @see: Function L{fmean} for further details.

608 '''

609 return fmean(xs, **nonfinites)

610

611

612 def f2mul_(x, *ys, **nonfinites): # **raiser

613 '''Cascaded, accurate multiplication C{B{x} * B{y} * B{y} ...} for all B{C{ys}}.

614

615 @arg x: Multiplicand (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

616 @arg ys: Multipliers (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), all

617 positional.

618 @kwarg nonfinites: Use C{B{nonfinites}=True} or C{=False}, to override default

619 L{nonfiniterrors} (C{bool}), see method L{Fsum.f2mul_}.

620

621 @return: The cascaded I{TwoProduct} (C{float}, C{int} or L{Fsum}).

622

623 @see: U{Equations 2.3<https://www.TUHH.De/ti3/paper/rump/OzOgRuOi06.pdf>}

624 '''

625 F, raiser = _Fm2(x, **nonfinites)

626 return F.f2mul_(*ys, **raiser).as_iscalar

627

628

629 def fpolynomial(x, *cs, **over_f2product_nonfinites):

630 '''Evaluate the polynomial M{sum(cs[i] * x**i for i=0..len(cs)) [/ over]}.

631

632 @kwarg over_f2product_nonfinites: Optional final divisor C{B{over}=None}

633 (I{non-zero} C{scalar}) and other settings, see class

634 L{Fpolynomial<Fpolynomial.__init__>}.

635

636 @return: Polynomial value (C{float} or L{Fpolynomial}).

637 '''

638 d, kwds = _xkwds_pop2(over_f2product_nonfinites, over=0)

639 P = Fpolynomial(x, *cs, **kwds)

640 return P.fover(d) if d else float(P)

641

642

643 def fpowers(x, n, alts=0):

644 '''Return a series of powers M{[x**i for i=1..n]}, note I{1..!}

645

646 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

647 @arg n: Highest exponent (C{int}).

648 @kwarg alts: Only alternating powers, starting with this

649 exponent (C{int}).

650

651 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).

652

653 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.

654

655 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.

656 '''

657 if not isint(n):

658 raise _IsnotError(int.__name__, n=n)

659 elif n < 1:

660 raise _ValueError(n=n)

661

662 p = x if isscalar(x) or _isFsum_2Tuple(x) else _2float(x=x)

663 ps = tuple(_powers(p, n))

664

665 if alts > 0: # x**2, x**4, ...

666 # ps[alts-1::2] chokes PyChecker

667 ps = ps[slice(alts-1, None, 2)]

668

669 return ps

670

671

672 try:

673 from math import prod as fprod # Python 3.8

674 except ImportError:

675

676 def fprod(xs, start=1):

677 '''Iterable product, like C{math.prod} or C{numpy.prod}.

678

679 @arg xs: Iterable of values to be multiplied (each

680 C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

681 @kwarg start: Initial value, also the value returned

682 for an empty B{C{xs}} (C{scalar}).

683

684 @return: The product (C{float} or L{Fsum}).

685

686 @see: U{NumPy.prod<https://docs.SciPy.org/doc/

687 numpy/reference/generated/numpy.prod.html>}.

688 '''

689 return freduce(_operator.mul, xs, start)

690

691

692 def frandoms(n, seeded=None):

693 '''Generate C{n} (long) lists of random C{floats}.

694

695 @arg n: Number of lists to generate (C{int}, non-negative).

696 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or

697 if C{True}, seed using today's C{year-day}.

698

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

700 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.

701 '''

702 from random import gauss, random, seed, shuffle

703

704 if seeded is None:

705 pass

706 elif seeded and isbool(seeded):

707 from time import localtime

708 seed(localtime().tm_yday)

709 elif isscalar(seeded):

710 seed(seeded)

711

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

713 for _ in range(n):

714 s = 0

715 t = list(c)

716 _a = t.append

717 for _ in range(n * 8):

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

719 _a(v)

720 s += v

721 shuffle(t)

722 yield t

723

724

725 def frange(start, number, step=1):

726 '''Generate a range of C{float}s.

727

728 @arg start: First value (C{float}).

729 @arg number: The number of C{float}s to generate (C{int}).

730 @kwarg step: Increment value (C{float}).

731

732 @return: A generator (C{float}s).

733

734 @see: U{NumPy.prod<https://docs.SciPy.org/doc/

735 numpy/reference/generated/numpy.arange.html>}.

736 '''

737 if not isint(number):

738 raise _IsnotError(int.__name__, number=number)

739 for i in range(number):

740 yield start + (step * i)

741

742

743 try:

744 from functools import reduce as freduce

745 except ImportError:

746 try:

747 freduce = reduce # PYCHOK expected

748 except NameError: # Python 3+

749

750 def freduce(f, xs, *start):

751 '''For missing C{functools.reduce}.

752 '''

753 if start:

754 r = v = start[0]

755 else:

756 r, v = 0, MISSING

757 for v in xs:

758 r = f(r, v)

759 if v is MISSING:

760 raise _TypeError(xs=(), start=MISSING)

761 return r

762

763

764 def fremainder(x, y):

765 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.

766

767 @arg x: Numerator (C{scalar}).

768 @arg y: Modulus, denominator (C{scalar}).

769

770 @return: Remainder (C{scalar}, preserving signed

771 0.0) or C{NAN} for any non-finite B{C{x}}.

772

773 @raise ValueError: Infinite or near-zero B{C{y}}.

774

775 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/

776 project/geographiclib/>} and Python 3.7+

777 U{math.remainder<https://docs.Python.org/3/

778 library/math.html#math.remainder>}.

779 '''

780 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and

781 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native

782 # fmod( 0, 360) == 0.0

783 # fmod( 360, 360) == 0.0

784 # fmod(-0, 360) == 0.0

785 # fmod(-0.0, 360) == -0.0

786 # fmod(-360, 360) == -0.0

787 # however, using the % operator ...

788 # 0 % 360 == 0

789 # 360 % 360 == 0

790 # 360.0 % 360 == 0.0

791 # -0 % 360 == 0

792 # -360 % 360 == 0 == (-360) % 360

793 # -0.0 % 360 == 0.0 == (-0.0) % 360

794 # -360.0 % 360 == 0.0 == (-360.0) % 360

795

796 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)

797 # == +0.0. This fixes this bug. See also Math::AngNormalize

798 # in the C++ library, Math.sincosd has a similar fix.

799 if isfinite(x):

800 try:

801 r = remainder(x, y) if x else x

802 except Exception as e:

803 raise _xError(e, unstr(fremainder, x, y))

804 else: # handle x INF and NINF as NAN

805 r = NAN

806 return r

807

808

809 if _MODS.sys_version_info2 < (3, 8): # PYCHOK no cover

810 from math import hypot # OK in Python 3.7-

811

812 def hypot_(*xs):

813 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.

814

815 Similar to Python 3.8+ n-dimension U{math.hypot

816 <https://docs.Python.org/3.8/library/math.html#math.hypot>},

817 but exceptions, C{nan} and C{infinite} values are

818 handled differently.

819

820 @arg xs: X arguments (C{scalar}s), all positional.

821

822 @return: Norm (C{float}).

823

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

825

826 @raise ValueError: Invalid or no B{C{xs}} values.

827

828 @note: The Python 3.8+ Euclidian distance U{math.dist

829 <https://docs.Python.org/3.8/library/math.html#math.dist>}

830 between 2 I{n}-dimensional points I{p1} and I{p2} can be

831 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},

832 provided I{p1} and I{p2} have the same, non-zero length I{n}.

833 '''

834 return float(_Hypot(*xs))

835

836 elif _MODS.sys_version_info2 < (3, 10):

837 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see

838 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},

839 # U{cffk<https://Bugs.Python.org/issue43088>} and module

840 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}

841

842 def hypot(x, y):

843 '''Compute the norm M{sqrt(x**2 + y**2)}.

844

845 @arg x: X argument (C{scalar}).

846 @arg y: Y argument (C{scalar}).

847

848 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).

849 '''

850 return float(_Hypot(x, y))

851

852 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9

853 else:

854 from math import hypot # PYCHOK in Python 3.10+

855 hypot_ = hypot

856

857

858 def _Hypot(*xs):

859 '''(INTERNAL) Substitute for inaccurate C{math.hypot}.

860 '''

861 return Fhypot(*xs, nonfinites=True, raiser=False) # f2product=True

862

863

864 def hypot1(x):

865 '''Compute the norm M{sqrt(1 + x**2)}.

866

867 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).

868

869 @return: Norm (C{float} or L{Fhypot}).

870 '''

871 h = _1_0

872 if x:

873 if _isFsum_2Tuple(x):

874 h = _Hypot(h, x)

875 h = float(h)

876 else:

877 h = hypot(h, x)

878 return h

879

880

881 def hypot2(x, y):

882 '''Compute the I{squared} norm M{x**2 + y**2}.

883

884 @arg x: X (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

885 @arg y: Y (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

886

887 @return: C{B{x}**2 + B{y}**2} (C{float}).

888 '''

889 x, y = map1(abs, x, y) # NOT fabs!

890 if y > x:

891 x, y = y, x

892 h2 = x**2

893 if h2 and y:

894 h2 *= (y / x)**2 + _1_0

895 return float(h2)

896

897

898 def hypot2_(*xs):

899 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.

900

901 @arg xs: Components (each C{scalar}, an L{Fsum} or

902 L{Fsum2Tuple}), all positional.

903

904 @return: Squared norm (C{float}).

905

906 @see: Class L{Fpowers} for further details.

907 '''

908 h2 = float(max(map(abs, xs))) if xs else _0_0

909 if h2: # and isfinite(h2)

910 _h = _1_0 / h2

911 xs = ((x * _h) for x in xs)

912 H2 = Fpowers(2, *xs, nonfinites=True) # f2product=True

913 h2 = H2.fover(_h**2)

914 return h2

915

916

917 def norm2(x, y):

918 '''Normalize a 2-dimensional vector.

919

920 @arg x: X component (C{scalar}).

921 @arg y: Y component (C{scalar}).

922

923 @return: 2-Tuple C{(x, y)}, normalized.

924

925 @raise ValueError: Invalid B{C{x}} or B{C{y}}

926 or zero norm.

927 '''

928 try:

929 h = None

930 h = hypot(x, y)

931 if h:

932 x, y = (x / h), (y / h)

933 else:

934 x = _copysign_0_0(x) # pass?

935 y = _copysign_0_0(y)

936 except Exception as e:

937 raise _xError(e, x=x, y=y, h=h)

938 return x, y

939

940

941 def norm_(*xs):

942 '''Normalize the components of an n-dimensional vector.

943

944 @arg xs: Components (each C{scalar}, an L{Fsum} or

945 L{Fsum2Tuple}), all positional.

946

947 @return: Yield each component, normalized.

948

949 @raise ValueError: Invalid or insufficent B{C{xs}}

950 or zero norm.

951 '''

952 try:

953 i = h = None

954 x = xs

955 h = hypot_(*xs)

956 _h = (_1_0 / h) if h else _0_0

957 for i, x in enumerate(xs):

958 yield x * _h

959 except Exception as X:

960 raise _xsError(X, xs, i, x, h=h)

961

962

963 def _powers(x, n):

964 '''(INTERNAL) Yield C{x**i for i=1..n}.

965 '''

966 p = 1 # type(p) == type(x)

967 for _ in range(n):

968 p *= x

969 yield p

970

971

972 def _root(x, p, where):

973 '''(INTERNAL) Raise C{x} to power C{0 < p < 1}.

974 '''

975 try:

976 if x > 0:

977 r = Fsum(f2product=True, nonfinites=True)(x)

978 return r.fpow(p).as_iscalar

979 elif x < 0:

980 raise ValueError(_negative_)

981 except Exception as X:

982 raise _xError(X, unstr(where, x))

983 return _0_0

984

985

986 def sqrt0(x, Error=None):

987 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},

988 preserving C{type(B{x})}.

989

990 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

991 @kwarg Error: Error to raise for negative B{C{x}}.

992

993 @return: Square root (C{float} or L{Fsum}) or C{0.0}.

994

995 @raise TypeeError: Invalid B{C{x}}.

996

997 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}

998 returns C{0.0}.

999 '''

1000 if Error and x < 0:

1001 raise Error(unstr(sqrt0, x))

1002 return _root(x, _0_5, sqrt0) if x > EPS02 else (

1003 _0_0 if x < EPS02 else EPS0)

1004

1005

1006 def sqrt3(x):

1007 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},

1008 preserving C{type(B{x})}.

1009

1010 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

1011

1012 @return: Square root I{cubed} (C{float} or L{Fsum}).

1013

1014 @raise TypeeError: Invalid B{C{x}}.

1015

1016 @raise ValueError: Negative B{C{x}}.

1017

1018 @see: Functions L{cbrt} and L{cbrt2}.

1019 '''

1020 return _root(x, _1_5, sqrt3)

1021

1022

1023 def sqrt_a(h, b):

1024 '''Compute C{I{a}} side of a right-angled triangle from

1025 C{sqrt(B{h}**2 - B{b}**2)}.

1026

1027 @arg h: Hypotenuse or outer annulus radius (C{scalar}).

1028 @arg b: Triangle side or inner annulus radius (C{scalar}).

1029

1030 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).

1031

1032 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.

1033

1034 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.

1035

1036 @see: Inner tangent chord B{I{d}} of an U{annulus

1037 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}

1038 and function U{annulus_area<https://People.SC.FSU.edu/

1039 ~jburkardt/py_src/geometry/geometry.py>}.

1040 '''

1041 try:

1042 if not (_isHeight(h) and _isRadius(b)):

1043 raise TypeError(_not_scalar_)

1044 c = fabs(h)

1045 if c > EPS0:

1046 s = _1_0 - (b / c)**2

1047 if s < 0:

1048 raise ValueError(_h_lt_b_)

1049 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)

1050 else: # PYCHOK no cover

1051 b = fabs(b)

1052 d = c - b

1053 if d < 0:

1054 raise ValueError(_h_lt_b_)

1055 d *= c + b

1056 a = sqrt(d) if d else _0_0

1057 except Exception as x:

1058 raise _xError(x, h=h, b=b)

1059 return copysign0(a, h)

1060

1061

1062 def zcrt(x):

1063 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},

1064 preserving C{type(B{x})}.

1065

1066 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

1067

1068 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).

1069

1070 @see: Functions L{bqrt} and L{zqrt}.

1071

1072 @raise TypeeError: Invalid B{C{x}}.

1073

1074 @raise ValueError: Negative B{C{x}}.

1075 '''

1076 return _root(x, _1_6th, zcrt)

1077

1078

1079 def zqrt(x):

1080 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,

1081 M{x**(1 / 8)}, preserving C{type(B{x})}.

1082

1083 @arg x: Value (C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

1084

1085 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).

1086

1087 @see: Functions L{bqrt} and L{zcrt}.

1088

1089 @raise TypeeError: Invalid B{C{x}}.

1090

1091 @raise ValueError: Negative B{C{x}}.

1092 '''

1093 return _root(x, _0_125, zqrt)

1094

1095# **) MIT License

1096#

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

1098#

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

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

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

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

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

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

1105#

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

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

1108#

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

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

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

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

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

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

1115# OTHER DEALINGS IN THE SOFTWARE.