Python Determinant of a Matrix

				
					import numpy as np
from numpy.linalg import det
				
			

2x2 Example

				
					matrix = np.array([[4, 7], [2, 6]])
matrix_det = det(matrix)
				
			
				
					print(matrix_det)
				
			

3x3 Example

				
					matrix = np.array([[3, 8, 1], [4, 6, 9], [7, 5, 2]])
matrix_det = det(matrix)
				
			
				
					print(matrix_det)
				
			
singular matrix
				
					matrix_singular = np.array([[8, 4], [4, 2]])
				
			
				
					matrix_det_singular = det(matrix_singular)
				
			
				
					print(matrix_det_singular)
				
			
				
					if np.isclose(np.linalg.det(matrix_singular), 0):
    print("Matrix is singular, inverse cannot be computed.")
else:
    np.linalg.inv(matrix_singular)
				
			
identity matrix
				
					I = np.identity(3)
				
			
				
					det_I = np.linalg.det(I)
				
			
				
					print(det_I)
				
			
The determinant of a product of matrices satisfies det(AB)=det(A)⋅det(B)
				
					A = np.array([[2, 1], [3, 4]])
				
			
				
					det_A = np.linalg.det(A)
				
			
				
					print(det_A)
				
			
				
					B = np.array([[0, 5], [6, 7]])
				
			
				
					det_B = np.linalg.det(B)
				
			
				
					print(det_B)
				
			
				
					det_AB = np.linalg.det(np.dot(A, B))
				
			
				
					print(det_AB)
				
			
Swapping two rows (or columns) of a matrix multiplies the determinant by − 1
				
					A_swapped = np.array([[3, 4], [2, 1]])  # Swap rows of A
				
			
				
					det_A_swapped = np.linalg.det(A_swapped)
				
			
				
					print(det_A_swapped)
				
			
Eigenvalues of A and their product
				
					eigenvalues_A, _ = np.linalg.eig(A)
				
			
				
					eigenvalues_product = np.prod(eigenvalues_A)
				
			
				
					print(eigenvalues_product)
				
			
Scale A by a scalar k and compute determinant
				
					k = 3
				
			
				
					scaled_A = k * A
				
			
				
					print(A)
				
			
				
					print(scaled_A)
				
			
				
					det_scaled_A = np.linalg.det(scaled_A)
				
			
				
					print(det_scaled_A)
				
			
				
					print(det_A)
				
			
the shape attribute of a numpy array provides the dimensions of the array as a tuple
				
					scaled_det = (k ** A.shape[0]) * det_A
				
			
				
					A.shape[0]
				
			
				
					print(scaled_det)
				
			

python determinant without numpy

Coming soon on the website.

Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.

Leave a Reply

Your email address will not be published. Required fields are marked *