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, isint, len2

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

11 _0_0, _0_125, _0_25, _0_5, _1_0, _N_1_0, \

12 _1_3rd, _1_5, _1_6th, _2_0, _2_3rd, _3_0, \

13 _isfinite, isnear1, _over, remainder

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

15 _xError, _xkwds_get, _xkwds_pop2

16 from pygeodesy.fsums import _2float, Fsum, _fsum, fsum, fsum1_, _pow_op_, \

17 _1primed, Fmt, unstr

18 from pygeodesy.interns import MISSING, _few_, _h_, _invokation_, _negative_, \

19 _not_scalar_, _SPACE_, _too_

20 from pygeodesy.lazily import _ALL_LAZY, _sys_version_info2

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

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

23

24 from math import fabs, sqrt # pow

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

26

27__all__ = _ALL_LAZY.fmath

28__version__ = '24.03.31'

29

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

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

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]

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

41

42 @arg a: Iterable, list, tuple, etc. (C{scalar}s).

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

44 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and

45 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.

46

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

48

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

50

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

52 '''

53 Fsum.__init__(self, **name_RESIDUAL)

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

55

56

57 class Fhorner(Fsum):

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

59 '''

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

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

62 for i=0..len(cs)-1)}.

63

64 @arg x: Polynomial argument (C{scalar} or C{Fsum} instance).

65 @arg cs: Polynomial coeffients (C{scalar} or C{Fsum}

66 instances), all positional.

67 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and

68 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.

69

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

71

72 @raise TypeError: Non-scalar B{C{x}}.

73

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

75

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

77 L{Fsum.fmul}.

78 '''

79 Fsum.__init__(self, **name_RESIDUAL)

80 if cs:

81 if isinstance(x, Fsum):

82 _mul = self._mul_Fsum

83 else:

84 _mul = self._mul_scalar

85 x = _2float(x=x)

86 op = Fhorner.__name__

87 if len(cs) > 1 and x:

88 for c in reversed(cs):

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

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

91 self._update()

92 else: # x == 0

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

94 else:

95 self._fset(_0_0)

96

97

98 class Fhypot(Fsum):

99 '''Precision summation and hypotenuse, default C{power=2}.

100 '''

101 def __init__(self, *xs, **power_name_RESIDUAL):

102 '''New L{Fhypot} hypotenuse of (the I{power} of) several components.

103

104 @arg xs: One or more components (each a C{scalar} or an C{Fsum}

105 instance).

106 @kwarg power_name_RESIDUAL: Optional, C{scalar} exponent and

107 root order C{B{power}=2}, a C{B{name}=NN} and

108 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.

109 '''

110 try:

111 p, kwds = _xkwds_pop2(power_name_RESIDUAL, power=2)

112 Fsum.__init__(self, **kwds)

113 if xs:

114 r = _1_0 / p

115 self._facc_power(p, xs, Fhypot)

116 self._fpow(r, _pow_op_)

117 else:

118 self._fset(_0_0)

119 except Exception as X:

120 raise self._ErrorX(X, xs, power=p)

121

122

123 class Fpolynomial(Fsum):

124 '''Precision polynomial evaluation.

125 '''

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

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

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

129

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

131 @arg cs: Polynomial coeffients (each a C{scalar} or

132 an L{Fsum} instance), all positional.

133 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and

134 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.

135

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

137

138 @raise TypeError: Non-scalar B{C{x}}.

139

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

141

142 @see: Class L{Fhorner}, function L{fpolynomial} and

143 method L{Fsum.fadd}.

144 '''

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

146 n = len(cs) - 1

147 if n > 0:

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

149 elif n < 0:

150 self._fset(_0_0)

151

152

153 class Fpowers(Fsum):

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

155 '''

156 def __init__(self, power, *xs, **name_RESIDUAL):

157 '''New L{Fpowers} sum of (the I{power} of) several values.

158

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

160 @arg xs: One or more values (each a C{scalar} or an

161 C{Fsum} instance).

162 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and

163 C{B{RESIDUAL}=None}, see L{Fsum.__init__}.

