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

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 def _r_X_kwds(power=None, raiser=True, root=2, **kwds):

111 # DEPRECATED keyword argument C{power=2}, use C{root=2}

112 return (root if power is None else power), raiser, kwds

113

114 r = None # _xkwds_pop2 error

115 try:

116 r, X, kwds = _r_X_kwds(**root_name_f2product_nonfinites_RESIDUAL_raiser)

117 Fsum.__init__(self, **kwds)

118 self(_0_0)

119 if xs:

120 self._facc_power(r, xs, Fhypot, raiser=X)

121 self._fset(self.root(r, raiser=X))

122 except Exception as X:

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

124

125

126 class Fpolynomial(Fsum):

127 '''Precision polynomial evaluation.

128 '''

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

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

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

132

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

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

135 all positional.

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

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

138

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

140

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

142

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

144

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

146 '''

147 Fsum.__init__(self, **name_f2product_nonfinites_RESIDUAL)

148 n = len(cs) - 1

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

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

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_f2product_nonfinites_RESIDUAL_raiser):

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

158

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

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

161 positional.

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

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

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

165 L{fpow<Fsum.fpow>}.

166 '''

167 try:

168 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)

169 Fsum.__init__(self, **kwds)

170 self(_0_0)

171 if xs:

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

173 except Exception as X:

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

175

176

177 class Froot(Fsum):

178 '''The root of a precision summation.

179 '''

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

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

182

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

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

185 positional.

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

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

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

189 L{fpow<Fsum.fpow>}.

190 '''

191 try:

192 X, kwds = _xkwds_pop2(name_f2product_nonfinites_RESIDUAL_raiser, raiser=True)

193 Fsum.__init__(self, **kwds)

194 self(_0_0)

195 if xs:

196 self.fadd(xs)

197 self(self.root(root, raiser=X))

198 except Exception as X:

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

200

201

202 class Fcbrt(Froot):

203 '''Cubic root of a precision summation.

204 '''

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

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

207

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

209 '''

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

211

212

213 class Fsqrt(Froot):

214 '''Square root of a precision summation.

215 '''

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

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

218

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

220 '''

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

222

223

224 def bqrt(x):

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

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

227

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

229

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

231

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

233

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

235

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

237 '''

238 return _root(x, _0_25, bqrt)

239

240

241 try:

242 from math import cbrt as _cbrt # Python 3.11+

243

244 except ImportError: # Python 3.10-

245

246 def _cbrt(x):

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

248 '''

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

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

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

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

253

254

255 def cbrt(x):

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

257

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

259

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

261

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

263 '''

264 if _isFsum_2Tuple(x):

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

266 if x.signOf() < 0:

267 r = -r

268 else:

269 r = _cbrt(x)

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

271

272

273 def cbrt2(x): # PYCHOK attr

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

275

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

277

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

279

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

281 '''

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

283

284

285 def euclid(x, y):

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

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

288

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

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

291

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

293

294 @see: Function L{euclid_}.

295 '''

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

297 if y > x:

298 x, y = y, x

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

300

301

302 def euclid_(*xs):

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

304 L{euclid}.

305

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

307 all positional.

308

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

310

311 @see: Function L{euclid}.

312 '''

313 e = _0_0

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

315 # e = euclid(x, e)

316 if e < x:

317 e, x = x, e

318 if x:

319 e += x * _0_4142

320 return e

321

322

323 def facos1(x):

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

325

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

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

328 '''

329 a = fabs(x)

330 if a < EPS0:

331 r = PI_2

332 elif a < EPS1:

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

334 r *= sqrt(_1_0 - a)

335 if x < 0:

336 r = PI - r

337 else:

338 r = PI if x < 0 else _0_0

339 return r

340

341

342 def fasin1(x): # PYCHOK no cover

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

344

345 @see: L{facos1}.

346 '''

347 return PI_2 - facos1(x)

348

349

350 def _fast(x, *cs):

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

352 '''

353 h = 0

354 for c in reversed(cs):

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

356 return h

357

358

359 def fatan(x):

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

361 '''

362 a = fabs(x)

363 if a < _1_0:

364 r = fatan1(a) if a else _0_0

365 elif a > _1_0:

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

367 else:

368 r = PI_4

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

370 r = -r

371 return r

372

373

374 def fatan1(x):

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

376

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

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

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

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

381 IEEE Signal Processing Magazine, 111, May 2006.

382 '''

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

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

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

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

387

388

389 def fatan2(y, x):

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

391

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

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

394 and L{fatan1}.

