Coverage for pygeodesy/fmath.py: 88%

371 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-10 16:16 -0500

1 

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

3 

4u'''Utilities for precision floating point summation, multiplication, 

5C{fused-multiply-add}, polynomials, roots, etc. 

6''' 

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

8from __future__ import division as _; del _ # noqa: E702 ; 

9 

10from pygeodesy.basics import _copysign, copysign0, isbool, iscomplex, \ 

11 _xiterable, isint, isodd, isscalar, len2, \ 

12 _zip, typename 

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

14 _0_0, _0_125, _0_25, _1_3rd, _0_5, _2_3rd, \ 

15 _1_0, _1_5, _copysign_0_0, isfinite, remainder 

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

17 _xError, _xkwds, _xkwds_get, _xkwds_pop2, _xsError 

18from pygeodesy.fsums import _2float, Fsum, fsum, _isFsum_2Tuple 

19# from pygeodesy.internals import typename # from .basics 

20from pygeodesy.interns import MISSING, _negative_, _not_scalar_ 

21from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS 

22from pygeodesy.streprs import Fmt, unstr 

23from pygeodesy.units import Int_, _isHeight, _isRadius 

24# from utily import atan2b, atan2p # _MODS, circular import! 

25 

26try: 

27 from math import trunc as _truncate 

28except ImportError: # Python 3.11- 

29 _truncate = int 

30from math import fabs, sqrt # pow 

31import operator as _operator # in .datums, .elliptic, .trf, .utm 

32 

33__all__ = _ALL_LAZY.fmath 

34__version__ = '26.11.06' 

35 

36# 1.4142135623730950_48801688724209 <https://WikiPedia.org/wiki/Square_root_of_2> 

37# math.sqrt(2) - 1 == 0.4142135623730950_3 == 3730904090310553 / 9007199254740992 

38_0_4142 = 0.4142135623730950488 

39_1_6th = _1_0 / 6 

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

41 

42 

43class Fdot(Fsum): 

44 '''Precision dot product. 

45 ''' 

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

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

48 

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

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

51 positional. 

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

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

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

55 

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

57 

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

59 

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

61 

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

63 

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

65 ''' 

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

67 Fsum.__init__(self, **kwds) 

68 self(s) 

69 

70 n = len(b) 

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

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

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

74 

75 

76class Fdot_(Fdot): # in .elliptic 

77 '''Precision dot product. 

78 ''' 

79 def __init__(self, *xys, **start_name_f2product_nonfinites_RESIDUAL): 

80 '''New L{Fdot_} precision dot product M{start + sum(xys[i] * xys[i+1] for i in 

81 range(0, len(xys), B{2}))}. 

82 

83 @arg xys: Pairwise values (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}), 

84 all positional. 

85 

86 @see: Class L{Fdot<Fdot.__init__>} for further details. 

87 ''' 

88 if isodd(len(xys)): 

89 raise LenError(Fdot_, xys=len(xys)) 

90 Fdot.__init__(self, xys[0::2], *xys[1::2], **start_name_f2product_nonfinites_RESIDUAL) 

91 

92 

93class Fhorner(Fsum): 

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

95 ''' 

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

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

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

99 

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

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

102 all positional. 

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

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

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

106 

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

108 

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

110 

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

112 

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

114 ''' 

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

116 Fsum.__init__(self, **kwds) 

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

118 

119 

120class Fhypot(Fsum): 

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

122 ''' 

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

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

125 to the power I{root}). 

126 

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

128 positional. 

129 @kwarg root_name_f2product_nonfinites_RESIDUAL_raiser: Optional, exponent 

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

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

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

133 L{root<Fsum.root>}. 

134 ''' 

135 def _r_X_kwds(power=None, raiser=True, root=2, **kwds): 

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

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

138 

139 r = None # _xkwds_pop2 error 

140 try: 

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

142 Fsum.__init__(self, **kwds) 

143 self(_0_0) 

144 if xs: 

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

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

147 except Exception as X: 

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

149 

150 

151class Fpolynomial(Fsum): 

152 '''Precision polynomial evaluation. 

