Incorrect boolean return for simple sequence

Here is the base code and its output. I really can't say anything more than a logical test for a sequence containing 1.2 gives an inaccurate result. It works for many other values.

# Incorrect > seq(0.5, 1.5, by=0.05) == 1.2 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE # Correct > seq(0.5, 1.5, by=0.05) == 1.15 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE # Correct > seq(0.5, 1.5, by=0.05) == 1.25 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE # Correct > seq(0.5, 1.5, by=0.05) == 1.3 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE 

I tried to check all the values ​​using the following which does not reproduce the error:

 > sapply(seq(0.5, 1.5, by=0.05), function(x){sum(seq(0.5, 1.5, by=0.05) == x)}) [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 

I am using R version 2.13.2 (2011-09-30), platform: x86_64-pc-linux-gnu (64-bit).

+1
source share
1 answer

You can duplicate what all.equal does by writing your own comparison function:

 is.nearenough=function(x,y,tol=.Machine$double.eps^0.5){ abs(xy)<tol } 

then you can do that (is.nearenough (s, 1.2)), where s is your sequence. You may need to configure access tolerance for your application.

+4
source

All Articles