164 '''

165 try:

166 Fsum.__init__(self, **name_RESIDUAL)

167 if xs:

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

169 else:

170 self._fset(_0_0)

171 except Exception as x:

172 raise self._ErrorX(x, xs, power=power)

173

174

175 class Fn_rt(Fsum):

176 '''N-th root of a precision summation.

177 '''

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

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

180

181 @arg root: The order (C{scalar} or C{Fsum}),

182 non-zero.

183 @arg xs: Values to summate (each a C{scalar} or

184 an C{Fsum} instance).

185 @kwarg name_RESIDUAL: See L{Fsum.__init__}.

186 '''

187 try:

188 Fsum.__init__(self, **name_RESIDUAL)

189 if xs:

190 r = _1_0 / root

191 self. fadd(xs)

192 self._fpow(r, _pow_op_) # self **= r

193 else:

194 self._fset(_0_0)

195 except Exception as x:

196 raise self._ErrorX(x, xs, root=root)

197

198

199 class Fcbrt(Fn_rt):

200 '''Cubic root of a precision summation.

201 '''

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

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

204

205 @see: Class L{Fn_rt} for further details.

206 '''

207 Fn_rt.__init__(self, _3_0, *xs, **name_RESIDUAL)

208

209

210 class Fsqrt(Fn_rt):

211 '''Square root of a precision summation.

212 '''

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

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

215

216 @see: Class L{Fn_rt} for further details.

217 '''

218 Fn_rt.__init__(self, _2_0, *xs, **name_RESIDUAL)

219

220

221 def bqrt(x):

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

223

224 @arg x: Value (C{scalar}).

225

226 @return: I{Quartic} root (C{float}).

227

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

229

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

231 '''

232 return _root(x, _0_25, bqrt)

233

234

235 try:

236 from math import cbrt # Python 3.11+

237

238 def cbrt2(x):

239 '''Compute the cube root I{squared} M{x**(2/3)}.

240 '''

241 return cbrt(x)**2 # cbrt(-0.0*2) == -0.0

242

243 except ImportError: # Python 3.10-

244

245 def cbrt(x):

246 '''Compute the cube root M{x**(1/3)}.

247

248 @arg x: Value (C{scalar}).

249

250 @return: Cubic root (C{float}).

251

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

253 '''

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

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

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

257 return _copysign(pow(fabs(x), _1_3rd), x) # cbrt(-0.0) == -0.0

258

259 def cbrt2(x): # PYCHOK attr

260 '''Compute the cube root I{squared} M{x**(2/3)}.

261

262 @arg x: Value (C{scalar}).

263

264 @return: Cube root I{squared} (C{float}).

265

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

267 '''

268 return pow(fabs(x), _2_3rd) # XXX pow(fabs(x), _1_3rd)**2

269

270

271 def euclid(x, y):

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

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

274

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

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

277

278 @return: Appoximate norm (C{float}).

279

280 @see: Function L{euclid_}.

281 '''

282 x, y = fabs(x), fabs(y)

283 if x < y:

284 x, y = y, x

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

286

287

288 def euclid_(*xs):

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

290 by cascaded L{euclid}.

291

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

293

294 @return: Appoximate norm (C{float}).

295

296 @see: Function L{euclid}.

297 '''

298 e = _0_0

299 for x in sorted(map(fabs, xs)): # XXX not reverse=True

300 # e = euclid(x, e)

301 if e < x:

302 e, x = x, e

303 if x:

304 e += x * _0_4142

305 return e

306

307

308 def facos1(x):

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

310

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

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

313 '''

314 a = fabs(x)

315 if a < EPS0:

316 r = PI_2

317 elif a < EPS1:

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

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

320 if x < 0:

321 r = PI - r

322 else:

323 r = PI if x < 0 else _0_0

324 return r

325

326

327 def fasin1(x): # PYCHOK no cover

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

329

330 @see: L{facos1}.

331 '''

332 return PI_2 - facos1(x)

333

334

335 def fatan(x):

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

337 '''

338 a = fabs(x)

339 if a < _1_0:

340 r = fatan1(a) if a else _0_0

341 elif a > _1_0:

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

343 else:

344 r = PI_4

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

346 r = -r

347 return r

348

349

350 def fatan1(x):

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

352

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

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

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

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

357 IEEE Signal Processing Magazine, 111, May 2006.

