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

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 _N_1_0, _1_5, _copysign_0_0, _isfinite, remainder

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

15 _xError, _xkwds_get, _xkwds_pop2

16 from pygeodesy.fsums import _2float, Fsum, fsum, fsum1_, _isFsumTuple, _1primed, \

17 Fmt, unstr

18 from pygeodesy.interns import MISSING, _negative_, _not_scalar_

19 from pygeodesy.lazily import _ALL_LAZY, _sys_version_info2

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

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

22

23 from math import fabs, sqrt # pow

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

25

26__all__ = _ALL_LAZY.fmath

27__version__ = '24.05.07'

28

29# sqrt(2) <https://WikiPedia.org/wiki/Square_root_of_2>

30_0_4142 = 0.41421356237309504880 # ... sqrt(2) - 1

31_2_3rd = _1_3rd * 2

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

33

34

35 class Fdot(Fsum):

36 '''Precision dot product.

37 '''

38 def __init__(self, a, *b, **name_RESIDUAL):

39 '''New L{Fdot} precision dot product M{sum(a[i] * b[i] for

40 i=0..len(a)-1)}.

41

42 @arg a: Iterable of values (each C{scalar} or an L{Fsum} or

43 L{Fsum2Tuple} instance).

44 @arg b: Other values (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

45 instance), all positional.

46 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}

47 threshold, see L{Fsum<Fsum.__init__>}.

48

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

50

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

52

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

54

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

56

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

58 '''

59 Fsum.__init__(self, **name_RESIDUAL)

60 self.fadd(_map_mul(a, b, Fdot))

61

62

63 class Fhorner(Fsum):

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

65 '''

66 def __init__(self, x, *cs, **name_RESIDUAL):

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

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

69

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

71 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or

72 L{Fsum2Tuple} instance), all positional.

73 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}

74 threshold, see L{Fsum<Fsum.__init__>}.

75

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

77

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

79

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

81

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

83 '''

84 Fsum.__init__(self, **name_RESIDUAL)

85 if cs:

86 if _isFsumTuple(x):

87 _mul = self._mul_Fsum

88 else:

89 _mul = self._mul_scalar

90 x = _2float(x=x)

91 op = Fhorner.__name__

92 if len(cs) > 1 and x:

93 for c in reversed(cs):

94 self._fset_ps(_mul(x, op))

95 self._fadd(c, op, up=False)

96 self._update()

97 else: # x == 0

98 self._fadd(cs[0], op)

99 else:

100 self._fset_ps(_0_0)

101

102

103 class Fhypot(Fsum):

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

105 '''

106 def __init__(self, *xs, **root_name_RESIDUAL_raiser):

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

108 (raised to the power I{root}).

109

110 @arg xs: Components (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

111 instance), all positional.

112 @kwarg root_name_RESIDUAL_raiser: Optional, exponent and C{B{root}=2}

113 order, C{B{name}=NN}, C{B{RESIDUAL}=0.0} threshold and

114 C{B{raiser}=True}, see class L{Fsum<Fsum.__init__>} and

115 method L{root<Fsum.root>}.

116 '''

117 r = None # _xkwds_pop2 error

118 try:

119 r, kwds = _xkwds_pop2(root_name_RESIDUAL_raiser, root=2)

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

121 raiser = _Fsum__init__(self, **kwds)

122 if xs:

123 self._facc_power(r, xs, Fhypot, **raiser)

124 self._fset(self.root(r, **raiser))

125 except Exception as X:

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

127

128

129 class Fpolynomial(Fsum):

130 '''Precision polynomial evaluation.

131 '''

132 def __init__(self, x, *cs, **name_RESIDUAL):

133 '''New L{Fpolynomial} evaluation of the polynomial

134 M{sum(cs[i] * x**i for i=0..len(cs)-1)}.

135

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

137 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or

138 L{Fsum2Tuple} instance), all positional.

139 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}

140 threshold, see L{Fsum<Fsum.__init__>}.

141

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

143

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

145

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

147

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

149 '''

150 Fsum.__init__(self, *cs[:1], **name_RESIDUAL)

151 n = len(cs) - 1

152 if n > 0:

153 self.fadd(_1map_mul(cs[1:], _powers(x, n)))

154 elif n < 0:

155 self._fset_ps(_0_0)

156

157

158 class Fpowers(Fsum):

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

