[R] Creating logical value from the difference of two absolute values
bates at stat.wisc.edu
Fri Nov 19 13:59:49 CET 2004
Nathan Leon Pace, MD, MStat wrote:
> Using R 2.0.1 on Mac g5 running Mac OS X 10.3.6.
> I would expect that
> abs(.7 - .5) >= abs(.3 - .5) should be returned TRUE.
> > www <- abs(.7 - .5) >= abs(.3 - .5)
> > www
>  FALSE
> Is this a result of floating point or the implementation of abs or
> something else?
Due to floating point arithmetic in general, not specifically the abs
function. The number .5 will have an exact floating point
representation but .3 and .7 will not. Making equality comparisons with
floating point values is always risky.
> In a function I need to compare two absolute values - each being of the
> form |variable - constant|.
On a Mac I get
> abs(.7-.5) - abs(.3-.5)
so you need to make a relative comparison, not an absolute comparison.
You could write the relative comparison using the all.equal function,
> v1 <- abs(.7-.5)
> v2 <- abs(.3-.5)
> (v1 > v2) || all.equal(v1, v2)
More information about the R-help