358 '''

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

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

361 # x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))

362 H = Fhorner(x, _0_0, 1.0300982, -0.1784, -0.0663)

363 return float(H)

364

365

366 def fatan2(y, x):

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

368

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

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

371 and L{fatan1}.

372 '''

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

374 if b > a:

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

376 elif a > b:

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

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

379 r = PI_4

380 else: # a == b == 0

381 return _0_0

382 if x < 0:

383 r = PI - r

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

385 r = -r

386 return r

387

388

389 def favg(v1, v2, f=_0_5):

390 '''Return the average of two values.

391

392 @arg v1: One value (C{scalar}).

393 @arg v2: Other value (C{scalar}).

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

395

396 @return: M{v1 + f * (v2 - v1)} (C{float}).

397 '''

398# @raise ValueError: Fraction out of range.

399# '''

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

401# raise _ValueError(fraction=f)

402 # v1 + f * (v2 - v1) == v1 * (1 - f) + v2 * f

403 return fsum1_(v1, -f * v1, f * v2)

404

405

406 def fdot(a, *b):

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

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

409

410 @arg a: Iterable, list, tuple, etc. (C{scalar}s).

411 @arg b: All positional arguments (C{scalar}s).

412

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

414

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

416

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

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

419 '''

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

421

422

423 def fdot3(a, b, c, start=0):

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

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

426

427 @arg a: Iterable, list, tuple, etc. (C{scalar}s).

428 @arg b: Iterable, list, tuple, etc. (C{scalar}s).

429 @arg c: Iterable, list, tuple, etc. (C{scalar}s).

430 @kwarg start: Optional bias (C{scalar}).

431

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

433

434 @raise LenError: Unequal C{len(B{a})}, C{len(B{b})}

435 and/or C{len(B{c})}.

436

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

438 '''

439 def _mul3(a, b, c): # map function

440 return a * b * c

441

442 def _mul3_(a, b, c, start):

443 yield start

444 for abc in map(_mul3, a, b, c):

445 yield abc

446

447 if not len(a) == len(b) == len(c):

448 raise LenError(fdot3, a=len(a), b=len(b), c=len(c))

449

450 return fsum(_mul3_(a, b, c, start) if start else map(_mul3, a, b, c))

451

452

453 def fhorner(x, *cs):

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

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

456

457 @arg x: Polynomial argument (C{scalar}).

458 @arg cs: Polynomial coeffients (C{scalar}s).

459

460 @return: Horner value (C{float}).

461

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

463

464 @raise TypeError: Non-scalar B{C{x}}.

465

466 @raise ValueError: No B{C{cs}} coefficients or B{C{x}} is not finite.

467

468 @see: Function L{fpolynomial} and class L{Fhorner}.

469 '''

470 H = Fhorner(x, *cs)

471 return float(H)

472

473

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

475 '''Interpolate using U{Inverse Distance Weighting

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

477

478 @arg xs: Known values (C{scalar}s).

479 @arg ds: Non-negative distances (C{scalar}s).

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

481

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

483

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

485

486 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} value,

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

488

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

490 '''

491 n, xs = len2(xs)

492 d, ds = len2(ds)

493 if n != d or n < 1:

494 raise LenError(fidw, xs=n, ds=d)

495

496 d, x = min(zip(ds, xs))

497 if d > EPS0 and n > 1:

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

499 if b < 0:

500 ws = tuple(float(d)**b for d in ds)

501 t = fsum(_1map_mul(xs, ws)) # Fdot(xs, *ws)

502 x = _over(t, fsum(ws, floats=True))

503 else: # b == 0

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

505 elif d < 0: # PYCHOK no cover

506 n = Fmt.SQUARE(distance=ds.index(d))

507 raise _ValueError(n, d, txt=_negative_)

508 return x

509

510

511 def fmean(xs):

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

513

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

515

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

517

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

519

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

521 '''

522 n, xs = len2(xs)

523 if n < 1:

524 raise LenError(fmean, xs=xs)

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

526

527

528 def fmean_(*xs):

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

530

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

