[Rd] Match .3 in a sequence
Duncan Murdoch
murdoch at stats.uwo.ca
Mon Mar 16 15:12:51 CET 2009
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
More information about the R-devel
mailing list