153 ''' 

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

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

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

157 

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

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

160 all positional. 

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

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

163 

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

165 

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

167 

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

169 

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

171 ''' 

172 Fsum.__init__(self, **name_f2product_nonfinites_RESIDUAL) 

173 n = len(cs) - 1 

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

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

176 

177 

178class Fpowers(Fsum): 

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

180 ''' 

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

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

183 

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

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

186 positional. 

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

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

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

190 L{fpow<Fsum.fpow>}. 

191 ''' 

192 try: 

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

194 Fsum.__init__(self, **kwds) 

195 self(_0_0) 

196 if xs: 

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

198 except Exception as X: 

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

200 

201 

202class Froot(Fsum): 

203 '''The root of a precision summation. 

204 ''' 

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

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

207 

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

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

210 positional. 

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

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

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

214 L{fpow<Fsum.fpow>}. 

215 ''' 

216 try: 

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

218 Fsum.__init__(self, **kwds) 

219 self(_0_0) 

220 if xs: 

221 self.fadd(xs) 

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

223 except Exception as X: 

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

225 

226 

227class Fcbrt(Froot): 

228 '''Cubic root of a precision summation. 

229 ''' 

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

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

232 

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

234 ''' 

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

236 

237 

238class Fsqrt(Froot): 

239 '''Square root of a precision summation. 

240 ''' 

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

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

243 

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

245 ''' 

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

247 

248 

249def bqrt(x): 

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

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

252 

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

254 

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

256 

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

258 

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

260 

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

262 ''' 

263 return _root(x, _0_25, bqrt) 

264 

265 

266try: 

267 from math import cbrt as _cbrt # Python 3.11+ 

268except ImportError: # Python 3.10- 

269 

270 def _cbrt(x): 

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

272 ''' 

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

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

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

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

277 

278 

279def cbrt(x): 

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

281 

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

283 

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

285 

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

287 ''' 

288 if _isFsum_2Tuple(x): 

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

290 if x.signOf() < 0: 

291 r = -r 

292 else: 

293 r = _cbrt(x) 

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

295 

296 

297def cbrt2(x): # PYCHOK attr 

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

299 

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

301 

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

303 

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

305 ''' 

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

307 

308 

309def euclid(x, y, *x0_y0, **half): 

310 '''I{Appoximate} the norm M{hypot(B{x}, B{y})} by M{max(abs(B{x}), 

311 abs(B{y})) + min(abs(B{x}), abs(B{y})) * 0.4142...}. 

312 

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

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

315 @arg x0_y0: Optional reference C{(x0, y0)} (each C{scalar}, an 

316 L{Fsum} or L{Fsum2Tuple}). 

317 @kwarg half: Use C{B{half}=True} to apply C{0.5} instead of 

318 C{sqrt(2) - 1} (C{bool}). 

319 

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

321 ''' 

322 x, y = _map0(abs, x, y, *x0_y0) # NOT fabs! 

323 if x < y: 

324 x, y = y, x 

325 y *= _half(**half) if half else _0_4142 # _0_5 before 20.10.02 

326 return x + y 

327 

328 

329def euclid_(*xs, **half): 

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

331 L{euclid}. 

332 

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

334 all positional. 

335 @kwarg half: Use C{B{half}=True} to apply C{0.5} instead of 

336 C{sqrt(2) - 1} (C{bool}). 

337 

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

339 

340 @see: Function L{euclid}. 

341 ''' 

342 e = _0_0 

343 f = _half(**half) 

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

345 # e = euclid(x, e) 

346 if x: 

347 if e < x: 

348 e, x = x, e 

349 x *= f 

350# s = e + x 

351# if e < x: # like .fsums._2sum 

352# x -= s # e = (x - s) + e 

353# else: 

354# e -= s # e = (e - s) + x 

355 e += x 

356# e += s 

357 return e 

358 

359 

360def facos1(x): 

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

362 

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

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

