Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a faster alternative to python's Decimal?

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
like image 641
Kozyarchuk Avatar asked Oct 12 '08 05:10

Kozyarchuk


People also ask

Should I use decimal or float Python?

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.

What is the Python decimal library good for?

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.

What is the difference between float and decimal in Python?

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.


2 Answers

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.

like image 152
Andrew G Avatar answered Nov 16 '22 01:11

Andrew G


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.

like image 37
Greg Hewgill Avatar answered Nov 16 '22 02:11

Greg Hewgill