Search code examples
pythonnumpypython-decimal

Multiple value output from expression using decimal.Decimal?


Suppose I have an expression involving the decimal module where I want to input multiple values and get multiple values out.

a=np.array([1,2,3])
b=np.array([4,5,6])
A=a.astype(object)
B=b.astype(object)

getcontext().prec = 100
x=Decimal(A+B)

This raises an error since Decimal is incompatible with numpy arrays.

How can I pass multiple values through a Decimal expression and get multiple values out in such a way that I could easily convert the outputs to a float and then put them in a numpy array?

The reason I would want this is that a certain calculation involves A+B being calculated incorrectly as a float but once Decimal(A+B) is calculated, the resulting output can be converted to a float and cause no further difficulties in the calculation.

EDIT: I have been developing a 'cheat' method but I don't know if it has legs:

a=np.array([1,2,3])
b=np.array([4,5,6])
A=a.astype(object)
B=b.astype(object)

getcontext().prec = 100
for i in range (0,2):
    x=Decimal(A[i]+B[i])
    print(x)

Key here is to indent print(x), this prints 5 7 9. Failing a true solution to the above problem, is there a way of converting 5 7 9 to np.array([5,7,9]). (Maybe by exporting as csv file and importing into Python again?)


Solution

  • I think you could do it manually like this:

    r = np.array(tuple(Decimal(x+y) for x, y in zip(A, B)), np.float64)
    print(r)
    

    Output:

    [5. 7. 9.]