Search code examples
pythonpython-3.xnumpymathdeterminants

Exact Value In Determinant Using Numpy


I want to compute the determinant of a 2*2 matrix , and I use linalg.det from Numpy like this:

import numpy as np
a = np.array([
[1,2],
[3,4]
])
b=np.linalg.det(a)

In other hand, We know that we also can compute it by a multiplication and a subtract like this:

1*4 - 2*3 = -2

But when I set b equal to -2 :

b == -2

It returns false.

What is the problem here? And How can I fix it?


Solution

  • If you're working with integers, you can use

    b = int(np.linalg.det(a))
    

    To just make it into an integer. This should give you the following

    int(b) == -2 ## Returns True
    

    Edit: This doesn't work if the approximation is something like -1.99999999999. As per JohanC in the comments below, try using int(round(b)) instead.