Coverage for pygeodesy/fmath.py: 89%

316 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-09-11 15:06 -0400

1 

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

3 

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

5''' 

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

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

8 

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

10 len2, map1, _xiterable 

11from 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 

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

15 _xError, _xkwds_get1, _xkwds_pop2 

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

17 Fmt, unstr 

18from pygeodesy.interns import MISSING, _negative_, _not_scalar_ 

19from pygeodesy.lazily import _ALL_LAZY, _sys_version_info2 

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

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

22 

23from math import fabs, sqrt # pow 

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

25 

26__all__ = _ALL_LAZY.fmath 

27__version__ = '24.09.09' 

28 

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

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

31_2_3rd = _1_3rd * 2 

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

33 

34 

35class 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 i=0..len(a)-1)}. 

40 

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

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

43 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) and the C{B{RESIDUAL}=0.0} 

44 threshold (C{scalar}) for raising L{ResidualError}s, see class 

45 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 Fsum.__init__(self, **name_RESIDUAL) 

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

59 

60 

61class Fhorner(Fsum): 

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

63 ''' 

64 def __init__(self, x, *cs, **incx_name_RESIDUAL): 

65 '''New L{Fhorner} evaluation of polynomial M{sum(cs[i] * x**i for i=0..n)} if 

66 C{B{incx}=False} for decreasing exponent M{sum(... i=n..0)} where C{n = 

67 len(cs) - 1}. 

68 

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

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

71 all positional. 

72 @kwarg incx_name_RESIDUAL: Optional C{B{name}=NN} (C{str}), C{B{incx}=True} 

73 for in-/decreasing exponents (C{bool}) and the C{B{RESIDUAL}=0.0} 

74 threshold (C{scalar}) for raising L{ResidualError}s, see class 

75 L{Fsum<Fsum.__init__>}. 

76 

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

78 

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

80 

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

82 

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

84 ''' 

85 incx, name_RESIDUAL = _xkwds_pop2(incx_name_RESIDUAL, incx=True) 

86 Fsum.__init__(self, **name_RESIDUAL) 

87 if cs: 

88 self._fhorner(x, cs, Fhorner.__name__, incx=incx) 

89 else: 

90 self._fset_ps(_0_0) 

91 

92 

93class Fhypot(Fsum): 

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

95 ''' 

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

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

98 to the power I{root}). 

99 

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

101 positional. 

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

103 (C{scalar}), C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0} 

104 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for 

105 raising L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and 

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

107 ''' 

108 r = None # _xkwds_pop2 error 

109 try: 

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

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

112 raiser = _Fsum__init__(self, **kwds) 

113 if xs: 

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

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

116 except Exception as X: 

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

118 

119 

120class Fpolynomial(Fsum): 

121 '''Precision polynomial evaluation. 

122 ''' 

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

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

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

126 

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

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

129 all positional. 

130 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) and the C{B{RESIDUAL}=0.0} 

131 threshold (C{scalar}) for raising L{ResidualError}s, see class 

132 L{Fsum<Fsum.__init__>}. 

133 

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

135 

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

137 

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

139 

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

141 ''' 

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

143 n = len(cs) - 1 

144 if n > 0: 

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

146 elif n < 0: 

147 self._fset_ps(_0_0) 

148 

149 

150class Fpowers(Fsum): 

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

152 ''' 

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

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

155 

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

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

158 positional. 

159 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0} 

160 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for raising 

161 L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and method 

162 L{fpow<Fsum.fpow>}. 

163 ''' 

164 try: 

165 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser) 

166 if xs: 

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

168 except Exception as X: 

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

170 

171 

172class Froot(Fsum): 

173 '''The root of a precision summation. 

174 ''' 

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

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

177 

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

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

180 positional. 

181 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0} 

182 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for raising 

183 L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and method 

184 L{fpow<Fsum.fpow>}. 

185 ''' 

186 try: 

187 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser) 

188 if xs: 

189 self.fadd(xs) 

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

191 except Exception as X: 

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

193 

194 

195class Fcbrt(Froot): 

196 '''Cubic root of a precision summation. 

197 ''' 

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

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

200 

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

202 ''' 

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

204 

205 

206class Fsqrt(Froot): 

207 '''Square root of a precision summation. 

208 ''' 

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

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

211 

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

213 ''' 

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

215 

216 

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

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

219 ''' 

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

221 inst._fset_ps(_0_0) 

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

223 

224 

225def bqrt(x): 

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

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

228 

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

230 

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

232 

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

234 

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

236 

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

238 ''' 

