%in% not working
On 1 Nov 2002, Peter Dalgaard BSA wrote:
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
Though it's a bit unintuitive that 1.253 %in% round(seq(1.1, 1.3,by=0.001), 3) is also FALSE. However, round(1.253,3) %in% round( seq(1.1, 1.3, by=0.001), 3) does work and should be more reliable. The optimistic version of Peter's general principle is that two real numbers will compare equal only if they were obtained by the same computation. -thomas -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- 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 _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._