As @joran mentioned, you will encounter floating point issues with == and != In any other language. One of the important aspects of them in R is part of the vectorization.
It would be much better to define a new almostEqual , fuzzyEqual or similar function. Unfortunately, there is no such basic function. all.equal not very efficient, as it processes all kinds of objects and returns a string describing the difference when you just want TRUE or FALSE .
Here is an example of such a function. It is vectorized as == .
almostEqual <- function(x, y, tolerance=1e-8) { diff <- abs(x - y) mag <- pmax( abs(x), abs(y) ) ifelse( mag > tolerance, diff/mag <= tolerance, diff <= tolerance) } almostEqual(1, c(1+1e-8, 1+2e-8))
... it is about 2 times faster than all.equal for scalar values ββand much faster with vectors.
x <- 1 y <- 1+1e-8 system.time(for(i in 1:1e4) almostEqual(x, y)) # 0.44 seconds system.time(for(i in 1:1e4) all.equal(x, y)) # 0.93 seconds
Tommy
source share