Re: Fast conversion of numbers to numerator/denominator pairs

2013-08-24 Thread Tim Delaney
On 25 August 2013 07:59, Tim Delaney wrote: > Breakdown of the above (for 19 digits): > > d.as_tuple() takes about 35% of the time. > > The multiply and add takes about 55% of the time. > > The exponentiation takes about 10% of the time. > Bah - sent before complete. Since the multiply and add

Re: Fast conversion of numbers to numerator/denominator pairs

2013-08-24 Thread Tim Delaney
On 24 August 2013 13:30, Steven D'Aprano < steve+comp.lang.pyt...@pearwood.info> wrote: > > 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 enoug

Re: Fast conversion of numbers to numerator/denominator pairs

2013-08-24 Thread Peter Otten
Steven D'Aprano wrote: > I have a need to convert arbitrary non-complex numbers into numerator/ > denominator pairs. Numbers could be ints, floats, Fractions or Decimals. > For example: > > 2 => (2, 1) > 0.25 => (1, 4) > Fraction(2, 3) => (2, 3) > Decimal("0.5") => (1, 2) > > > The first three

Re: Fast conversion of numbers to numerator/denominator pairs

2013-08-24 Thread Ian Kelly
On Sat, Aug 24, 2013 at 1:37 AM, Ian Kelly wrote: > > 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 =

Re: Fast conversion of numbers to numerator/denominator pairs

2013-08-24 Thread Ian Kelly
On Fri, Aug 23, 2013 at 9:30 PM, Steven D'Aprano 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 prefer

Fast conversion of numbers to numerator/denominator pairs

2013-08-23 Thread Steven D'Aprano
I have a need to convert arbitrary non-complex numbers into numerator/ denominator pairs. Numbers could be ints, floats, Fractions or Decimals. For example: 2 => (2, 1) 0.25 => (1, 4) Fraction(2, 3) => (2, 3) Decimal("0.5") => (1, 2) The first three cases are easy and fast: # ints and Fraction