pythonsympylinear-equation

Matrix rank and determinant vs. linear combinations of column vectors using sympy


If a square matrix is not full rank, its determinant is zero, its column vectors are linearly dependent and we can obtain one of the column vectors as a linear combination of the others. Below is a matrix which, according to sympy, has not full rank, and has determinant of 0. However, sympy seems unable to find a linear combination of any two column vectors that is equal to the third column vector. Why is that?

Input:

x = sympy.symbols('x')
D = Matrix([[1,1+x,(1-x)*(1+3*x)],[1, 1-x, (1-x)**2],[1,1,(1-x**2)]])
print(D)
print('rank', D.rank())
print('det', D.det())
D[:,[1,2]].LUsolve(D[:,0]) # gives same result as D[:,[0,1]].LUsolve(D[:,2]) and D[:,[0,2]].LUsolve(D[:,1])

Output:

Matrix([[1, x + 1, (1 - x)*(3*x + 1)], [1, 1 - x, (1 - x)**2], [1, 1, 1 - x**2]])
rank 2
det 0

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-330-4d4f8f3e2cc0> in <module>
      5 print('det', D.det())
      6 
----> 7 D[:,1:].LUsolve(D[:,0])

~\anaconda3\envs\symbolic\lib\site-packages\sympy\matrices\matrices.py in LUsolve(self, rhs, iszerofunc)
   2152 
   2153     def LUsolve(self, rhs, iszerofunc=_iszero):
-> 2154         return _LUsolve(self, rhs, iszerofunc=iszerofunc)
   2155 
   2156     def QRsolve(self, b):

~\anaconda3\envs\symbolic\lib\site-packages\sympy\matrices\solvers.py in _LUsolve(M, rhs, iszerofunc)
    357             for j in range(b.cols):
    358                 if not iszerofunc(b[i, j]):
--> 359                     raise ValueError("The system is inconsistent.")
    360 
    361         b = b[0:n, :]   # truncate zero rows if consistent

ValueError: The system is inconsistent.

Solution

  • Possibly this is a bug in lusolve.

    You can get an answer with linsolve:

    In [10]: linsolve((D[:,[1,2]], D[:,0]))
    Out[10]: 
    ⎧⎛ -2        -1      ⎞⎫
    ⎪⎜─────, ────────────⎟⎪
    ⎨⎜x - 1   2          ⎟⎬
    ⎪⎝       x  - 2⋅x + 1⎠⎪
    ⎩                     ⎭