简体   繁体   中英

How to find determinant of matrix using python

New at python and rusty on linear Algebra. However, I am looking for guidance on the correct way to create a determinant from a matrix in python without using Numpy. Please see the snippet of code below. Any assistance is greatly appreciated.

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 = []

sum is an inbuilt function and cannot be used as a variable name. The code was not properly indented. This should work:

def determinant(matrix, mul):

    width = len(matrix)
    if width == 1:
        return mul * matrix[0][0]
    else:
        sign = -1
        answer = 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
            answer = answer + mul * determinant(m, sign * matrix[0][i])
    return answer

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

print(determinant(test_matrix, 1))

This way you can get the determinant of non square matrix. Maybe it is a non sense, but I found it useful this implementation in jupyter notebook because avoids the need of using try for the exceptions and sometimes it's interesting to get a zero output for a not square matrix.

import sympy as sp
import numpy as np

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

在此处输入图片说明

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM