python - Why doesn't numpy determinant return a Fraction when given a Fraction matrix? -
i want perform operations on rational matrices. use modules numpy
, fractions
.
here code:
import numpy np fractions import fraction m=np.matrix([[fraction(1, 6), fraction(8, 7)], [fraction(1, 2), fraction(3, 2)]]) print(np.linalg.det(m)) # gives -0.321428571429 print(m[0,0]*m[1,1] - m[0,1]*m[1,0]) # gives -9/28
since computing determinant require rational operations gauss' method, determinant of rational matrix rational.
so questions are: why numpy return float , not fraction? how can rational determinant?
note other operations on matrix give rational output (for instance m.trace()
).
numpy computes determinant of matrix lower upper decomposition routine in lapack. routine can handle floating point numbers.
before calculating determinant of matrix, linalg.det
checks types of values has , establishes type of internal loop should run using call function named _commontype()
. function set loop run either double or complex-double values.
here python part of function linalg.det
handles checking:
def det(a): = asarray(a) # convert matrix numpy array _assertnoempty2d(a) _assertrankatleast2(a) _assertndsquareness(a) t, result_t = _commontype(a) # input/output types established here signature = 'd->d' if iscomplextype(t) else 'd->d' # signature 'float->float' chosen return _umath_linalg.det(a, signature=signature).astype(result_t)
after running checks on shape of matrix , determining types, return
line passes values in array lapack implementation of lower-upper decomposition , float returned.
trying bypass type checking type signature of our own raises error saying no such loop defined object types:
>>> np.linalg._umath_linalg.det(a, signature='o->o') # 'o' 'object' typeerror: no loop matching specified signature found ufunc det
this implies not possible keep fraction
type return type when using det
.
other functions such trace()
not same type checking det
, object type may persist. trace
sums diagonal calling fraction
object's __add__
method, fraction
object can kept return type.
if want calculate determinant rational number, investigate sympy. matrix operations such calculating determinants documented here.
Comments
Post a Comment