1

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.

gerosalesc
  • 2,983
  • 3
  • 27
  • 46
  • It doesn't seem to me that "precision" is a meaningful feature for a matrix inverse. How many digits do you want it to use? What makes you think the inverse can be accurately represented in that way? – Brent Bradburn Sep 20 '15 at 23:56
  • @nobar the end purpose of this operation is to calculate coefficients of a 3th grade equation and I have a requirement for these coefficients to be as precise as they could be and I defined 24 decimal positions for my Decimal class, does the double precision float provide this precision? – gerosalesc Sep 21 '15 at 00:12
  • I misunderstood what you meant by "precision". I thought you wanted fewer digits, but perfect accuracy (which is one of the features of [`decimal`](https://docs.python.org/2/library/decimal.html)). By the way, here are some thoughts about the precision of numpy.float128: [What is the internal precision of numpy.float128?](http://stackoverflow.com/questions/9062562/what-is-the-internal-precision-of-numpy-float128) – Brent Bradburn Sep 21 '15 at 05:54

1 Answers1

1

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)

benbo
  • 1,471
  • 1
  • 16
  • 29
  • how much precision does the float64 provides? can you provide a little snippet of how to convert? – gerosalesc Sep 21 '15 at 00:14
  • 1
    see my edits in the response. Note that the operations with float128 will be slower than float64 so make sure you really need that precision. – benbo Sep 21 '15 at 01:15