Re: [R] %in% not working

About this list Date view Thread view Subject view Author view Attachment view

From: Thomas Lumley (tlumley@u.washington.edu)
Date: Sat 02 Nov 2002 - 02:08:46 EST


Message-id: <Pine.A41.4.44.0211010706051.71068-100000@homer19.u.washington.edu>

On 1 Nov 2002, Peter Dalgaard BSA wrote:

> Neil Klepeis <nklepeis@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@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Tue 01 Jun 2004 - 09:31:35 EST