239 return _root(x, _0_25, bqrt) 

240 

241 

242try: 

243 from math import cbrt as _cbrt # Python 3.11+ 

244 

245except ImportError: # Python 3.10- 

246 

247 def _cbrt(x): 

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

249 ''' 

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

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

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

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

254 

255 

256def cbrt(x): 

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

258 

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

260 

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

262 

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

264 ''' 

265 if _isFsumTuple(x): 

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

267 if x.signOf() < 0: 

268 r = -r 

269 else: 

270 r = _cbrt(x) 

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

272 

273 

274def cbrt2(x): # PYCHOK attr 

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

276 

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

278 

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

280 

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

282 ''' 

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

284 

285 

286def euclid(x, y): 

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

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

289 

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

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

292 

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

294 

295 @see: Function L{euclid_}. 

296 ''' 

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

298 if y > x: 

299 x, y = y, x 

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

301 

302 

303def euclid_(*xs): 

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

305 L{euclid}. 

306 

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

308 all positional. 

309 

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

311 

312 @see: Function L{euclid}. 

313 ''' 

314 e = _0_0 

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

316 # e = euclid(x, e) 

317 if e < x: 

318 e, x = x, e 

319 if x: 

320 e += x * _0_4142 

321 return e 

322 

323 

324def facos1(x): 

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

326 

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

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

329 ''' 

330 a = fabs(x) 

331 if a < EPS0: 

332 r = PI_2 

333 elif a < EPS1: 

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

335 H *= Fsqrt(_1_0, -a) 

336 r = float(H) 

337 if x < 0: 

338 r = PI - r 

339 else: 

340 r = PI if x < 0 else _0_0 

341 return r 

342 

343 

344def fasin1(x): # PYCHOK no cover 

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

346 

347 @see: L{facos1}. 

348 ''' 

349 return PI_2 - facos1(x) 

350 

351 

352def fatan(x): 

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

354 ''' 

355 a = fabs(x) 

356 if a < _1_0: 

357 r = fatan1(a) if a else _0_0 

358 elif a > _1_0: 

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

360 else: 

361 r = PI_4 

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

363 r = -r 

364 return r 

365 

366 

367def fatan1(x): 

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

369 

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

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

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

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

374 IEEE Signal Processing Magazine, 111, May 2006. 

375 ''' 

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

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

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

379 H = Fhorner(x, _0_0, 1.0300981634, -0.1784, -0.0663) 

380 return float(H) 

381 

382 

383def fatan2(y, x): 

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

385 

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

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

388 and L{fatan1}. 

389 ''' 

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

391 if b > a: 

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

393 elif a > b: 

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

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

396 r = PI_4 

397 else: # a == b == 0 

398 return _0_0 

399 if x < 0: 

400 r = PI - r 

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

402 r = -r 

403 return r 

404 

405 

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

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

408 

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

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

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

412 

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

414 ''' 

415# @raise ValueError: Fraction out of range. 

416# ''' 

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

418# raise _ValueError(fraction=f) 

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

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

421 

422 

423def fdot(a, *b): 

424 '''Return the precision dot product M{sum(a[i] * b[i] for ni=0..len(a))}. 

425 

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

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

428 positional. 

429 

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

431 

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

433 

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

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

436 ''' 

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

438 

439 

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

441 '''Return the precision dot product M{start + sum(a[i] * b[i] * c[i] 

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

443 

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

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

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

447 @kwarg start: Optional bias (C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

448 

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

450 

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

452 

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

454 ''' 

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

456 if s: 

457 yield s 

458 if p: 

459 yield _1_0 

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

461 yield (Fsum(x) * y) * z 

462 if p: 

463 yield _N_1_0 

464 

465 n = len(xs) 

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

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

468 

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

470 

471 

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

473 '''Evaluate a polynomial using the Horner form M{sum(cs[i] * x**i 

474 for i=0..n)} or if C{B{incx}=False} for decreasing exponent 

475 M{sum(... i=n..0)} where C{n = len(cs) - 1}. 

476 

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

478 

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

480 ''' 

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

482 return float(H) 

483 

484 

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

486 '''Interpolate using U{Inverse Distance Weighting 

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

488 

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

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

491 L{Fsum2Tuple}). 

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

493 

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

495 

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

497 

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

499 

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

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

502 

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

504 ''' 

505 n, xs = len2(xs) 

506 if n > 1: 

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

508 if b < 0: 

509 try: # weighted 

510 _F = Fsum 

511 W = _F() 

