[Python-ideas] Python Float Update

Case Van Horsen casevh at gmail.com
Mon Jun 1 06:39:03 CEST 2015

On Sun, May 31, 2015 at 8:14 PM,  <random832 at fastmail.us> wrote:
> On Sun, May 31, 2015, at 22:25, u8y7541 The Awesome Person wrote:
>> First, I propose that a float's integer ratio should be accurate. For
>> example, (1 / 3).as_integer_ratio() should return (1, 3). Instead, it
>> returns(6004799503160661, 18014398509481984).
> Even though he's mistaken about the core premise, I do think there's a
> kernel of a good idea here - it would be nice to have a method (maybe
> as_integer_ratio, maybe with some parameter added, maybe a different
> method) to return with the smallest denominator that would result in
> exactly the original float if divided out, rather than merely the
> smallest power of two.

The gmpy2 library already supports such a method.

>>> import gmpy2
>>> gmpy2.version()
>>> a=gmpy2.mpfr(1)/3
>>> a.as_integer_ratio()
(mpz(6004799503160661), mpz(18014398509481984))
>>> a.as_simple_fraction()

gmpy2 uses a version of the Stern-Brocot algorithm to find the shortest
fraction that, when converted to a floating point value, will return the same
value as the original floating point value. The implementation was
originally done by Alex Martelli; I have just maintained it over the years.

The algorithm is quite fast. If there is a consensus to add this method
to Python, I would be willing to help implement it.


> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/

More information about the Python-ideas mailing list