[英]python: Greatest common divisor (gcd) for floats, preferably in numpy
我正在尋找一種有效的方法來確定兩個使用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
以下代碼可能有用。 要調用的函數是float_gdc(a,b)。
from math import gcd, log10, pow
def float_scale(x):
max_digits = 14
int_part = int(abs(x))
magnitude = 1 if int_part == 0 else int(log10(int_part)) + 1
if magnitude >= max_digits:
return 0
frac_part = abs(x) - int_part
multiplier = 10 ** (max_digits - magnitude)
frac_digits = multiplier + int(multiplier * frac_part + 0.5)
while frac_digits % 10 == 0:
frac_digits /= 10
return int(log10(frac_digits))
def float_gcd(a, b):
sc = float_scale(a)
sc_b = float_scale(b)
sc = sc_b if sc_b > sc else sc
fac = pow(10, sc)
a = int(round(a*fac))
b = int(round(b*fac))
return round(gcd(a, b)/fac, sc)
代碼的一部分取自此處: 確定Python中特定數字的精度和比例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.