395 '''

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

397 if b > a:

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

399 elif a > b:

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

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

402 r = PI_4

403 else: # a == b == 0

404 return _0_0

405 if x < 0:

406 r = PI - r

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

408 r = -r

409 return r

410

411

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

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

414

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

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

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

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

419

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

421 '''

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

423 return float(F)

424

425

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

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

428

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

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

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

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

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

434

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

436

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

438

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

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

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

442 '''

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

444 return float(D)

445

446

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

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

449

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

451

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

453

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

455 '''

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

457

458

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

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

461

462 @arg xs: X values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

463 @arg ys: Y values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

464 @arg zs: Z values iterable (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}).

465

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

467

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

469

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

471 '''

472 n = len(xs)

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

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

475

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

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

478 _f = Fsum(**kwds)

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

480 return float(D)

481

482

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

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

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

486

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

488

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

490 '''

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

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}, an L{Fsum} or L{Fsum2Tuple}).

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

501 L{Fsum2Tuple}).

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

503

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

505

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

507

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

509

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

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

512

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

514 '''

515 n, xs = len2(xs)

516 if n > 1:

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

518 if b < 0:

519 try: # weighted

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

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

522 x = xs[i]

523 D = _d(d)

524 if D < EPS0:

525 if D < 0:

526 raise ValueError(_negative_)

527 x = float(x)

528 i = n

529 break

530 if D.fpow(b):

531 W += D

532 X += D.fmul(x)

533 else:

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

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

536 except IndexError:

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

538 except Exception as X:

539 _I = Fmt.INDEX

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

541 _I(ds=i), d)

542 else: # b == 0

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

544 i = n

545 elif n:

546 x = float(xs[0])

547 i = n

548 else:

549 x = _0_0

550 i, _ = len2(ds)

551 if i != n:

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

553 return x

554

555

556 try:

557 from math import fma as _fma

558 except ImportError: # PYCHOK DSPACE!

559

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

561 return x * y + z

562

563

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

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

566 or an equivalent implementation.

567

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

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

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

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

572 to override default L{nonfiniterrors}

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

574

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

576 '''

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

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

579

580

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

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

583 '''

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

585

586

587 def fmean(xs):

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

589

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

591

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

593

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

595

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

597 '''

598 n, xs = len2(xs)

599 if n < 1:

600 raise LenError(fmean, xs=xs)

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

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

603

604

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

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

607

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

609 '''

610 return fmean(xs, **nonfinites)

611

612

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

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

615

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

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

618 positional.

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

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

621

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

623

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

625 '''

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

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

628

629

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

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

632

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

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

635 L{Fpolynomial<Fpolynomial.__init__>}.

636

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

638 '''

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

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

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

642

643

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

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

646

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

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

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

650 exponent (C{int}).

651

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

653

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

655

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

657 '''

658 if not isint(n):

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

660 elif n < 1:

661 raise _ValueError(n=n)

662

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

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

665

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

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

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

669

670 return ps

671

672

673 try:

674 from math import prod as fprod # Python 3.8

675 except ImportError:

676

677 def fprod(xs, start=1):

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

679

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

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

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

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

684

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

686

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

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

689 '''

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

691

692

693 def frandoms(n, seeded=None):

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

695

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

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

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

699

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

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

702 '''

703 from random import gauss, random, seed, shuffle

704

705 if seeded is None:

706 pass

707 elif seeded and isbool(seeded):

708 from time import localtime

709 seed(localtime().tm_yday)

710 elif isscalar(seeded):

711 seed(seeded)

712

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

714 for _ in range(n):

715 s = 0

716 t = list(c)

717 _a = t.append

718 for _ in range(n * 8):

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

720 _a(v)

721 s += v

722 shuffle(t)

723 yield t

724

725

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

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

728

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

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

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

732

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

734

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

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

737 '''

738 if not isint(number):

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

740 for i in range(number):

741 yield start + (step * i)

742

743

744 try:

745 from functools import reduce as freduce

746 except ImportError:

747 try:

748 freduce = reduce # PYCHOK expected

749 except NameError: # Python 3+

750

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

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

753 '''

754 if start:

755 r = v = start[0]

756 else:

757 r, v = 0, MISSING

758 for v in xs:

759 r = f(r, v)

760 if v is MISSING:

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

762 return r

763

764

765 def fremainder(x, y):

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

767

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

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

770

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

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

773

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

775

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

777 project/geographiclib/>} and Python 3.7+

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

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