160 '''

161 def __init__(self, power, *xs, **name_RESIDUAL_raiser):

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

163

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

165 @arg xs: One or more bases (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

166 instance), all positional.

167 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN}, C{B{RESIDUAL}=0.0}

168 threshold and C{B{raiser}=True}, see L{Fsum<Fsum.__init__>}

169 and L{fpow<Fsum.fpow>}.

170 '''

171 try:

172 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)

173 if xs:

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

175 except Exception as X:

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

177

178

179 class Froot(Fsum):

180 '''The root of a precision summation.

181 '''

182 def __init__(self, root, *xs, **name_RESIDUAL_raiser):

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

184

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

186 @arg xs: Items to summate (each a C{scalar} or an L{Fsum} or L{Fsum2Tuple}

187 instance), all positional.

188 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN}, C{B{RESIDUAL}=0.0}

189 threshold and C{B{raiser}=True}, see L{Fsum<Fsum.__init__>}

190 and L{fpow<Fsum.fpow>}.

191 '''

192 try:

193 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)

194 if xs:

195 self.fadd(xs)

196 self._fset(self.root(root, **raiser))

197 except Exception as X:

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

199

200

201 class Fcbrt(Froot):

202 '''Cubic root of a precision summation.

203 '''

204 def __init__(self, *xs, **name_RESIDUAL_raiser):

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

206

207 @see: Class L{Froot} for further details.

208 '''

209 Froot.__init__(self, 3, *xs, **name_RESIDUAL_raiser)

210

211

212 class Fsqrt(Froot):

213 '''Square root of a precision summation.

214 '''

215 def __init__(self, *xs, **name_RESIDUAL_raiser):

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

217

218 @see: Class L{Froot} for further details.

219 '''

220 Froot.__init__(self, 2, *xs, **name_RESIDUAL_raiser)

221

222

223 def _Fsum__init__(inst, raiser=MISSING, **name_RESIDUAL):

224 '''(INTERNAL) Init an C{F...} instance above.

225 '''

226 Fsum.__init__(inst, **name_RESIDUAL) # PYCHOK self

227 inst._fset_ps(_0_0)

228 return {} if raiser is MISSING else dict(raiser=raiser)

229

230

231 def bqrt(x):

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

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

234

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

236

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

238

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

240

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

242

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

244 '''

245 return _root(x, _0_25, bqrt)

246

247

248 try:

249 from math import cbrt as _cbrt # Python 3.11+

250

251 except ImportError: # Python 3.10-

252

253 def _cbrt(x):

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

255 '''

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

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

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

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

260

261

262 def cbrt(x):

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

264

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

266

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

268

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

270 '''

271 if _isFsumTuple(x):

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

273 if x.signOf() < 0:

274 r = -r

275 else:

276 r = _cbrt(x)

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

278

279

280 def cbrt2(x): # PYCHOK attr

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

282

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

284

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

286

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

288 '''

289 return abs(x).fpow(_2_3rd) if _isFsumTuple(x) else _cbrt(x**2)

290

291

292 def euclid(x, y):

293 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by

294 M{max(abs(x), abs(y)) + min(abs(x), abs(y)) * 0.4142...}.

295

296 @arg x: X component (C{scalar} or L{Fsum} instance).

297 @arg y: Y component (C{scalar} or L{Fsum} instance).

298

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

300

301 @see: Function L{euclid_}.

302 '''

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

304 if y > x:

305 x, y = y, x

306 return x + y * _0_4142 # XXX * _0_5 before 20.10.02

307

308

309 def euclid_(*xs):

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

311 cascaded L{euclid}.

312

313 @arg xs: X arguments (each C{scalar} or an L{Fsum}

314 instance), all positional.

315

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

317

318 @see: Function L{euclid}.

319 '''

320 e = _0_0

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

322 # e = euclid(x, e)

323 if e < x:

324 e, x = x, e

325 if x:

326 e += x * _0_4142

327 return e

328

329

330 def facos1(x):

331 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}.

332

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

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

335 '''

336 a = fabs(x)

337 if a < EPS0:

338 r = PI_2

339 elif a < EPS1:

340 H = Fhorner(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)

341 r = float(H * sqrt(_1_0 - a))

342 if x < 0:

343 r = PI - r

344 else:

345 r = PI if x < 0 else _0_0

346 return r

347

348

349 def fasin1(x): # PYCHOK no cover

