Does anyone know of a faster decimal implementation in python?
As the example below demonstrates, the standard library's decimal module is ~100 times slower than float
.
from timeit import Timer
def run(val, the_class):
test = the_class(1)
for c in xrange(10000):
d = the_class(val)
d + test
d - test
d * test
d / test
d ** test
str(d)
abs(d)
if __name__ == "__main__":
a = Timer("run(123.345, float)", "from decimal_benchmark import run")
print "FLOAT", a.timeit(1)
a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal")
print "DECIMAL", a.timeit(1)
Outputs:
FLOAT 0.040635041427
DECIMAL 3.39666790146
By default, Python interprets any number that includes a decimal point as a double precision floating point number. The Decimal is a floating decimal point type which more precision and a smaller range than the float. It is appropriate for financial and monetary calculations.
Summary. Use the Python decimal module when you want to support fast correctly-rounded decimal floating-point arithmetic. Use the Decimal class from the decimal module to create Decimal object from strings, integers, and tuples. The Decimal numbers have a context that controls the precision and rounding mechanism.
Float is a single precision (32 bit) floating point data type and decimal is a 128-bit floating point data type. Floating point data type represent number values with fractional parts.
You can try cdecimal:
from cdecimal import Decimal
As of Python 3.3, the cdecimal implementation is now the built-in implementation of the decimal
standard library module, so you don't need to install anything. Just use decimal
.
For Python 2.7, installing cdecimal
and using it instead of decimal
should provide a speedup similar to what Python 3 gets by default.
The GMP library is one of the best arbitrary precision math libraries around, and there is a Python binding available at GMPY. I would try that method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With