python: Greatest common divisor (gcd) for floats, preferably in numpy -
i looking efficient way determine greatest common divisor of 2 floats python. routine should have following layout
gcd(a, b, rtol=1e-05, atol=1e-08) """ returns greatest common divisor of , b parameters ---------- a,b : float 2 floats gcd rtol, atol : float, optional relative , absolute tolerance returns ------- gcd : float greatest common divisor such x in [a,b]: np.mod(x,gcd) < rtol*x + atol .. _pep 484: https://www.python.org/dev/peps/pep-0484/ """ example: gcd of rational , irrational number
the gcd(1., np.pi, rtol=0, atol=1e-5) should return (roughly) 1e-5, as
in [1]: np.mod(np.pi,1e-5) out[1]: 2.6535897928590063e-06 in [2]: np.mod(1.,1e-5) out[2]: 9.9999999999181978e-06 i prefer use library implementation , not write myself. fractions.gcd function not seem appropriate me here, not want work fractions , (obviously) not have tolerance parameters.
seems modify code of fractions.gcd include tolerances:
def float_gcd(a, b, rtol = 1e-05, atol = 1e-08): t = min(abs(a), abs(b)) while abs(b) > rtol * t + atol: a, b = b, % b return
Comments
Post a Comment