Skip to content
Prev 65544 / 398506 Next

a==0 vs as.integer(a)==0 vs all.equal(a,0)

On Tue, 8 Mar 2005 09:03:43 +0000, Robin Hankin
<r.hankin at soc.soton.ac.uk> wrote :
When you say it isn't legitimate, you mean that it violates the advice
never to use exact comparison on floating point values?

I think that's just advice, it's not a hard and fast rule.  If you
happen to know that the values being compared have been calculated and
stored exactly, then "==" is valid.  In your function, when a and b
are integers that are within some range (I'm not sure what it is, but
it approaches +/- 2^53), the %% operator should return exact results.
(Does it do so on all platforms?  I'm not sure, but I'd call it a bug
if it didn't unless a and/or b were very close to the upper limit of
exactly representable integers.)

Do you know of examples where a and b are integers stored in floating
point, and a %% b returns a value that is different from as.integer(a)
%% as.integer(b)?
I'd suggest

(5) Use your gcd function almost as above, but modified to work on
vectors:

   gcd <- function(a, b){
     result <- a
     nonzero <- b != 0
     if (any(nonzero))
       result[nonzero] <- Recall(b[nonzero], a[nonzero] %% b[nonzero])
     return(result)
   }
I'd say not.  Your original function returns integer when both a and b
are stored as integers, and double when at least one of them is not.
That seems like reasonable behaviour to me.

Duncan Murdoch