780 '''

781 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and

782 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native

783 # fmod( 0, 360) == 0.0

784 # fmod( 360, 360) == 0.0

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

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

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

788 # however, using the % operator ...

789 # 0 % 360 == 0

790 # 360 % 360 == 0

791 # 360.0 % 360 == 0.0

792 # -0 % 360 == 0

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

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

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

796

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

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

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

800 if isfinite(x):

801 try:

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

803 except Exception as e:

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

805 else: # handle x INF and NINF as NAN

806 r = NAN

807 return r

808

809

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

811 from math import hypot # OK in Python 3.7-

812

813 def hypot_(*xs):

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

815

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

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

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

819 handled differently.

820

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

822

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

824

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

826

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

828

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

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

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

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

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

834 '''

835 return float(_Hypot(*xs))

836

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

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

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

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

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

842

843 def hypot(x, y):

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

845

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

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

848

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

850 '''

851 return float(_Hypot(x, y))

852

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

854 else:

855 from math import hypot # PYCHOK in Python 3.10+

856 hypot_ = hypot

857

858

859 def _Hypot(*xs):

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

861 '''

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

863

864

865 def hypot1(x):

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

867

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

869

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

871 '''

872 h = _1_0

873 if x:

874 if _isFsum_2Tuple(x):

875 h = _Hypot(h, x)

876 h = float(h)

877 else:

878 h = hypot(h, x)

879 return h

880

881

882 def hypot2(x, y):

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

884

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

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

887

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

889 '''

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

891 if y > x:

892 x, y = y, x

893 h2 = x**2

894 if h2 and y:

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

896 return float(h2)

897

898

899 def hypot2_(*xs):

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

901

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

903 L{Fsum2Tuple}), all positional.

904

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

906

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

908 '''

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

910 if h2: # and isfinite(h2)

911 _h = _1_0 / h2

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

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

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

915 return h2

916

917

918 def norm2(x, y):

919 '''Normalize a 2-dimensional vector.

920

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

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

923

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

925

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

927 or zero norm.

928 '''

929 try:

930 h = None

931 h = hypot(x, y)

932 if h:

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

934 else:

935 x = _copysign_0_0(x) # pass?

936 y = _copysign_0_0(y)

937 except Exception as e:

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

939 return x, y

940

941

942 def norm_(*xs):

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

944

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

946 L{Fsum2Tuple}), all positional.

947

948 @return: Yield each component, normalized.

949

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

951 or zero norm.

952 '''

953 try:

954 i = h = None

955 x = xs

956 h = hypot_(*xs)

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

958 for i, x in enumerate(xs):

959 yield x * _h

960 except Exception as X:

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

962

963

964 def _powers(x, n):

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

966 '''

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

968 for _ in range(n):

969 p *= x

970 yield p

971

972

973 def _root(x, p, where):

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

975 '''

976 try:

977 if x > 0:

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

979 return r.fpow(p).as_iscalar

980 elif x < 0:

981 raise ValueError(_negative_)

982 except Exception as X:

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

984 return _0_0

985

986

987 def sqrt0(x, Error=None):

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

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

990

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

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

993

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

995

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

997

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

999 returns C{0.0}.

1000 '''

1001 if Error and x < 0:

1002 raise Error(unstr(sqrt0, x))

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

1004 _0_0 if x < EPS02 else EPS0)

1005

1006

1007 def sqrt3(x):

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

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

1010

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

1012

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

1014

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

1016

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

1018

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

1020 '''

1021 return _root(x, _1_5, sqrt3)

1022

1023

1024 def sqrt_a(h, b):

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

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

1027

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

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

1030

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

1032

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

1034

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

1036

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

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

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

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

1041 '''

1042 try:

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

1044 raise TypeError(_not_scalar_)

1045 c = fabs(h)

1046 if c > EPS0:

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

1048 if s < 0:

1049 raise ValueError(_h_lt_b_)

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

1051 else: # PYCHOK no cover

1052 b = fabs(b)

1053 d = c - b

1054 if d < 0:

1055 raise ValueError(_h_lt_b_)

1056 d *= c + b

1057 a = sqrt(d) if d else _0_0

1058 except Exception as x:

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

1060 return copysign0(a, h)

1061

1062

1063 def zcrt(x):

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

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

1066

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

1068

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

1070

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

1072

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

1074

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

1076 '''

1077 return _root(x, _1_6th, zcrt)

1078

1079

1080 def zqrt(x):

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

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

1083

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

1085

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

1087

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

1089

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

1091

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

1093 '''

1094 return _root(x, _0_125, zqrt)

1095

1096# **) MIT License

1097#

1098# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.

1099#

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

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

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

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

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

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

1106#

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

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

1109#

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

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

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

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

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

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

1116# OTHER DEALINGS IN THE SOFTWARE.