我正在寻找一种有效的方法来用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/
"""
Run Code Online (Sandbox Code Playgroud)
示例:有理数和无理数的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
Run Code Online (Sandbox Code Playgroud)
我宁愿使用库实现而不是自己编写它。该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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
934 次 |
| 最近记录: |