Search code examples
sympy

Maybe a wrong rank when there are parameters


The result of the following code is 2, but the value of the rank of the matrix is not 2 if k = 0. Is this a bug?

import sympy as sp

k = sp.Symbol('k', assumptions={'real': True})

A = sp.Matrix([[1, 0], [1, k]])

A.rank()

Solution

  • I looked into the source code for this some time ago because I had the same question. When asking for the rank of a matrix, the procedure for a 2x2 matrix is: If all elements are zero, the rank is zero. Otherwise, get the determinant and check whether it is identical to zero. As your k is not zero in general, the rank is determined to be 2. There just are no explicit checks whether a combination of parameters could result in special cases of a rank 1 matrix.

    If we think about it, this is in my opinion the best we can expect from SymPy. As matrix entries can be arbitrary functions, one would need to check whether some arguments could result in special cases for a reduction of the matrix rank. This would be far too complex.

    We just have to be aware of it and read the result as in general the rank is 2 but I need to check myself for special cases.

    For instance, we also get from SymPy a valid inverse in the following case although there obviously is no inverse for ad-bc = 0.

    import sympy as sp
    
    sp.var('a, b, c, d')
    
    A = sp.Matrix([[a, b], [c, d]])
    A.inv()