365 ''' 

366 a = fabs(x) 

367 if a < EPS0: 

368 r = PI_2 

369 elif a < EPS1: 

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

371 r *= sqrt(_1_0 - a) 

372 if x < 0: 

373 r = PI - r 

374 else: 

375 r = PI if x < 0 else _0_0 

376 return r 

377 

378 

379def fasin1(x): # PYCHOK no cover 

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

381 

382 @see: L{facos1}. 

383 ''' 

384 return PI_2 - facos1(x) 

385 

386 

387def _fast(x, *cs): 

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

389 ''' 

390 h = 0 

391 for c in reversed(cs): 

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

393 return h 

394 

395 

396def fatan(x): 

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

398 ''' 

399 a = fabs(x) 

400 if a < _1_0: 

401 r = fatan1(a) if a else _0_0 

402 elif a > _1_0: 

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

404 else: 

405 r = PI_4 

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

407 r = -r 

408 return r 

409 

410 

411def fatan1(x): 

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

413 

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

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

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

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

418 IEEE Signal Processing Magazine, 111, May 2006. 

419 ''' 

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

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

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

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

424 

425 

426def fatan2(y, x): 

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

428 

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

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

431 and L{fatan1}. 

432 ''' 

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

434 if b > a: 

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

436 elif a > b: 

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

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

439 r = PI_4 

440 else: # a == b == 0 

441 return _0_0 

442 if x < 0: 

443 r = PI - r 

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

445 r = -r 

446 return r 

447 

448 

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

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

451 

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

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

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

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

456 

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

458 ''' 

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

460 return float(F) 

461 

462 

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

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

465 

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

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

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

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

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

471 

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

473 

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

475 

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

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

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

479 ''' 

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

481 return float(D) 

482 

483 

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

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

486 

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

488 

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

490 

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

492 ''' 

493 D = Fdot_(*xys, **_xkwds(start_f2product_nonfinites, nonfinites=True)) 

494 return float(D) 

495 

496 

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

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

499 

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

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

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

503 

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

505 

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

507 

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

509 ''' 

510 n = len(xs) 

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

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

513 

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

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

516 _f = Fsum(**kwds) 

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

518 return float(D) 

519 

520 

521if _zip is zip: # Python 3.9- 

522 _fdotf = fdot 

523else: 

524 from pygeodesy.fsums import _fsum # math.fsum 

525 

526 def _fdotf(xs, *ys): # in .datums, .ecef 

527 '''(INTERNAL) Dot product for C{float} tuples of matching C{len}gths. 

528 ''' 

529 return _fsum(x * y for x, y in _zip(xs, ys)) # strict=True 

530 

531 

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

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

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

535 

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

537 

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

539 ''' 

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

541 return float(H) 

542 

543 

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

545 '''Interpolate using U{Inverse Distance Weighting 

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

547 

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

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

550 L{Fsum2Tuple}). 

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

552 

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

554 

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

556 

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

558 

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

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

561 

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

563 ''' 

564 n, xs = len2(xs) 

565 if n > 1: 

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

567 if b < 0: 

568 try: # weighted 

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

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

571 x = xs[i] 

572 D = _d(d) 

573 if D < EPS0: 

574 if D < 0: 

575 raise ValueError(_negative_) 

576 x = float(x) 

577 i = n 

578 break 

579 if D.fpow(b): 

580 W += D 

581 X += D.fmul(x) 

582 else: 

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

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

585 except IndexError: 

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

587 except Exception as X: 

588 _I = Fmt.INDEX 

589 raise _xError(X, _I(xs=i), x, # PYLINT E1120 

590 _I(ds=i), d) # PYLINT E1120 

591 else: # b == 0 

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

593 i = n 

594 elif n: 

595 x = float(xs[0]) 

596 i = n 

597 else: 

598 x = _0_0 

599 i, _ = len2(ds) 

600 if i != n: 

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

602 return x 

603 

604 

605try: 

606 from math import fma as _fma # in .resections 

607 

608 def _fhornerf(x, *cs, **incx): 

609 '''(INTERNAL) Horner form for C{float} coefficients C{cs} and C{x} 

610 and C{B{incx}=True} in- or decreasing with exponents=. 

