[R] strange behaviour with equality after simple subtraction

Mike Prager mike.prager at noaa.gov
Fri Jan 26 17:40:34 CET 2007


"martin sikora" <martin.sikora at upf.edu> wrote:

> today while trying to extract data from a list for subsequent analysis, i
> stumbled upon this funny behavior on my system:
> 
> > x<-c(0.1,0.9)
> 
> > 1-x[2]
> 
> [1] 0.1
> 
> > x[1]
> 
> [1] 0.1
> 
> > x[1]==1-x[2]
> 
> [1] FALSE
> 
> > x[1]>1-x[2]
> 
> [1] TRUE
> 

Not at all strange, an expected property of floating-point
arithmetic and one of the most frequently asked questions here.

> print(0.1, digits=17)
[1] 0.1
> print(1 - 0.9, digits=17)
[1] 0.09999999999999998
> 

A simple description of the issue is at

http://docs.python.org/tut/node16.html

In most cases, it suffices to test for approximate difference or
relative difference. The former would look like this

if (abs(x[1] - x[2]) < eps)) ...
 
with "eps" set to something you think is an insignificant
difference, say 1.0e-10.


-- 
Mike Prager, NOAA, Beaufort, NC
* Opinions expressed are personal and not represented otherwise.
* Any use of tradenames does not constitute a NOAA endorsement.



More information about the R-help mailing list