long(Decimal) performance
ajaksu
ajaksu at gmail.com
Sat Aug 12 11:29:09 EDT 2006
Hi Aahz, thanks for the feedback!
Aahz wrote:
> I'm not sure why it's coded that, but it's somewhat irrelevant: right
> now, work is being done to convert decimal.py to C code, which will
> almost certainly be much faster than your code. Generally speaking, you
> should not be using Decimal now with any expectation of speed.
Agreed and agreed.
Just to avoid that the buggy (and unreadable) versions above harm
anyone, here's a better attempt:
def dec2long(number):
""" Convert C{decimal.Decimal} to long """
decimal_string = str(number)
## Split 123.45E10 -> radix = 123.45, exponent = 10
if "e" in decimal_string:
radix, exponent = decimal_string.split("e")
elif "E" in decimal_string:
radix, exponent = decimal_string.split("E")
else:
radix, exponent = (decimal_string, 0)
if exponent:
exponent = int(exponent)
if "." in radix:
## radix = 123.45, radix_decimal_part_len = 2
radix_decimal_part_len = long(len(radix.split(".")[1]))
## radix = 123.45, radix_as_long = 123.45 * 10**2 = 12345
radix_as_long = long(Decimal(radix) *
(10L**radix_decimal_part_len))
##corrected_exponent = 10 - 2 = 8
corrected_exponent = exponent - radix_decimal_part_len
## return 12345 * 10**8
result = radix_as_long * 10L** corrected_exponent
else:
radix_as_long = long(radix)
result = radix_as_long * 10L**exponent
else:
if "." in radix:
radix_integer_part = long(radix.split(".")[0])
else:
radix_integer_part = long(radix)
result = radix_integer_part
return result
Working from inside decimal.py allows things to work faster, but anyone
wanting speed REALLY shouldn't use Decimal :). Now I'm trying clnum
("Rational and arbitrary precision floating point numbers"):
http://cheeseshop.python.org/pypi/clnum/1.2
Cheers,
Daniel
More information about the Python-list
mailing list