modulus bug in R
10,516
In addition to @joshua Ulrich's comment
from ?'%%'
%% and x %/% y can be used for non-integer y, e.g. 1 %/% 0.2, but the results are subject to representation error and so may be platform-dependent. Because the IEC 60059 representation of 0.2 is a binary fraction slightly larger than 0.2, the answer to 1 %/% 0.2 should be 4 but most platforms give 5.
also similar to why we get this
> .1 + .1 + .1 == .3
[1] FALSE
as @Ben Boker pointed out, you may want to use something like
> 3:8 %% 2 / 10
[1] 0.1 0.0 0.1 0.0 0.1 0.0
Author by
mike
Updated on June 09, 2022Comments
-
mike almost 2 years
Possible Duplicate:
Why are these numbers not equal?Just noticed this bug in R. I'm guessing it's the way 0.6 is represented, but anyone know exactly what's going on?
According to R:
0.3 %% 0.2 = 0.1 0.4 %% 0.2 = 0 0.5 %% 0.2 = 0.1 **0.6 %% 0.2 = 0.2** 0.7 %% 0.2 = 0.1 0.8 %% 0.2 = 0
What's going on?
-
Ben Bolker over 11 yearsand (as pointed out in a now-deleted answer) the 'solution' is to use integer arithmetic if possible:
6 %% 2
instead of0.6 %% 0.2
-
mike over 11 yearsYep, ended up doing that. Thanks.
-
theEricStone about 10 yearsthis seems to work:
Mod <- function(n,m){ if( m >= n ) return(n); n.digits <- nchar(strsplit(paste(n),".",fixed=T)[[1]][2]); div <- floor(n/m); rem <- n - (div * m); return(round(rem,n.digits)) }