Skip to content
Prev 59395 / 398502 Next

Creating logical value from the difference of two absolute values

Nathan Leon Pace, MD, MStat wrote:
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.
On a Mac I get

 > abs(.7-.5) - abs(.3-.5)
[1] -5.551115e-17

so you need to make a relative comparison, not an absolute comparison. 
You could write the relative comparison using the all.equal function, 
such as

 > v1 <- abs(.7-.5)
 > v2 <- abs(.3-.5)
 > (v1 > v2) || all.equal(v1, v2)
[1] TRUE