Fast conversion of numbers to numerator/denominator pairs
Tim Delaney
timothy.c.delaney at gmail.com
Sat Aug 24 17:59:15 EDT 2013
On 24 August 2013 13:30, Steven D'Aprano <
steve+comp.lang.python at 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 enough. Any suggestions?
>
Straightforward multiply and add takes about 60% of the time for a single
digit on my machine compared to the above, and 55% for 19 digits (so
reasonably consistent). It's about 10x slower than fractions.
def convert_muladd(d, _trans=_trans, bytes=bytes):
sign, digits, exp = d.as_tuple()
num = 0
for digit in digits:
num *= 10
num += digit
if sign:
num = -num
return num, 10**-exp
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.
Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130825/e34a6e70/attachment.html>
More information about the Python-list
mailing list