I'm trying to find the inverse of a matrix made up of a specific class (decimal.Decimal
) and keep the values as Decimal objects throughout the process (to preserve exactness throughout the calculation).
My problem is numpy.linalg.inverse
always returns the matrix values as floats. I've figured out a work around by changing the type from floats to Decimal objects after the inverse is calculated but I'd prefer to maintain the class of the original matrix throughout (I'm worried I may be losing accuracy when the numbers are converted to floats)?
So I guess I have a few questions: (1) am I losing accuracy/exactness when the values of the matrix are converted to float types (I'm dealing with an 11 by 11 matrix); if so, (2) is there anyway to keep the values as decimal.Decimal
throughout the calculation using numpy
; if not, (3) is there another module / method I should consider for this type of calculation?
Here's an example of what my code will look like:
import numpy as np
from decimal import Decimal as D
a = np.array( [ [D('1'), D('2'), D('3')],
[D('4'), D('5'), D('6')],
[D('7'), D('8'), D('9')] ] )
print type(a[0,0])
# <class 'decimal.Decimal'>
inverse_a = np.linalg.inv(a)
print type(inverse_a[0,0])
# <type 'numpy.float64'>
inverse_a_Decimal_flat = [D(str(i)) for i in inverse_a.flat] # change all values to decimal.Decimal
inverse_a_Decimal = np.reshape(inverse_a_Decimal_flat, [3, 3]) # reshape to 3x3
print type(inverse_a_Decimal[0,0]), d.shape
# <class 'decimal.Decimal'> (3,3)