0

In R, why is this false for y > 2?

y <- c(1, 2, 3, 4, 5)
x <- 2*y
exp(log(x)) == exp(log(y)) * 2
[1]  TRUE  TRUE FALSE FALSE FALSE
  • 8
    Floating point roundoff error. You'll notice that `exp(log(y))` is not exactly `3`. Have a read of [What Every Computer Scientist Should Know About Floating Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Chris Taylor Jul 15 '13 at 08:50
  • Thank you. In this case I know from theory that the results must be the same. How do I compare results in a case where I don't know if they should be equal? Impossible? –  Jul 15 '13 at 08:55
  • But `exp(log(y))` returns `[1] 1 2 3 4 5`, and `exp(log(x))` returns `[1] 2 4 6 8 10` which is exactly what was confusing me. –  Jul 15 '13 at 08:57
  • 1
    Use `sprintf("%.20f", exp(log(y)))` to get it displayed with more precision. – Roland Jul 15 '13 at 09:01

2 Answers2

4

Numeric precision. Try calculating the difference:

exp(log(x)) - exp(log(y)) * 2

You could use something like:

all.equal( exp(log(x)) , exp(log(y)) * 2 )
Jeroen Ooms
  • 31,998
  • 35
  • 134
  • 207
  • Or something like `apply(cbind(exp(log(x)), exp(log(y)) * 2), 1, function(tmp) all.equal(tmp[[1]],tmp[[2]]))` to check each element. – Roland Jul 15 '13 at 08:59
1

Exactly, the numerci precision is the cause. Try this, even simpler calculation

1/2+1/3+1/6 #equal to 1    
(1/2+1/3+1/6)-1 # should be 0
[1] -1.110223e-16
bartektartanus
  • 15,284
  • 6
  • 74
  • 102