611 ''' 

612 h = _0_0 

613 if cs: 

614 if _xkwds_get(incx, incx=True): 

615 cs = reversed(cs) 

616 for c in cs: 

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

618 return h 

619 

620except ImportError: # PYCHOK DSPACE! 

621 _fhornerf = fhorner # PYCHOK redef 

622 

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

624 return x * y + z 

625 

626 

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

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

629 or an equivalent implementation. 

630 

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

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

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

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

635 to override default L{nonfiniterrors} 

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

637 

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

639 ''' 

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

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

642 

643 

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

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

646 ''' 

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

648 

649 

650def fmean(xs, nonfinites=True): 

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

652 

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

654 

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

656 

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

658 

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

660 ''' 

661 n, xs = len2(xs) 

662 if n < 1: 

663 raise LenError(fmean, xs=xs) 

664 M = Fsum(*xs, nonfinites=nonfinites) 

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

666 

667 

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

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

670 

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

672 ''' 

673 return fmean(xs, **nonfinites) 

674 

675 

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

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

678 

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

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

681 positional. 

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

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

684 

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

686 

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

688 ''' 

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

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

691 

692 

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

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

695 

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

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

698 L{Fpolynomial<Fpolynomial.__init__>}. 

699 

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

701 ''' 

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

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

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

705 

706 

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

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

709 

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

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

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

713 exponent (C{int}). 

714 

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

716 

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

718 

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

720 ''' 

721 if not isint(n): 

722 raise _IsnotError(typename(int), n=n) 

723 elif n < 1: 

724 raise _ValueError(n=n) 

725 

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

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

728 

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

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

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

732 

733 return ps 

734 

735 

736try: 

737 from math import prod as fprod # PYLINT W0611 Python 3.8 

738except ImportError: 

739 

740 def fprod(xs, start=1): 

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

742 

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

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

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

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

747 

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

749 

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

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

752 ''' 

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

754 

755 

756def frandoms(n, seeded=None): 

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

758 

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

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

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

762 

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

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

765 ''' 

766 from random import gauss, random, seed, shuffle 

767 

768 if seeded is None: 

769 pass 

770 elif seeded and isbool(seeded): 

771 from time import localtime 

772 seed(localtime().tm_yday) 

773 elif isscalar(seeded): 

774 seed(seeded) 

775 

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

777 for _ in range(n): 

778 s = 0 

779 t = list(c) 

780 _a = t.append 

781 for _ in range(n * 8): 

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

783 _a(v) 

784 s += v 

785 shuffle(t) 

786 yield t 

787 

788 

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

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

791 

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

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

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

795 

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

797 

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

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

800 ''' 

801 if not isint(number): 

802 raise _IsnotError(typename(int), number=number) 

803 for i in range(number): 

804 yield start + (step * i) 

805 

806 

807try: 

808 from functools import reduce as freduce 

809except ImportError: 

810 try: 

811 freduce = reduce # PYCHOK expected 

812 except NameError: # Python 3+ 

813 

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

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

816 ''' 

817 if start: 

818 r = v = start[0] 

819 else: 

820 r, v = 0, MISSING 

821 for v in xs: 

822 r = f(r, v) 

823 if v is MISSING: 

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

825 return r 

826 

827 

828def fremainder(x, y): 

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

830 

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

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

833 

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

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

836 

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

838 

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

840 project/geographiclib/>} and Python 3.7+ 

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

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

843 ''' 

844 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and 

845 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native 

846 # fmod( 0, 360) == 0.0 

847 # fmod( 360, 360) == 0.0 

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

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

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

851 # however, using the % operator ... 

852 # 0 % 360 == 0 

853 # 360 % 360 == 0 

854 # 360.0 % 360 == 0.0 

855 # -0 % 360 == 0 

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

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

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

859 

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

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

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

863 if isfinite(x): 

864 try: 

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

866 except Exception as e: 

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

868 else: # handle x INF and NINF as NAN 

869 r = NAN 

870 return r 

871 

872 

873def ftruncate(f): 

874 '''(INTERNAL) Truncate C{f} toward C{0} preserving signed C{0}. 

