sympy / sympy

A computer algebra system written in pure Python
https://sympy.org/
Other
13.05k stars 4.47k forks source link

elementary_row_op() raise a false ValueError saying "This matrix doesn't have a row '5'" #17827

Closed Hou-Rui closed 5 years ago

Hou-Rui commented 5 years ago

I was using sympy for elementary row operations when it raised an expected ValueError. The code is like this:

from sympy import Matrix, pprint

C = Matrix([
    [3,4,-1,1],
    [9,12,-3,3],
    [0,2,1,3],
    [2,3,0,-2],
    [0,3,3,-5],
    [8,15,0,6],
])
pprint(C)
pprint(C.elementary_row_op('n<->m', row1=2, row2=5))

This code will raise ValueError: This matrix doesn't have a row '5', but I'm pretty sure that the matrix does have a row 5. It works fine if I do C.elementary_row_op('n<->m', row1=2, row2=4).

Strangely, if I add an additional column and doesn't change the count of rows at all, it will work fine:

from sympy import Matrix, pprint

C = Matrix([
    [3,4,-1,1,0],
    [9,12,-3,3,0],
    [0,2,1,3,0],
    [2,3,0,-2,0],
    [0,3,3,-5,0],
    [8,15,0,6,0],
])
pprint(C)
pprint(C.elementary_row_op('n<->m', row1=2, row2=5))

I'm novice both in sympy and in linear algebra. Is it a bug or did I miss out something?

p.s. Screenshot attached:

Screenshot 2019-10-31 at 15 33 14

Running in macOS 10.14, python 3.7, sympy 1.4.

jksuom commented 5 years ago

There is a bug on line 624. _normalize_op_args() is used for both columns and rows. It should have self.rows instead of self.cols when rows are handled. (Besides, there should be strict inequality 0 <= col2 < self.cols even in the column case.)

This could be fixed by adding the number of columns/rows as an input parameter.