Search code examples
pythonpython-3.xnumpymatrix-inverse

Matrix inverse with Decimal type NumPy


I have a couple of matrix like this one:

[[Decimal('1') Decimal('1') Decimal('1') Decimal('1')][Decimal('56.44000000000000000') Decimal('57.32000000000000000') Decimal('57.04000000000000000') Decimal('56.48000000000000000')]

Yes, that's decimal.Decimal type.

Then I want it's inverse:

from numpy.linalg.linalg import inv
invs = inv(mymatrix)
print(invs)

[[ -2.07973657e+15  -7.33173736e+13  -5.68628487e+13   6.80363276e+11
    4.51521775e+12   6.50136911e+11   1.12144399e+10  -1.44488244e+10
   -4.87281445e+10   5.24155356e+08] ...

As you can see the values were converted to float values. I understand Decimal is not supported out of the box, but still I would like a way to accomplish this working with the decimal type for precision.


Solution

  • Unfortunately, there is no way to make numpy and its inverse operation work with decimal.Decimal, or cdecimal.Decimal. It will always convert to float64 as it cannot perform that operation with Decimal. Numpy doesn't know anything about Decimal as the array holds it as dtype object.

    If you want to change the datatype of your numpy array you can call something like this:

    from cdecimal import Decimal
    a=np.array([[Decimal('1'),Decimal('1')],[Decimal('1'),Decimal('2')]])
    a
    >>> array([[Decimal('1'), Decimal('1')],
       [Decimal('1'), Decimal('2')]], dtype=object)
    a=a.astype(np.float128)
    a
    >>> array([[ 1.0,  1.0],
       [ 1.0,  2.0]], dtype=float128)
    

    This will give you the precision of your C compiler's long double, probably Extended Precision Format (80-bit floating point)