0

currently learning some basics in R. I have encountered a problem where R does not identify two (seemingly) identical matrices as indentical.

K <- rbind(c(63,32,32),c(69,20,31),c(58,41,30))
L <- rbind(c(36,35,65),c(61,39,36),c(43,67,25))

c3 <- solve(K%*%L)
c4 <- (solve(L)%*%solve(K))

This is the return for c3

> c3
             [,1]         [,2]         [,3]
[1,] -0.008210912  0.002098811  0.006187541
[2,]  0.019277529 -0.007768868 -0.011693360
[3,] -0.010079058  0.005248454  0.005097116

This is the return for c4

> c4
             [,1]         [,2]         [,3]
[1,] -0.008210912  0.002098811  0.006187541
[2,]  0.019277529 -0.007768868 -0.011693360
[3,] -0.010079058  0.005248454  0.005097116

The typeof and class of both c3 and c4 is the same. Yet this happens:

> c3 == c4
      [,1]  [,2]  [,3]
[1,] FALSE FALSE FALSE
[2,] FALSE FALSE FALSE
[3,] FALSE FALSE FALSE
tshelky
  • 1
  • 1
  • 2
    Roundoff error. Try `options(digits=13)` and the print out both matrices. Also, take a look at [Why are these numbers not equal?](https://stackoverflow.com/q/9508518/4752675) – G5W Mar 16 '21 at 16:29

1 Answers1

2

The code is using floating point arithmetic which is not exact. Different approaches can result in slightly different values if you look at enough decimals.

c3-c4
##               [,1]          [,2]          [,3]
## [1,] -1.214306e-17  1.734723e-18  1.040834e-17
## [2,]  6.938894e-18  5.204170e-18 -1.214306e-17
## [3,]  5.204170e-18 -7.806256e-18  8.673617e-19

Ignoring small differences they are the same:

all.equal(c3, c4)
## [1] TRUE

See http://www.hep.by/gnu/r-patched/r-faq/R-FAQ_82.html

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341