We will learn together how to calculate the determinant of a matrix using Python’s Numpy library.

## Calculating a determinant

To calculate the determinant, you need to use linear algebra. It offers a dedicated det function, thanks to which it is very easy to calculate a determinant.

import numpy as np my_matrix = np.array([(10, 2), (7, 8)]) determinant = np.linalg.det(my_matrix) print(f"Determinant equals {round(determinant, 2)}")

## Explanation

I created an example matrix and called it my_matrix. Then I used the np.linalg.det function, which takes my_matrix as an argument.

Finally I printed out the result, which I rounded to the two decimal places. I recommend rounding results. Otherwise, the result will be more like 65.99999999999997. The reason is that Numpy calculates numerically and not analytically. That’s why the results, which are not rounded up look very strange and they are not very useful.

## Dealing with errors

Sometimes it may happen that you will get an error like:

raise LinAlgError('%d-dimensional array given. Array must be ' numpy.linalg.LinAlgError: 1-dimensional array given. Array must be at least two-dimensional

That kind of error tells you that there is something wrong with your matrix. Please check if the tuples are equal. Maybe some of them contain obsolete values?

The other type of error is like the below one:

r = _umath_linalg.det(a, signature=signature) TypeError: No loop matching the specified signature and casting was found for ufunc det

This one is not so obvious because it does not tell much. The reason for the error is that the data type of matrix values is not the same. One of them is probably a string. The data type of all values in the matrix must be the same.

I hope you find this tutorial useful and you are able to calculate determinants in Numpy like a pro.