875 ''' 

876 try: 

877 i = _truncate(f) 

878 f = i if i else _copysign_0_0(f) 

879 except (OverflowError, ValueError): 

880 pass 

881 return f 

882 

883 

884def _half(half=False): 

885 return _0_5 if half else _0_4142 

886 

887 

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

889 from math import hypot # OK in Python 3.7- 

890 

891 def hypot_(*xs): 

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

893 

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

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

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

897 handled differently. 

898 

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

900 

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

902 

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

904 

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

906 

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

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

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

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

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

912 ''' 

913 return float(_Hypot(*xs)) 

914 

915elif _MODS.sys_version_info2 < (3, 10): # PYCHOK no cover 

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

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

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

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

920 

921 def hypot(x, y): 

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

923 

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

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

926 

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

928 ''' 

929 return float(_Hypot(x, y)) 

930 

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

932else: 

933 from math import hypot # PYCHOK in Python 3.10+ 

934 hypot_ = hypot 

935 

936 

937def _Hypot(*xs): 

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

939 ''' 

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

941 

942 

943def hypot1(x): 

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

945 

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

947 

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

949 ''' 

950 h = _1_0 

951 if x: 

952 if _isFsum_2Tuple(x): 

953 h = _Hypot(h, x) 

954 h = float(h) 

955 else: 

956 h = hypot(h, x) 

957 return h 

958 

959 

960def hypot2(x, y, *x0_y0): 

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

962 

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

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

965 @arg x0_y0: Optional reference C{(x0, y0)} (each C{scalar}, 

966 an L{Fsum} or L{Fsum2Tuple}). 

967 

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

969 ''' 

970 x, y = _map0(abs, x, y, *x0_y0) # NOT fabs! 

971 if x < y: 

972 x, y = y, x 

973 h2 = x**2 

974 if h2 and y: 

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

976 return float(h2) 

977 

978 

979def hypot2_(*xs): 

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

981 

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

983 L{Fsum2Tuple}), all positional. 

984 

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

986 

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

988 ''' 

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

990 if h2: # and isfinite(h2) 

991 _h = _1_0 / h2 

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

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

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

995 return h2 

996 

997 

998def _map0(_f, x, y, x0=_0_0, y0=_0_0, *unused): # PYLINT W1113 

999 return _f(x - x0), _f(y - y0) 

1000 

1001 

1002def _map03(_f, x, y, *x0_y0): 

1003 x, y = _map0(_f, x, y, *x0_y0) 

1004 return x, y, hypot(x, y) 

1005 

1006 

1007def norm2(x, y, *x0_y0): 

1008 '''Normalize a 2-dimensional vector. 

1009 

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

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

1012 @arg x0_y0: Optional reference C{(x0, y0)} (each C{scalar}, 

1013 an L{Fsum} or L{Fsum2Tuple}). 

1014 

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

1016 

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

1018 

1019 @see: Function L{polar3}. 

1020 ''' 

1021 return polar3(x, y, *x0_y0)[:2] 

1022 

1023 

1024def norm_(*xs): 

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

1026 

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

1028 L{Fsum2Tuple}), all positional. 

1029 

1030 @return: Yield each component, normalized. 

1031 

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

1033 or zero norm. 

1034 ''' 

1035 try: 

1036 i = h = None 

1037 x = xs 

1038 h = hypot_(*xs) 

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

1040 for i, x in enumerate(xs): 

1041 yield x * _h 

1042 except Exception as X: 

1043 raise _xsError(X, xs, i, x, h=h) # PYLINT E0601 

1044 

1045 

1046def polar2(x, y, *x0_y0): 

1047 '''Return 2-tuple C{(length, angle)} with C{angle} in radians M{[0..+PI2)}. 

1048 

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

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

1051 @arg x0_y0: Optional reference C{(x0, y0)} (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

1052 

1053 @note: Use C{polar(B{y}, B{x}, *B{y0_x0})} to get the angle as C{bearing} from North. 

1054 ''' 

1055 x, y, h = _map03(float, x, y, *x0_y0) 

