Fast conversion of numbers to numerator/denominator pairs

Ian Kelly ian.g.kelly at gmail.com
Sat Aug 24 03:37:53 EDT 2013


On Fri, Aug 23, 2013 at 9:30 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Is there a fast way to convert a Decimal into a pair of numbers numerator/
> denominator? It *must* be exact, but it doesn't have to be simplest form.
> For example, Decimal("0.5") => (5, 10) would be okay, although (1, 2)
> would be preferred.
>
>
> I've tried this function:
>
> def convert(d):
>     sign, digits, exp = d.as_tuple()
>     num = int(''.join([str(digit) for digit in digits]))
>     if sign: num = -num
>     return num, 10**-exp
>
>
> which is faster, but not fast enough. Any suggestions?

I time this function at about 33% faster than your version for a
six-digit decimal, and almost 50% faster for a 12-digit decimal.  My
guess would be because it's not calling str() on every individual
digit.

def convert(d):
    exp = d.as_tuple().exponent
    num = int(d.scaleb(-exp))
    return num, 10**-exp



More information about the Python-list mailing list