我正在寻找一种有效的方法来确定使用python的两个浮点数的最大公约数。该例程应具有以下布局

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:浮点数的最大公约数(gcd),最好是numpy,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45323619/

10-12 21:44