3

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?

ariankazemi
  • 105
  • 3
  • 14
  • `b`, which is here `-2.0000000000000004`, is not equal to `-2`. Are you trying to change the value of `b`, or check if it is `-2`? –  Dec 05 '21 at 17:12
  • 1
    Floating point error I believe. – kpie Dec 05 '21 at 17:21
  • Does this answer your question? [Precise determinant of integer NxN matrix](https://stackoverflow.com/questions/66192894/precise-determinant-of-integer-nxn-matrix) – user202729 Dec 05 '21 at 17:27
  • For exact answers you could try sympy (making sure you avoid floats in the input). – JohanC Dec 05 '21 at 18:29

1 Answers1

2

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.

Ahmad Chaiban
  • 106
  • 10