我正在寻找一种有效的方法来使用 python 确定两个 float 的最大公约数。例程应具有以下布局
gcd(a, b, rtol=1e-05, atol=1e-08)
"""
Returns the greatest common divisor of a and b
Parameters
----------
a,b : float
two floats for gcd
rtol, atol : float, optional
relative and absolute tolerance
Returns
-------
gcd : float
Greatest common divisor such that for x in [a,b]:
np.mod(x,gcd) < rtol*x + atol
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
例子:有理数和无理数的gcd
gcd(1., np.pi, rtol=0, atol=1e-5)
应该(大致)返回 1e-5
,因为
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
我更愿意使用库实现而不是自己编写。 fractions.gcd函数在这里似乎不适合我,因为我不想使用分数,而且它(显然)没有公差参数。
最佳答案
看来你可以只修改 fractions.gcd
的代码包括公差:
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, a % b
return a
关于python: float 的最大公约数(gcd),最好在numpy中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45323619/