From murdoch at stats.uwo.ca  Mon Mar 16 15:12:51 2009
From: murdoch at stats.uwo.ca (Duncan Murdoch)
Date: Mon, 16 Mar 2009 10:12:51 -0400
Subject: [Rd] Match .3 in a sequence
In-Reply-To: <48f8cced0903160636k112500f6k4b8d46c1ac775d89@mail.gmail.com>
References: <48f8cced0903160636k112500f6k4b8d46c1ac775d89@mail.gmail.com>
Message-ID: <49BE5E63.9010800@stats.uwo.ca>

On 3/16/2009 9:36 AM, Daniel Murphy wrote:
> Hello:I am trying to match the value 0.3 in the sequence seq(.2,.3). I get
>> 0.3 %in% seq(from=.2,to=.3)
> [1] FALSE
> Yet
>> 0.3 %in% c(.2,.3)
> [1] TRUE
> For arbitrary sequences, this "invisible .3" has been problematic. What is
> the best way to work around this?

Don't assume that computations on floating point values are exact. 
Generally computations on small integers *are* exact, so you could 
change that to

3 %in% seq(from=2, to=3)

and get the expected result.  You can divide by 10 just before you use 
the number, or if you're starting with one decimal place, multiply by 10 
*and round to an integer* before doing the test.  Alternatively, use 
some approximate test rather than an exact one, e.g. all.equal() (but 
you'll need a bit of work to make use of all.equal() in an expression 
like 0.3 %in% c(.2,.3)).

Duncan Murdoch



[Rd] Match .3 in a sequence
Duncan Murdoch