532 '''

533 return fmean(xs)

534

535

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

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

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

539

540 @arg x: Polynomial argument (C{scalar}).

541 @arg cs: Polynomial coeffients (C{scalar}s), all

542 positional.

543 @kwarg over: Optional final, I{non-zero} divisor

544 (C{scalar}).

545

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

547

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

549

550 @raise TypeError: Non-scalar B{C{x}}.

551

552 @raise ValueError: No B{C{cs}} coefficients or B{C{x}} is not finite.

553

554 @see: Function L{fhorner} and class L{Fpolynomial}.

555 '''

556 P = Fpolynomial(x, *cs)

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

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

559

560

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

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

563

564 @arg x: Value (C{scalar} or L{Fsum}).

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

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

567 exponent (C{int}).

568

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

570

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

572

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

574 '''

575 if not isint(n):

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

577 elif n < 1:

578 raise _ValueError(n=n)

579

580 p = x if isint(x) or isinstance(x, Fsum) else _2float(x=x)

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

582

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

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

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

586

587 return ps

588

589

590 try:

591 from math import prod as fprod # Python 3.8

592 except ImportError:

593

594 def fprod(xs, start=1):

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

596

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

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

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

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

601

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

603

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

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

606 '''

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

608

609

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

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

612

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

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

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

616

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

618

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

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

621 '''

622 if not isint(number):

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

624 for i in range(number):

625 yield start + (step * i)

626

627

628 try:

629 from functools import reduce as freduce

630 except ImportError:

631 try:

632 freduce = reduce # PYCHOK expected

633 except NameError: # Python 3+

634

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

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

637 '''

638 if start:

639 r = v = start[0]

640 else:

641 r, v = 0, MISSING

642 for v in xs:

643 r = f(r, v)

644 if v is MISSING:

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

646 return r

647

648

649 def fremainder(x, y):

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

651

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

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

654

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

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

657

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

659

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

661 project/geographiclib/>} and Python 3.7+

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

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

664 '''

665 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and

666 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native

667 # fmod( 0, 360) == 0.0

668 # fmod( 360, 360) == 0.0

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

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

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

672 # however, using the % operator ...

673 # 0 % 360 == 0

674 # 360 % 360 == 0

675 # 360.0 % 360 == 0.0

676 # -0 % 360 == 0

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

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

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

680

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

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

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

684 if _isfinite(x):

685 try:

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

687 except Exception as e:

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

689 else: # handle x INF and NINF as NAN

690 r = NAN

691 return r

692

693

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

695 from math import hypot # OK in Python 3.7-

696

697 def hypot_(*xs):

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

699

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

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

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

703 handled differently.

704

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

706

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

708

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

710

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

712

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

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

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

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

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

718 '''

719 h, x2 = _h_x2(xs)

720 return (h * sqrt(x2)) if x2 else _0_0

721

722 elif _sys_version_info2 < (3, 10):

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

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

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

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

727

728 def hypot(x, y):

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

730

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

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

733

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

735 '''

736 if x:

737 h = sqrt(x**2 + y**2) if y else fabs(x)

738 elif y:

739 h = fabs(y)

740 else:

741 h = _0_0

742 return h

743

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

745 else:

746 from math import hypot # PYCHOK in Python 3.10+

747 hypot_ = hypot

748

749

750 def _h_x2(xs):

751 '''(INTERNAL) Helper for L{hypot_} and L{hypot2_}.

752 '''

753 if xs:

754 n, xs = len2(xs)

755 if n > 0:

756 h = float(max(map(fabs, xs)))

757 if h < EPS0:

758 x2 = _0_0

759 elif h in (_1_0, _N_1_0):

760 x2 = _fsum(_1primed(x**2 for x in xs))

761 else: # math.fsum

762 x2 = _fsum(_1primed((x / h)**2 for x in xs))

763 return h, x2

764

765 raise _ValueError(xs=xs, txt=_too_(_few_))

766

767

768 def hypot1(x):

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

770

771 @arg x: Argument (C{scalar}).

772

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

774 '''

775 return hypot(_1_0, x) if x else _1_0

776

777

778 def hypot2(x, y):

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

780

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

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

783

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

