Let’s learn together how to calculate determinant of matrix using python Numpy library.

To calculate 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)}")

I created my an example matrix a called it my_matrix. Then I used 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 roundind results. Otherwise the result will be more like 65.99999999999997. The reason is that Numpy is calculating numerically and not analytically. That’s why the results which are not rounded up looks very strange and they are not very useful.

Sometimes it may happen that you will get a 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 errors tells you that it is something wrong with you matrix. Please check if the tuples are equal. Maybe some of them contains obsolete values?

The other type of errors is like 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 of the error is that the data type of matrix values is not the same. Probably one of them is a string. The data type of values in the matrix must be the same.

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