-3

I tried to calculate determinants of matrices in Spyder IDE, but the results made me suspicious about "scipy" for further study.

Here is the code I used:

import numpy as np
from scipy import linalg

matrix = np.array([[5.0, 9.0],[3.0, 5.0]], dtype=float)
det = linalg.det(matrix)
print(det)

and here is the output:

-1.999999999999999

Another matrix and its determinant:

import numpy as np
from scipy import linalg

matrix = np.array([[5.0, 12.0],[2.0, 5.0]], dtype=float)
det = linalg.det(matrix)
print(det)

Output:

1.000000000000001
Arda Kandemir
  • 49
  • 1
  • 1
  • 7
  • 1
    Please make sure to ask a question in the post itself, not just the title. It seems as though you consider that these results are wrong. Why? What do you think the results should be instead? Why? – Karl Knechtel May 11 '22 at 11:08
  • matrix = np.array([[5.0, 9.0],[3.0, 5.0]], dtype=float) 5 9 3 5 For this matrix, the determinant is: (5 * 5) - (9 * 3) = -2 but code gives: -1.999999999999999 matrix = np.array([[5.0, 12.0],[2.0, 5.0]], dtype=float) 5 12 2 5 For this matrix, the determinant is: (5 * 5) - (12 * 2) = 1 but code gives: 1.000000000000001 – Arda Kandemir May 11 '22 at 12:05
  • The determinant is computed from some decomposition like the LU decomposition. This here has only one row operation, subtract the first row times `3/5` from the second row. The factor is not a multiple of a power of 2, so you get rounding errors in `5-(3/5)*9=-0.39999999999999947` for the lower-right entry. This error is propagated to the determinant `-1.9999999999999973`. (This only shows that errors happen, even if it does not give the specific error.) – Lutz Lehmann May 12 '22 at 12:25

1 Answers1

2

You might want to look at this answer since it's a reccuring issue with float values:

What is the best way to compare floats for almost-equality in Python?

It is due to the way floats are implemented and sadly the only real option is to approximate or use a couple of int as a fraction. (i.e. tuple(numerator, denominator))

cfgn
  • 201
  • 2
  • 10