computing determinant of a matrix (nxn) recursively

前端 未结 5 1066
心在旅途
心在旅途 2021-01-19 05:26

I\'m about to write some code that computes the determinant of a square matrix (nxn), using the Laplace algorithm (Meaning recursive algorithm) as written Wikipedia\'s Lapla

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 06:09

    Here's the function in python 3.

    Note: I used a one-dimensional list to house the matrix and the size array is the amount of rows or columns in the square array. It uses a recursive algorithm to find the determinant.

    def solve(matrix,size):
        c = []
        d = 0
        print_matrix(matrix,size)
        if size == 0:
            for i in range(len(matrix)):
                d = d + matrix[i]
            return d
        elif len(matrix) == 4:
            c = (matrix[0] * matrix[3]) - (matrix[1] * matrix[2])
            print(c)
            return c
        else:
            for j in range(size):
                new_matrix = []
                for i in range(size*size):
                    if i % size != j and i > = size:
                        new_matrix.append(matrix[i])
    
                c.append(solve(new_matrix,size-1) * matrix[j] * ((-1)**(j+2)))
    
            d = solve(c,0)
            return d
    

提交回复
热议问题