How to get the determinant of a matrix using NumPy?

Learn, how to calculate/get the determinant of a matrix using NumPy in Python? By Pranit Sharma Last updated : December 23, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Determinant of a matrix

Mathematically, the determinant is a scalar value that is a function of the entries of a square matrix. It characterizes some properties of the matrix and the linear map represented by the matrix.

Problem statement

Suppose that we are given a numpy matrix and we need to find its determinant using numpy methods.

Calculating the determinant of a matrix using NumPy

To find the determinant of a matrix in NumPy, use the numpy.linalg.det() method which returns the determinant of a given array. Below is the syntax of numpy.linalg.det() method:

np.linalg.det(a)

The linalg is a module in numpy where linalg stands for "Linear algebra".

Let us understand with the help of an example,

Python code to calculate the determinant of a matrix using NumPy

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[1, 2], [3, 4]])

# Display original array
print("Original Array:\n",arr,"\n")

# Calculating determinant of the matrix
res = np.linalg.det(arr)

# Display result
print("Result:\n",res)

Output

Example: How to get the determinant of a matrix using NumPy?

Python code to calculate the determinant of a random matrix using NumPy

Here, we are creating a 2x2 random matrix and then finding its determinant.

import numpy as np

# Creating a matrix of 2x2 with random values
arr = np.random.randint(10, 20, (2, 2))

# Displaying original matrix
print("Original matrux:\n", arr, "\n")

# finding determinant of arr
result = np.linalg.det(arr)

# Printing
print("Determinant: \n", result)

Output

RUN 1:
Original matrux:
 [[11 19]
 [16 15]] 

Determinant: 
 -138.99999999999997

RUN 2:
Original matrux:
 [[10 11]
 [19 17]] 

Determinant: 
 -38.99999999999999 

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.