尝试手动计算矩阵行列式(我知道值是28
,可以通过m.det()
获得(:
from sympy import symbols, Matrix, summation
i = symbols('i', integer=True)
m = Matrix([[3, 2, -1],
[2, -1, -3],
[1, 3, -2]])
D = summation(m[i,0]*m.cofactor(i,0), (i, 0, 2))
它提出:
File ... sympymatricesmatrices.py:140 in minor_submatrix
return _minor_submatrix(self, i, j)
File ... sympymatricesdeterminant.py:890 in _minor_submatrix
if i < 0:
File ... sympycorerelational.py:511 in __bool__
raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational
定点:
summation(m[i,0], (i, 0, 2)) # Works
summation(m.cofactor(i,0), (i, 0, 2)) # Raises the error
我迷路了。
问题是m.cofactor(i,0)
,特别是i
。通过查看回溯:
859 def _minor_submatrix(M, i, j):
860 """Return the submatrix obtained by removing the `i`th row
861 and `j`th column from ``M`` (works with Pythonic negative indices).
862
(...)
883 cofactor
884 """
--> 886 if i < 0:
887 i += M.rows
888 if j < 0:
可以猜测m.cofactor
的自变量必须是整数,而不是符号。因此,我们需要重新思考如何获得您想要的结果。对于这种情况,简单的列表理解就足够了:
# here, the i variable takes numerical values
sum([m[i,0] * m.cofactor(i, 0) for i in range(m.shape[0])])
# out: 28