[R] %in% not working

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Nov 1 09:26:09 CET 2002


Neil Klepeis <nklepeis at uclink4.berkeley.edu> writes:

> I'm at a loss on this one:
> 
>  > c(1.253) %in% seq(1.1,1.3,by=0.001)
> [1] FALSE
>  > c(1.252) %in% seq(1.1,1.3,by=0.001)
> [1] TRUE
>  > c(1.254) %in% seq(1.1,1.3,by=0.001)
> [1] TRUE

"Never trust exact equality with floating point operations."

Finite decimal fractions are not finite binary fractions and if you
compute them in two different ways you'll very likely get differences
in the last few bits because of rounding errors.

> seq(1.1,1.3,by=0.001)[154]
[1] 1.253
> seq(1.1,1.3,by=0.001)[154]-1.253
[1] 2.220446e-16

It's not different in principle from the fact that in 3-digit decimal
arithmetic 1/3 * 3 = 0.333 * 3 = 0.999
-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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