如何使用python找到矩阵的行列式

时间:2017-11-24 01:58:14

标签: python matrix linear-algebra

新的python和生锈的线性代数。但是,我正在寻找关于在不使用Numpy的情况下从python中的矩阵创建行列式的正确方法的指导。请参阅下面的代码片段。非常感谢任何帮助。

import math 
from math import sqrt
import numbers 
import operators

def determinant(self)

        if not self.is_square():
            raise(ValueError, "Cannot calculate determinant of non-square matrix.")
        if self.h > 2:
            raise(NotImplementedError, "Calculating determinant not implemented for matrices larger than 2x2.")


        |x| = A

    det(A) = [[A, B][C, D]]

    assert self.rows == A.cols
    assert self.row > 1
    term_list = []

2 个答案:

答案 0 :(得分:1)

def determinant(matrix, mul):
width = len(matrix)
 if width == 1:
    return mul * matrix[0][0]
 else:
    sign = -1
    sum = 0
    for i in range(width):
        m = []
        for j in range(1, width):
            buff = []
            for k in range(width):
                if k != i:
                    buff.append(matrix[j][k])
            m.append(buff)
        sign *= -1
        sum += mul * determinant(m, sign * matrix[0][i])
    return sum

test_matrix = [[1,-2,3],[0,-3,-4],[0,0,-3]]

print(determinant(test_matrix, 1))

答案 1 :(得分:0)

这样你就可以得到非方阵的行列式。也许这是无稽之谈,但我发现 jupyter notebook 中的这个实现很有用,因为避免了对异常使用 try 的需要,有时获得零输出很有趣对于非方阵。

import sympy as sp
import numpy as np

A=np.array([[1,1],[1,2],[-2,-4]])
sp.Matrix(A)

enter image description here

B = np.hstack((A,np.array([[0],[0],[0]])))
sp.Matrix(B)

enter image description here

def determinant(A):
  if len(sp.Matrix(A).rref()[1]) < max(np.shape(A)):
    return 0
  else:
    return np.linalg.det(A)

determinant(A)
0
determinant(B)
0
np.linalg.det(A)  -----> ERROR
相关问题