512 X = _F() 

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

514 x = xs[i] 

515 D = _F(d) 

516 if D < EPS0: 

517 if D < 0: 

518 raise ValueError(_negative_) 

519 x = float(x) 

520 i = n 

521 break 

522 if D.fpow(b): 

523 W += D 

524 X += D.fmul(x) 

525 else: 

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

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

528 except IndexError: 

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

530 except Exception as X: 

531 _I = Fmt.INDEX 

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

533 else: # b == 0 

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

535 i = n 

536 elif n: 

537 x = float(xs[0]) 

538 i = n 

539 else: 

540 x = _0_0 

541 i, _ = len2(ds) 

542 if i != n: 

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

544 return x 

545 

546 

547def fma(x, y, z): 

548 '''Fused-multiply-add, as C{math.fma(x, y, z)} from Python 3.13+. 

549 

550 @arg x: A C{scalar}, an L{Fsum} or L{Fsum2Tuple} instance. 

551 @arg y: A C{scalar}, an L{Fsum} or L{Fsum2Tuple} instance. 

552 @arg z: A C{scalar}, an L{Fsum} or L{Fsum2Tuple} instance. 

553 

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

555 ''' 

556 return Fsum(x).fma(y, z).as_iscalar 

557 

558 

559def fmean(xs): 

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

561 

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

563 

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

565 

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

567 

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

569 ''' 

570 n, xs = len2(xs) 

571 if n < 1: 

572 raise LenError(fmean, xs=xs) 

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

574 

575 

576def fmean_(*xs): 

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

578 

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

580 ''' 

581 return fmean(xs) 

582 

583 

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

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

586 [/ over]}. 

587 

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

589 

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

591 

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

593 ''' 

594 P = Fpolynomial(x, *cs) 

595 d = _xkwds_get1(over, over=0) if over else 0 

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

597 

598 

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

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

601 

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

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

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

605 exponent (C{int}). 

606 

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

608 

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

610 

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

612 ''' 

613 if not isint(n): 

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

615 elif n < 1: 

616 raise _ValueError(n=n) 

617 

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

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

620 

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

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

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

624 

625 return ps 

626 

627 

628try: 

629 from math import prod as fprod # Python 3.8 

630except ImportError: 

631 

632 def fprod(xs, start=1): 

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

634 

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

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

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

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

639 

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

641 

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

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

644 ''' 

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

646 

647 

648def frandoms(n, seeded=None): 

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

650 

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

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

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

654 

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

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

657 ''' 

658 from random import gauss, random, seed, shuffle 

659 

660 if seeded is None: 

661 pass 

662 elif seeded and isbool(seeded): 

663 from time import localtime 

664 seed(localtime().tm_yday) 

665 elif isscalar(seeded): 

666 seed(seeded) 

667 

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

669 for _ in range(n): 

670 s = 0 

671 t = list(c) 

672 _a = t.append 

673 for _ in range(n * 8): 

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

675 _a(v) 

676 s += v 

677 shuffle(t) 

678 yield t 

679 

680 

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

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

683 

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

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

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

687 

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

689 

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

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

692 ''' 

693 if not isint(number): 

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

695 for i in range(number): 

696 yield start + (step * i) 

697 

698 

699try: 

700 from functools import reduce as freduce 

701except ImportError: 

702 try: 

703 freduce = reduce # PYCHOK expected 

704 except NameError: # Python 3+ 

705 

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

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

708 ''' 

709 if start: 

710 r = v = start[0] 

711 else: 

712 r, v = 0, MISSING 

713 for v in xs: 

714 r = f(r, v) 

715 if v is MISSING: 

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

717 return r 

718 

719 

720def fremainder(x, y): 

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

722 

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

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

725 

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

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

728 

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

730 

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

732 project/geographiclib/>} and Python 3.7+ 

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

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

735 ''' 

736 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and 

737 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native 

738 # fmod( 0, 360) == 0.0 

739 # fmod( 360, 360) == 0.0 

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

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

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

743 # however, using the % operator ... 

744 # 0 % 360 == 0 

745 # 360 % 360 == 0 

746 # 360.0 % 360 == 0.0 

747 # -0 % 360 == 0 

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

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

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

751 

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

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

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

755 if _isfinite(x): 

756 try: 

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

758 except Exception as e: 

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

760 else: # handle x INF and NINF as NAN 

761 r = NAN 

762 return r 

763 

764 

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

766 from math import hypot # OK in Python 3.7- 

767 

768 def hypot_(*xs): 

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

770 

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

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

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

774 handled differently. 

775 

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

777 

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

779 

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

781 

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

783 

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

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

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

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

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

789 ''' 

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

