0

Here I have a 3 x 3 matrix and have calculated the determinant of the matrix and the determinant of the transpose of the matrix (which should be and are the same according to the code) but when comparing them to check if they are equal I am getting an output of false.

This is also true if I assign the values to other variables and check them.

Here is my code:

matrixTest <- matrix(
  c(c(1,5,7),c(1,2,6),c(8,2,6)),
  ncol = 3,
)

det(matrixTest)
det(t(matrixTest))

det(matrixTest) == det(t(matrixTest))

Output from R studio when running this block:

> det(matrixTest)
[1] 112
> det(t(matrixTest))
[1] 112
> 
> det(matrixTest) == det(t(matrixTest))
[1] FALSE
ajax2112
  • 228
  • 1
  • 6
  • I suspect the same issue as here: https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal – Jon Spring Oct 20 '19 at 02:41
  • 1
    Yep. Try `sprintf("%.15f", det(matrixTest))` and `sprintf("%.15f", det(t(matrixTest)))` You'll see that the two numbers are slightly different many digits down due to how floating point numbers work. In a situation like this, it's more informative to use `all.equal(det(matrixTest), det(t(matrixTest)))`, since it allows for some imprecision in how the number is stored. – Jon Spring Oct 20 '19 at 02:49

1 Answers1

1

This is due to floating point approximation:

det(matrixTest) - det(t(matrixTest))
## [1] -9.947598e-14

Use all.equal to compare whether two objects are equal to within a tolerance. See ?all.equal for more information.

all.equal(det(matrixTest), det(t(matrixTest)))
## [1] TRUE

In this particular case since the elements are all integer we know the result must be integer so another appraoch is to round both sides:

round(det(matrixTest)) == round(det(t(matrixTest)))
## [1] TRUE

There is also zapsmall:

zapsmall(det(matrixTest)) == zapsmall(det(t(matrixTest)))
## [1] TRUE
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Do you know of any resources where I can read about the way R handles situations like this? To learn how to avoid it in future. – ajax2112 Oct 20 '19 at 03:02
  • This is how floating point works in all languages, not just R, so any general discussion of floating point should do. Maybe Wikipedia's entry: https://en.wikipedia.org/wiki/Floating-point_arithmetic – G. Grothendieck Oct 20 '19 at 03:04
  • See informative answer from the question I linked above: https://stackoverflow.com/a/9508558/6851825 – Jon Spring Oct 20 '19 at 03:05