Skip to content
Prev 24947 / 398502 Next

%in% not working

Barry Rowlingson wrote:
Not sure this was a fair example.  Consider the following, where we use 
the same arguments for numeric versus character comparisons:

 > 1e-4 == 0.0001+.000000000000000000000001
[1] TRUE
 > as.character(1e-4) == as.character(0.0001+.000000000000000000000001)
[1] TRUE
 > as.character(1e-4) == as.character(0.0001+.000000000000000001)
[1] FALSE
 > 1e-4 == 0.0001+.000000000000000001
[1] FALSE

Both "get it wrong" at high (false) precision and "get it right" at 
lower precision.

However, as pointed out earlier, the numeric comparison will often "get 
it wrong" when the numbers come from different calculations.  It seems 
that character comparisons will always "get it right" in terms of what 
my computer is able to resolve.  This seems to be the desired behavior 
when we want to know whether two numbers in a given calculation will 
really be treated differently by the computer.

`as.character()' is doing some implicit rounding with respect to machine 
precision.  If my machine can't really discern two decimal numbers, then 
as.character() will return them as the same (character) value.


 > .Machine$double.eps
[1] 2.220446e-16


"Outside" machine precision:

 > as.character(0.0001+.000000000000000000000001)
[1] "1e-04"


"Inside" machine precision:

 > as.character(1e-4)
[1] "1e-04"
 > as.character(0.0001+.000000000000001)
[1] "0.000100000000001"


Using as.character() is more convenient and/or general (portable?) than 
rounding off each side or explicitly using a tolerance in comparisons. 
  And it seems to be working for me so far.