1

I am trying to get same result of this specific matrix, but they are returning slightly different result. Here is the image of example code: enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
Sourav Roy
  • 19
  • 5
  • 1
    R is treating the computation as integer type, Python as float – Gustav Rasmussen Jun 28 '20 at 11:23
  • @GustavRasmussen Not necessarily, in R `class(B[1,1])` returns `"numeric"` but `det(B)` is 8. Note: the matrix was created with `B <- diag(c(1,2,4))`. I dupe hammered without checking. – Rui Barradas Jun 28 '20 at 11:27
  • If you just need the same result in Python as in r, you could use math.ceil: `det = math.ceil(np.linalg.det(x)) ` – Gustav Rasmussen Jun 28 '20 at 11:34
  • 4
    They're both calling LAPACK's `dgetrf` and `sprintf("%0.17f", det(diag(c(1, 2, 4))))` in R shows `"7.99999999999999822"`... This seems to be just a case of differences in how they **display** the answer, not differences in what they answer **is**. Of course, the easy to see true value of the answer is 8, but, you know, [floating point arithmetic / representation of numbers](https://stackoverflow.com/q/9508518/8386140) and all... – duckmayr Jun 28 '20 at 11:48
  • 2
    If you use `identical(det(B), 8L)` you will get `FALSE` for result. Its just prinitng configuration. If you write `1.9999999` in console you will get `2` as output in console. I think that default parameter is `6` for decimal points (if you write `1.999999` you will get `1.999999`). – det Jun 28 '20 at 12:12

1 Answers1

1

In the numpy source code of the linag module can be read:

This module is a lite version of the linalg.py module in SciPy which contains high-level Python interface to the LAPACK library.

In the numpy documentation we find:

The determinant is computed via LU factorization using the LAPACK routine z/dgetrf.

Also, in the scipy documentation we find:

The determinant is computed via LU factorization, LAPACK routine z/dgetrf.

However, checking the numpy source code and scipy source code can be seen that the det functions are not calculated in the same way. scipy returns the desired output:

>>> import scipy
>>> scipy.linalg.det(B)
8.0
Gorka
  • 1,971
  • 1
  • 13
  • 28