How to Get the Determinant of a Matrix in Python using Numpy



Python


In this article, we show how to get the determinant of a matrix in Python using the numpy module.

The determinant of a matrix is a numerical value computed that is useful for solving for other values of a matrix such as the inverse of a matrix. To obtain the inverse of a matrix, you multiply each value of a matrix by 1/determinant.

Therefore, knowing how to calculate the determinant can be very important.

Luckily, with Python and the numpy module, you don't have to actually know how to calculate the determinant mathematically. Python can just do this for you. All you need to know how to do is how to obtain the determinant of a matrix using Python.

So to obtain the determinant of a matrix with Python, the following code can be used, shown below.



So let's now go over the code.

So the first thing we must do is import the numpy module. We do so with the line, import numpy.linalg as m. The reason we put, as m, is so that we don't have to reference numpy each time; we can just use m.

We then create a variable called matrix1 and set it equal to, np.matrix([[8,2],[4,6]])

It's a 2x2 matrix, 2 rows and 2 columns.

We then are able to get the determinant of the matrix using the line, m.det(matrix1) This gives us the answer, 39.999999999999979

How does the numpy module of Python compute this?

Well to determine the determinant of a 2x2 matrix, you cross multiply first from the first element of the first row diagonally and then minus the product of the second element of the first row diagonally. This gives us, (8)(6)-(2)(4)= 40

I'm not sure why numpy computes the answer as, 39.999999999999979, instead of 40.0. It may be an internal programming error. So to fix this, all you have to do is use the Python round() function.

Let's now do an example of a 3x3 matrix.

This is shown in the code below.



Numpy can find the matrix of other matrices other than 2x2 matrices.

So mathematically how numpy computes the determinant of a 3x3 array is by the following, 8(18-45) -2(12-9) + 7(20-6)= -124.

Again, it gives us the answer, -123.99999999999991, which we can round to -124.0 with the round() function.

If you want the number to be returned as an integer, then you can type cast it using the int() function.

Remember that when computing the determinant of a matrix in Python, the matrix must be a square matrix, i.e, 2x2, 3x3, 4x4,5x5, etc.

It cannot be nonsquare such as 2x3, 2x4, etc.

If you attempt to find the determinant of a nonsquare matrix with numpy, an error will be thrown.

This can be seen in the example below.



And this is how you can obtain the determinant of a matrix in Python using numpy.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...