785 '''

786 if x:

787 if y:

788 if fabs(x) < fabs(y):

789 x, y = y, x

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

791 else:

792 h2 = x**2

793 elif y:

794 h2 = y**2

795 else:

796 h2 = _0_0

797 return h2

798

799

800 def hypot2_(*xs):

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

802

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

804

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

806

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

808

809 @raise ValueError: Invalid or no B{C{xs}} value.

810

811 @see: Function L{hypot_}.

812 '''

813 h, x2 = _h_x2(xs)

814 return (h**2 * x2) if x2 else _0_0

815

816

817 def _map_mul(a, b, where):

818 '''(INTERNAL) Yield each B{C{a * b}}.

819 '''

820 n = len(b)

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

822 raise LenError(where, a=len(a), b=n)

823 return map(_operator.mul, a, b) if n > 3 else _1map_mul(a, b)

824

825

826 def _1map_mul(a, b):

827 '''(INTERNAL) Yield each B{C{a * b}}, 1-primed.

828 '''

829 return _1primed(map(_operator.mul, a, b))

830

831

832 def norm2(x, y):

833 '''Normalize a 2-dimensional vector.

834

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

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

837

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

839

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

841 or zero norm.

842 '''

843 h = hypot(x, y)

844 if not h:

845 x = y = _0_0 # pass?

846 elif not isnear1(h):

847 try:

848 x, y = x / h, y / h

849 except Exception as e:

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

851 return x, y

852

853

854 def norm_(*xs):

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

856

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

858

859 @return: Yield each component, normalized.

860

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

862 or zero norm.

863 '''

864 h = hypot_(*xs)

865 if h:

866 try:

867 for i, x in enumerate(xs):

868 yield x / h

869 except Exception as e:

870 raise _xError(e, Fmt.SQUARE(xs=i), x, _h_, h)

871 else:

872 for _ in xs:

873 yield _0_0

874

875

876 def _powers(x, n):

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

878 '''

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

880 for _ in range(n):

881 p *= x

882 yield p

883

884

885 def _root(x, p, where):

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

887 '''

888 if x < 0:

889 t = _SPACE_(_invokation_, where.__name__)

890 raise _ValueError(unstr(t, x), txt=_negative_)

891 return pow(x, p) if x else _0_0

892

893

894 def sqrt0(x, Error=None):

895 '''Return the square root iff C{B{x} >} L{EPS02}.

896

897 @arg x: Value (C{scalar}).

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

899

900 @return: Square root (C{float}) or C{0.0}.

901

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

903 returns C{0.0}.

904 '''

905 if Error and x < 0:

906 raise Error(Fmt.PAREN(sqrt=x))

907 return sqrt(x) if x > EPS02 else (_0_0 if x < EPS02 else EPS0)

908

909

910 def sqrt3(x):

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

912

913 @arg x: Value (C{scalar}).

914

915 @return: Square root I{cubed} (C{float}).

916

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

918

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

920 '''

921 return _root(x, _1_5, sqrt3)

922

923

924 def sqrt_a(h, b):

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

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

927

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

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

930

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

932

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

934

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

936

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

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

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

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

941 '''

942 try:

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

944 raise TypeError(_not_scalar_)

945 c = fabs(h)

946 if c > EPS0:

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

948 if s < 0:

949 raise ValueError(_h_lt_b_)

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

951 else: # PYCHOK no cover

952 b = fabs(b)

953 d = c - b

954 if d < 0:

955 raise ValueError(_h_lt_b_)

956 d *= c + b

957 a = sqrt(d) if d else _0_0

958 except Exception as x:

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

960 return copysign0(a, h)

961

962

963 def zcrt(x):

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

965

966 @arg x: Value (C{scalar}).

967

968 @return: I{Zenzi-cubic} root (C{float}).

969

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

971

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

973 '''

974 return _root(x, _1_6th, zcrt)

975

976

977 def zqrt(x):

978 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root, M{x**(1 / 8)}.

979

980 @arg x: Value (C{scalar}).

981

982 @return: I{Zenzi-quartic} root (C{float}).

983

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

985

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

987 '''

988 return _root(x, _0_125, zqrt)

989

990# **) MIT License

991#

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

993#

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

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

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

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

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

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

1000#

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

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

1003#

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

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

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

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

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

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

1010# OTHER DEALINGS IN THE SOFTWARE.