python: Greatest common divisor (gcd) for floats, preferably in numpy

2024/4/15 1:16:13

I am looking for an efficient way to determine the greatest common divisor of two floats with python. The routine should have the following layout

gcd(a, b, rtol=1e-05, atol=1e-08)
Returns the greatest common divisor of a and bParameters
a,b : floattwo floats for gcd
rtol, atol : float, optionalrelative and absolute toleranceReturns
gcd : floatGreatest common divisor such that for x in [a,b]:np.mod(x,gcd) < rtol*x + atol .. _PEP 484:"""

Example: gcd of rational and 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-06In [2]: np.mod(1.,1e-5)
Out[2]: 9.9999999999181978e-06

I would prefer to use a library implementation and not to write it myself. The fractions.gcd function does not seem appropriate to me here, as I do not want to work with fractions and it (obviously) does not have the tolerance parameters.


Seems like you could just modify the code of fractions.gcd to include the 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, a % breturn a

Related Q&A

Difference between @property and property()

Is there a difference betweenclass Example(object):def __init__(self, prop):self._prop = propdef get_prop(self):return self._propdef set_prop(self, prop):self._prop = propprop = property(get_prop, set_…

airflow webserver command fails with {} ERROR - Operation not permitted

I am installing airflow on a Cent OS 7. I have configured airflow db init and checked the status of the nginx server as well its working fine. But when I run the airflow webserver command I am getting …

Django REST Framework - How to return 404 error instead of 403

My API allows access (any request) to certain objects only when a user is authenticated and certain other conditions are satisfied.class SomethingViewSet(viewsets.ModelViewSet):queryset = Something.obj…

503 Reponse when trying to use python request on local website

Im trying to scrape my own site from my local server. But when I use python requests on it, it gives me a response 503. Other ordinary sites on the web work. Any reason/solution for this?import reques…

Dereferencing lists inside list in Python

When I define a list in a "generic" way:>>>a=[[]]*3 >>>a [[],[],[]]and then try to append only to the second element of the outer list:>>>a[1].append([0,1]) >>…

Unit test Theories in Python?

In a previous life I did a fair bit of Java development, and found JUnit Theories to be quite useful. Is there any similar mechanism for Python?Currently Im doing something like:def some_test(self):c…

how to do a nested for-each loop with PySpark

Imagine a large dataset (>40GB parquet file) containing value observations of thousands of variables as triples (variable, timestamp, value).Now think of a query in which you are just interested in …

Understanding an issue with the namedtuple typename and pickle in Python

Earlier today I was having trouble trying to pickle a namedtuple instance. As a sanity check, I tried running some code that was posted in another answer. Here it is, simplified a little more:from coll…

SQLAlchemy Columns result processing

Im working with a IBM DB2 database using ibm_db2 driver and sqlalchemy. My model is:class User(Model):id = Column(UID, Integer, primary_key=True)user = Column(USER, String(20))password …

How can I access relative paths in Python 2.7 when imported by different modules

The Goal: Access / Write to the same temp files when using a common utility function called from various python modules.Background: I am using the python Unittest module to run sets of custom tests tha…