1056 return h, _MODS.utily.atan2p(y, x) 

1057 

1058 

1059def polar2d(x, y, *x0_y0): 

1060 '''Return 2-tuple C{(length, angle)} with C{angle} in degrees M{[0..+360)}. 

1061 

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

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

1064 @arg x0_y0: Optional reference C{(x0, y0)} (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

1065 

1066 @note: Use C{polar2d(B{y}, B{x}, *B{y0_x0})} to get the angle as C{bearing} from North. 

1067 ''' 

1068 x, y, h = _map03(float, x, y, *x0_y0) 

1069 return h, _MODS.utily.atan2b(y, x) 

1070 

1071 

1072def polar3(x, y, *x0_y0): 

1073 '''Return 3-tuple C{(cosine, sine, length)}. 

1074 

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

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

1077 @arg x0_y0: Optional reference C{(x0, y0)} (each C{scalar}, an L{Fsum} or L{Fsum2Tuple}). 

1078 

1079 @see: Function L{norm2}. 

1080 ''' 

1081 try: 

1082 h = None 

1083 x, y, h = _map03(float, x, y, *x0_y0) 

1084 if h: 

1085 t = (x / h), (y / h), h 

1086 else: 

1087 t = (_copysign_0_0(x), # pass? 

1088 _copysign_0_0(y), h) 

1089 except Exception as X: 

1090 raise _xError(X, x=x, y=y, h=h) 

1091 return t 

1092 

1093 

1094def _powers(x, n): 

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

1096 ''' 

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

1098 for _ in range(n): 

1099 p *= x 

1100 yield p 

1101 

1102 

1103def _root(x, p, where): 

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

1105 ''' 

1106 try: 

1107 if iscomplex(x): 

1108 return pow(x, p) 

1109 elif x > 0: 

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

1111 return r.fpow(p).as_iscalar 

1112 elif x < 0: 

1113 raise ValueError(_negative_) 

1114 except Exception as X: 

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

1116 return _0_0 if p else _1_0 # x == 0 

1117 

1118 

1119def sqrt0(x, Error=None): 

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

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

1122 

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

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

1125 

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

1127 

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

1129 

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

1131 returns C{0.0}. 

1132 ''' 

1133 if Error and x < 0: 

1134 raise Error(unstr(sqrt0, x)) 

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

1136 _0_0 if x < EPS02 else EPS0) 

1137 

1138 

1139def sqrt3(x): 

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

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

1142 

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

1144 

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

1146 

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

1148 

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

1150 

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

1152 ''' 

1153 return _root(x, _1_5, sqrt3) 

1154 

1155 

1156def sqrt_a(h, b): 

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

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

1159 

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

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

1162 

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

1164 

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

1166 

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

1168 

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

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

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

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

1173 ''' 

1174 try: 

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

1176 raise TypeError(_not_scalar_) 

1177 c = fabs(h) 

1178 if c > EPS0: 

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

1180 if s < 0: 

1181 raise ValueError(_h_lt_b_) 

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

1183 else: # PYCHOK no cover 

1184 b = fabs(b) 

1185 d = c - b 

1186 if d < 0: 

1187 raise ValueError(_h_lt_b_) 

1188 d *= c + b 

1189 a = sqrt(d) if d else _0_0 

1190 except Exception as x: 

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

1192 return copysign0(a, h) 

1193 

1194 

1195def zcrt(x): 

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

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

1198 

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

1200 

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

1202 

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

1204 

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

1206 

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

1208 ''' 

1209 return _root(x, _1_6th, zcrt) 

1210 

1211 

1212def zqrt(x): 

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

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

1215 

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

1217 

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

1219 

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

1221 

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

1223 

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

1225 ''' 

1226 return _root(x, _0_125, zqrt) 

1227 

1228# **) MIT License 

1229# 

1230# Copyright (C) 2016-2027 -- mrJean1 at Gmail -- All Rights Reserved. 

1231# 

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

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

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

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

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

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

1238# 

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

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

1241# 

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

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

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

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

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

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

1248# OTHER DEALINGS IN THE SOFTWARE.