[R] %in% not working

Neil Klepeis nklepeis at uclink4.berkeley.edu
Mon Nov 4 22:33:18 CET 2002


Barry Rowlingson wrote:
>  > as.character(1e-4) == as.character(0.0001+.000000000000000000000001)
> [1] TRUE
> 
>  - as.character gets it wrong -
> 
>  Wheras:
> 
>  > 1e-4 == 0.0001+.0000000000000000001
> [1] FALSE
> 
>  - plain old numbers gets it right.
> 
>  Far better to understand what is going on with floating point numbers 
> and their inherent imprecision, and then work round it!



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.


-- 
______________________________________________________
Neil E. Klepeis, UC Berkeley, School of Public Health,
and Lawrence Berkeley National Laboratory,
Berkeley, CA USA.  Voice: 831-768-9510


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list