Search code examples
pythonmatrixscipydeterminants

Matrix determinant symbolic in python


Hi everyone I want to calculate the determinant of the below matrix "Symbolically" in python

x, y, z, a, b, c = symbols('x,y,z,a,b,c')
arr3 = np.array(([1-a,6,8-x],[2-b,10,12-y],[6-c,3,15-z]))
linalg.det(arr3)

But I get this error :

ValueError                                Traceback (most recent call last)
<ipython-input-34-fa7fd6eebff6> in <module>
----> 1 linalg.det(arr3)

~\anaconda3\lib\site-packages\scipy\linalg\basic.py in det(a, overwrite_a, check_finite)
   1030 
   1031     """
-> 1032     a1 = _asarray_validated(a, check_finite=check_finite)
   1033     if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
   1034         raise ValueError('expected square matrix')

~\anaconda3\lib\site-packages\scipy\_lib\_util.py in _asarray_validated(a, check_finite, sparse_ok, objects_ok, mask_ok, as_inexact)
    264     if not objects_ok:
    265         if a.dtype is np.dtype('O'):
--> 266             raise ValueError('object arrays are not supported')
    267     if as_inexact:
    268         if not np.issubdtype(a.dtype, np.inexact):

ValueError: object arrays are not supported

I am new so can you tell me how did I make wrong and Can I fix it?


Solution

  • You can't use numpy arrays for symbolical calculations with sympy. Instead, use a sympy Matrix:

    import sympy as sp
    x, y, z, a, b, c = sp.symbols('x,y,z,a,b,c')
    arr3 = sp.Matrix(([1-a,6,8-x],[2-b,10,12-y],[6-c,3,15-z]))
    print(sp.det(arr3))
    

    yields

    -3*a*y + 10*a*z - 114*a + 3*b*x - 6*b*z + 66*b - 10*c*x + 6*c*y + 8*c + 54*x - 33*y + 2*z - 66