[R] odd behaviour of %%?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Nov 22 11:37:11 CET 2006


"Jonathan Williams" <jonathan.williams at pharmacology.oxford.ac.uk> writes:

> Dear R Helpers,
> 
> I am trying to extract the modulus from divisions by a sequence of
> fractions.
> I noticed that %% seems to behave inconsistently (to my untutored eye),
> thus:
> 
> > 0.1%%0.1
> [1] 0
> > 0.2%%0.1
> [1] 0
> > 0.3%%0.1
> [1] 0.1
> > 0.4%%0.1
> [1] 0
> > 0.5%%0.1
> [1] 0.1
> > 0.6%%0.1
> [1] 0.1
> > 0.7%%0.1
> [1] 0.1
> > 0.8%%0.1
> [1] 0
> > 0.9%%0.1
> 
> The modulus for 0.1, 0.2, 0.4 and 0.8 is zero, as I'd expect. But, the
> modulus
> for 0.3, 0.6, 0.7 and 0.9 is 0.1 - which I did not expect. I can see no
> obvious
> rule that predicts whether x%%0.1 will give an answer of 0 or 0.1.  I could
> find
> no explanation of the way that %% works in the R manuals. So, I have 3
> questions:-
> 
> 1) Why is the modulus of 0.3%%0.1 (and 0.5%%0.1 and 0.6%%0.1...) not zero?
> 2) Are there any algorithms in R that use the %% operator with fractional
> divisors
> in this way, and do they know about its apparently inconsistent behaviour?
> 3) If %% is not intended for use with fractional divisors, then would it be
> a
> good idea to trap attempts to use them?

These are not fractions but floating point numbers. See FAQ 7.31

http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f

and the references therein for reasons why 0.3 is not an integer
multiple of 0.1 in binary. etc.

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list