350 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}.

351

352 @see: L{facos1}.

353 '''

354 return PI_2 - facos1(x)

355

356

357 def fatan(x):

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

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 H = Fhorner(x, _0_0, 1.0300981634, -0.1784, -0.0663)

385 return float(H)

386

387

388 def fatan2(y, x):

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

390

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

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

393 and L{fatan1}.

394 '''

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

396 if b > a:

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

398 elif a > b:

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

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

401 r = PI_4

402 else: # a == b == 0

403 return _0_0

404 if x < 0:

405 r = PI - r

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

407 r = -r

408 return r

409

410

411 def favg(a, b, f=_0_5):

412 '''Return the precision average of two values.

413

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

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

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

417

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

419 '''

420# @raise ValueError: Fraction out of range.

421# '''

422# if not 0 <= f <= 1: # XXX restrict fraction?

423# raise _ValueError(fraction=f)

424 # a + f * (b - a) == a * (1 - f) + b * f

425 return fsum1_(a, a * (-f), b * f)

426

427

428 def fdot(a, *b):

429 '''Return the precision dot product M{sum(a[i] * b[i] for

430 i=0..len(a))}.

431

432 @arg a: Iterable of values (each C{scalar}).

433 @arg b: Other values (each C{scalar}), all positional.

434

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

436

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

438

439 @see: Class L{Fdot} and U{Algorithm 5.10 B{DotK}

440 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.

441 '''

442 return fsum(_map_mul(a, b, fdot))

443

444

445 def fdot3(xs, ys, zs, start=0):

446 '''Return the precision dot product M{start +

447 sum(a[i] * b[i] * c[i] for i=0..len(a)-1)}.

448

449 @arg xs: Iterable (each C{scalar} or an L{Fsum} or

450 L{Fsum2Tuple} instance).

451 @arg ys: Iterable (each C{scalar} or an L{Fsum} or

452 L{Fsum2Tuple} instance).

453 @arg zs: Iterable (each C{scalar} or an L{Fsum} or

454 L{Fsum2Tuple} instance).

455 @kwarg start: Optional bias (C{scalar} or an L{Fsum}

456 or L{Fsum2Tuple}).

457

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

459

460 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})}

461 and/or C{len(B{zs})}.

462

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

464 '''

465 def _mul3(xs, ys, zs, s, p):

466 if s:

467 yield s

468 if p:

469 yield _1_0

470 _F = Fsum

471 for x, y, z in zip(xs, ys, zs):

472 yield (_F(x) * y) * z

473 if p:

474 yield _N_1_0

475

476 n = len(xs)

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

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

479

480 return fsum(_mul3(xs, ys, zs, start, n < 4))

481

482

483 def fhorner(x, *cs):

484 '''Evaluate the polynomial M{sum(cs[i] * x**i for

485 i=0..len(cs)-1)} using the Horner form.

486

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

488

489 @see: Class L{Fhorner} for further details.

490 '''

491 H = Fhorner(x, *cs)

492 return float(H)

493

494

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

496 '''Interpolate using U{Inverse Distance Weighting

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

498

499 @arg xs: Known values (each C{scalar} or an L{Fsum} or

500 L{Fsum2Tuple} instance).

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

502 or L{Fsum2Tuple} instance).

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

504

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

506

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

508

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

510

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

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

513

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

515 '''

516 n, xs = len2(xs)

517 if n > 1:

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

519 if b < 0:

520 try: # weighted

521 _F = Fsum

522 W = _F()

523 X = _F()

524 for i, d in enumerate(ds):

525 x = xs[i]

526 if d < EPS0:

527 if d < 0:

528 raise ValueError(_negative_)

529 x = float(x)

530 i = n

531 break

532 D = _F(d).fpow(b)

533 W += D

534 X += D.fmul(x)

535 else:

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

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

538 except IndexError:

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

540 except Exception as X:

541 _I = Fmt.INDEX

542 raise _xError(X, _I(xs=i), x, _I(ds=i), d)

543 else: # b == 0

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

545 i = n

546 elif n:

547 x = float(xs[0])

548 i = n

549 else:

550 x = _0_0

551 i, _ = len2(ds)

552 if i != n:

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

554 return x

555

556

557 def fmean(xs):

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

559

560 @arg xs: Values (C{scalar} or L{Fsum} instances).

561

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

