0

I am searching for a fast implementation to multiply two vectors of decimal in Python. I tried to make two lists and then multiply them:

from decimal import Decimal, getcontext
getcontext().prec = 20
import cProfile

a = [Decimal(x) for x in range(1,10000)]
b = [Decimal(x) for x in range(1,10000)]
def multiply(a,b):
    [x*y for x,y in zip(a,b)]
cProfile.run('multiply(a,b)')

and this takes around 0.224 seconds. However, if I try to do the same for numpy vectors:

import numpy as np
a = np.arange(1,10000)
b = np.arange(1,10000)
def multiply(a,b):
    a*b
cProfile.run('multiply(a,b)')

It takes 0.000 second. Is there any alternative way to make a vector of decimal and multiply them in python?

Roozbeh
  • 1
  • 1
  • What's the problem with numpy? Numpy was made to do exactly these things very fast. – Spidey Aug 26 '17 at 23:40
  • 5
    `Decimal` is slow. You aren't getting around that. – Ignacio Vazquez-Abrams Aug 26 '17 at 23:40
  • 4
    The reason NumPy is fast is fundamentally incompatible with decimal.Decimal, which is arbitrary-precision. – user2357112 Aug 26 '17 at 23:41
  • I need a similar package with the same feature of `Decimal` that be comparable with `numpy` – Roozbeh Aug 26 '17 at 23:43
  • 4
    That's badly formulated and contradicts the valid points already mentioned when you are asking for performance (do you think the decimal package is slow on purpose?). – sascha Aug 26 '17 at 23:44
  • It is not on purpose for sure, but I want to multiply two vector of numbers which are super low and NumPy sees them as a sequence of zeros. – Roozbeh Aug 26 '17 at 23:49
  • How about scaling super low numbers to high numbers and them scaling them back down? – Spidey Aug 26 '17 at 23:52
  • Good suggestion, but for my case, the numbers are ranging between 10^-1000 to 1. So there is not a uniform scaling. – Roozbeh Aug 26 '17 at 23:55
  • 1
    That range is really unfavorable. You need to find a way to change it and that depends on what you're doing. Otherwise, you are forced to use data structures with arbitrary precision and all of them are slow (slower than their counterparts). – Spidey Aug 27 '17 at 00:00
  • 4
    Possible duplicate of [numpy arbitrary precision linear algebra](https://stackoverflow.com/questions/6876377/numpy-arbitrary-precision-linear-algebra) – Andrea Corbellini Aug 27 '17 at 00:01
  • 4
    Work with logarithms. – user2357112 Aug 27 '17 at 00:02

0 Answers0