791 

792elif _sys_version_info2 < (3, 10): 

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

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

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

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

797 

798 def hypot(x, y): 

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

800 

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

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

803 

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

805 ''' 

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

807 

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

809else: 

810 from math import hypot # PYCHOK in Python 3.10+ 

811 hypot_ = hypot 

812 

813 

814def hypot1(x): 

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

816 

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

818 

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

820 ''' 

821 if _isFsumTuple(x): 

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

823 else: 

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

825 return h 

826 

827 

828def hypot2(x, y): 

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

830 

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

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

833 

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

835 ''' 

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

837 if y > x: 

838 x, y = y, x 

839 if x: 

840 h2 = x**2 

841 if y: 

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

843 h2 = float(h2) 

844 else: 

845 h2 = _0_0 

846 return h2 

847 

848 

849def hypot2_(*xs): 

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

851 

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

853 L{Fsum2Tuple}), all positional. 

854 

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

856 

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

858 ''' 

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

860 if h2: 

861 _h = _1_0 / h2 

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

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

864 return h2 

865 

866 

867def _map_mul(xs, ys, where): 

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

869 ''' 

870 n = len(ys) 

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

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

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

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

875 

876 

877def _1map_mul(xs, ys): 

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

879 ''' 

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

881 

882 

883def norm2(x, y): 

884 '''Normalize a 2-dimensional vector. 

885 

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

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

888 

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

890 

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

892 or zero norm. 

893 ''' 

894 try: 

895 h = None 

896 h = hypot(x, y) 

897 if h: 

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

899 else: 

900 x = _copysign_0_0(x) # pass? 

901 y = _copysign_0_0(y) 

902 except Exception as e: 

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

904 return x, y 

905 

906 

907def norm_(*xs): 

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

909 

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

911 L{Fsum2Tuple}), all positional. 

912 

913 @return: Yield each component, normalized. 

914 

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

916 or zero norm. 

917 ''' 

918 try: 

919 i = x = h = None 

920 h = hypot_(*xs) 

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

922 for i, x in enumerate(xs): 

923 yield x * _h 

924 except Exception as X: 

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

926 

927 

928def _powers(x, n): 

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

930 ''' 

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

932 for _ in range(n): 

933 p *= x 

934 yield p 

935 

936 

937def _root(x, p, where): 

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

939 ''' 

940 try: 

941 if x > 0: 

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

943 elif x < 0: 

944 raise ValueError(_negative_) 

945 except Exception as X: 

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

947 return _0_0 

948 

949 

950def sqrt0(x, Error=None): 

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

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

953 

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

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

956 

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

958 

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

960 

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

962 returns C{0.0}. 

963 ''' 

964 if Error and x < 0: 

965 raise Error(unstr(sqrt0, x)) 

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

967 _0_0 if x < EPS02 else EPS0) 

968 

969 

970def sqrt3(x): 

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

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

973 

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

975 

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

977 

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

979 

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

981 

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

983 ''' 

984 return _root(x, _1_5, sqrt3) 

985 

986 

987def sqrt_a(h, b): 

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

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

990 

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

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

993 

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

995 

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

997 

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

999 

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

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

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

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

1004 ''' 

1005 try: 

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

1007 raise TypeError(_not_scalar_) 

1008 c = fabs(h) 

1009 if c > EPS0: 

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

1011 if s < 0: 

1012 raise ValueError(_h_lt_b_) 

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

1014 else: # PYCHOK no cover 

1015 b = fabs(b) 

1016 d = c - b 

1017 if d < 0: 

1018 raise ValueError(_h_lt_b_) 

1019 d *= c + b 

1020 a = sqrt(d) if d else _0_0 

1021 except Exception as x: 

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

1023 return copysign0(a, h) 

1024 

1025 

1026def zcrt(x): 

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

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

1029 

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

1031 

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

1033 

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

1035 

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

1037 

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

1039 ''' 

1040 return _root(x, _1_6th, zcrt) 

1041 

1042 

1043def zqrt(x): 

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

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

1046 

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

1048 

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

1050 

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

1052 

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

1054 

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

1056 ''' 

1057 return _root(x, _0_125, zqrt) 

1058 

1059# **) MIT License 

1060# 

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

1062# 

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

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

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

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

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

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

1069# 

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

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

1072# 

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

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

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

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

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

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

1079# OTHER DEALINGS IN THE SOFTWARE.