563

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

565

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

567 '''

568 n, xs = len2(xs)

569 if n < 1:

570 raise LenError(fmean, xs=xs)

571 return Fsum(*xs).fover(n) if n > 1 else _2float(index=0, xs=xs[0])

572

573

574 def fmean_(*xs):

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

576

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

578 '''

579 return fmean(xs)

580

581

582 def fpolynomial(x, *cs, **over):

583 '''Evaluate the polynomial M{sum(cs[i] * x**i for

584 i=0..len(cs)) [/ over]}.

585

586 @kwarg over: Optional final, I{non-zero} divisor (C{scalar}).

587

588 @return: Polynomial value (C{float}).

589

590 @see: Class L{Fpolynomial} for further details.

591 '''

592 P = Fpolynomial(x, *cs)

593 d = _xkwds_get(over, over=0) if over else 0

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

595

596

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

598 '''Return a series of powers M{[x**i for i=1..n]}.

599

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

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

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

603 exponent (C{int}).

604

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

606

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

608

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

610 '''

611 if not isint(n):

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

613 elif n < 1:

614 raise _ValueError(n=n)

615

616 p = x if isint(x) or _isFsumTuple(x) else _2float(x=x)

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

618

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

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

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

622

623 return ps

624

625

626 try:

627 from math import prod as fprod # Python 3.8

628 except ImportError:

629

630 def fprod(xs, start=1):

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

632

633 @arg xs: Terms to be multiplied, an iterable, list,

634 tuple, etc. (C{scalar}s).

635 @kwarg start: Initial term, also the value returned

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

637

638 @return: The product (C{float}).

639

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

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

642 '''

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

644

645

646 def frandoms(n, seeded=None):

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

648

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

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

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

652

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

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

655 '''

656 from random import gauss, random, seed, shuffle

657

658 if seeded is None:

659 pass

660 elif seeded and isbool(seeded):

661 from time import localtime

662 seed(localtime().tm_yday)

663 elif isscalar(seeded):

664 seed(seeded)

665

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

667 for _ in range(n):

668 s = 0

669 t = list(c)

670 _a = t.append

671 for _ in range(n * 8):

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

673 _a(v)

674 s += v

675 shuffle(t)

676 yield t

677

678

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

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

681

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

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

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

685

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

687

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

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

690 '''

691 if not isint(number):

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

693 for i in range(number):

694 yield start + (step * i)

695

696

697 try:

698 from functools import reduce as freduce

699 except ImportError:

700 try:

701 freduce = reduce # PYCHOK expected

702 except NameError: # Python 3+

703

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

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

706 '''

707 if start:

708 r = v = start[0]

709 else:

710 r, v = 0, MISSING

711 for v in xs:

712 r = f(r, v)

713 if v is MISSING:

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

715 return r

716

717

718 def fremainder(x, y):

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

720

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

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

723

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

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

726

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

728

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

730 project/geographiclib/>} and Python 3.7+

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

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

733 '''

734 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and

735 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native

736 # fmod( 0, 360) == 0.0

737 # fmod( 360, 360) == 0.0

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

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

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

741 # however, using the % operator ...

742 # 0 % 360 == 0

743 # 360 % 360 == 0

744 # 360.0 % 360 == 0.0

745 # -0 % 360 == 0

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

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

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

749

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

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

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

753 if _isfinite(x):

754 try:

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

756 except Exception as e:

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

758 else: # handle x INF and NINF as NAN

759 r = NAN

760 return r

761

762

763 if _sys_version_info2 < (3, 8): # PYCHOK no cover

764 from math import hypot # OK in Python 3.7-

765

766 def hypot_(*xs):

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

768

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

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

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

772 handled differently.

773

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

775

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

777

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

779

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

781

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

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

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

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

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

787 '''

788 return float(Fhypot(*xs, raiser=False))

789

790 elif _sys_version_info2 < (3, 10):

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

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

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

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

795

796 def hypot(x, y):

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

798

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

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

801

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

803 '''

804 return float(Fhypot(x, y, raiser=False))

805

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

807 else:

808 from math import hypot # PYCHOK in Python 3.10+

809 hypot_ = hypot

810

811

812 def hypot1(x):

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

814

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

816

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

818 '''

819 if _isFsumTuple(x):

820 h = float(Fhypot(_1_0, x)) if x else _1_0

821 else:

