[R] bug?

Mike Prager Mike.Prager at noaa.gov
Mon Jul 14 20:47:45 CEST 2003


At 7/14/2003 at 03:29 AM, Marc Vandemeulebroecke wrote:
>Dear R programmers,
>
>is there a sensible explanation for the following behaviour?
>
> > seq(0.7, 0.9, by=0.1) == 0.8
>[1] FALSE FALSE FALSE


As Uwe Ligges pointed out, most floating point numbers are not exactly 
representable in most bases.  Therefore, most floating-point comparisons 
for equality will not yield the common-sense results.

A reasonably short and free article that describes this in a bit more detail is

http://www.lahey.com/float.htm

As a result, a better way of doing such comparisons is something like this:

 > eps = 1e-6
 > aa = seq(0.7, 0.9, by=0.1)
 > abs(aa-0.8) < eps
[1] FALSE  TRUE FALSE

If the scales of numbers vary in a given computation, it can be better to 
compare abs((a-b)/(a+b)) to some epsilon, rather than just abs(a-b).

Hope that helps.


-- 
Michael Prager, Ph.D.                <Mike.Prager at noaa.gov>
NOAA Center for Coastal Fisheries and Habitat Research
Beaufort, North Carolina  28516
http://shrimp.ccfhrb.noaa.gov/~mprager/




More information about the R-help mailing list