822 h = hypot(_1_0, x) if x else _1_0

823 return h

824

825

826 def hypot2(x, y):

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

828

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

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

831

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

833 '''

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

835 if y > x:

836 x, y = y, x

837 if x:

838 h2 = x**2

839 if y:

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

841 h2 = float(h2)

842 else:

843 h2 = _0_0

844 return h2

845

846

847 def hypot2_(*xs):

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

849

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

851 L{Fsum2Tuple} instance), all positional.

852

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

854

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

856 '''

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

858 if h2:

859 _h = _1_0 / h2

860 h2 = Fpowers(2, *((x * _h) for x in xs))

861 h2 = h2.fover(_h**2)

862 return h2

863

864

865 def _map_mul(xs, ys, where):

866 '''(INTERNAL) Yield each B{C{x * y}}.

867 '''

868 n = len(ys)

869 if len(xs) != n: # PYCHOK no cover

870 raise LenError(where, xs=len(xs), ys=n)

871 return _1map_mul(xs, ys) if n < 4 else map(

872 _operator.mul, map(Fsum, xs), ys)

873

874

875 def _1map_mul(xs, ys):

876 '''(INTERNAL) Yield each B{C{x * y}}, 1-primed.

877 '''

878 return _1primed(map(_operator.mul, map(Fsum, xs), ys))

879

880

881 def norm2(x, y):

882 '''Normalize a 2-dimensional vector.

883

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

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

886

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

888

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

890 or zero norm.

891 '''

892 try:

893 h = hypot(x, y)

894 if h:

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

896 else:

897 x = _copysign_0_0(x) # pass?

898 y = _copysign_0_0(y)

899 except Exception as e:

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

901 return x, y

902

903

904 def norm_(*xs):

905 '''Normalize all n-dimensional vector components.

906

907 @arg xs: Components (C{scalar}s), all positional.

908

909 @return: Yield each component, normalized.

910

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

912 or zero norm.

913 '''

914 try:

915 i = x = h = None

916 h = hypot_(*xs)

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

918 for i, x in enumerate(xs):

919 yield x * _h

920 except Exception as X:

921 raise _xError(X, Fmt.SQUARE(xs=i), x, h=h)

922

923

924 def _powers(x, n):

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

926 '''

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

928 for _ in range(n):

929 p *= x

930 yield p

931

932

933 def _root(x, p, where):

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

935 '''

936 try:

937 if x > 0:

938 return Fsum(x).fpow(p).as_iscalar

939 elif x < 0:

940 raise ValueError(_negative_)

941 except Exception as X:

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

943 return _0_0

944

945

946 def sqrt0(x, Error=None):

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

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

949

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

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

952

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

954

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

956

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

958 returns C{0.0}.

959 '''

960 if Error and x < 0:

961 raise Error(unstr(sqrt0, x))

962 return _root(x, _0_5, sqrt0) if x > EPS02 else (_0_0 if x < EPS02 else EPS0)

963

964

965 def sqrt3(x):

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

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

968

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

970

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

972

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

974

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

976

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

978 '''

979 return _root(x, _1_5, sqrt3)

980

981

982 def sqrt_a(h, b):

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

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

985

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

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

988

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

990

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

992

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

994

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

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

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

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

999 '''

1000 try:

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

1002 raise TypeError(_not_scalar_)

1003 c = fabs(h)

1004 if c > EPS0:

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

1006 if s < 0:

1007 raise ValueError(_h_lt_b_)

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

1009 else: # PYCHOK no cover

1010 b = fabs(b)

1011 d = c - b

1012 if d < 0:

1013 raise ValueError(_h_lt_b_)

1014 d *= c + b

1015 a = sqrt(d) if d else _0_0

1016 except Exception as x:

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

1018 return copysign0(a, h)

1019

1020

1021 def zcrt(x):

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

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

1024

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

1026

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

1028

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

1030

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

1032

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

1034 '''

1035 return _root(x, _1_6th, zcrt)

1036

1037

1038 def zqrt(x):

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

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

1041

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

1043

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

1045

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

1047

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

1049

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

1051 '''

1052 return _root(x, _0_125, zqrt)

1053

1054# **) MIT License

1055#

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

1057#

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

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

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

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

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

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

1064#

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

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

1067#

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

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

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

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

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

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

1074# OTHER DEALINGS IN THE SOFTWARE.