# [R] erratic behavior of match()?

Henrik Bengtsson hb at stat.berkeley.edu
Thu Apr 19 23:51:12 CEST 2007

```...and so say google [http://www.google.com/search?q=1%250.1]:

"1 modulo 0.1 = 0.1",

so end of discussion ;)

In bit of a food coma now, but the following is interesting:

r = a %% b
<=>
r = (b*a/b) %% (b*b/b)
<=>
r = b*((a/b) %% 1)

> modulo <- function(a, b) { b * ((a/b) %% 1) }
> intdiv <- function(a, b) { as.integer(a/b - modulo(a,b)) }

> a <- 1
> b <- 0.1
> modulo(a, b)
 0
> stopifnot(all.equal(a, (a %% b) + b * (a %/% b)))
> stopifnot(all.equal(a, modulo(a, b) + b * intdiv(a,b)))

The question is, do we gain anything at all from this, i.e. is the set
of "odd" results larger or smaller than using a %% b, or is just a
different equally sized set of numbers?  ...and of course it will be a
matter of how we want to define modulo - mathematically or "IEEE
numerically".  Though, there is no such as thing as a free lunch, so
probably nothing to see here...

/Henrik

On 4/19/07, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> On 4/19/2007 4:29 PM, Bernhard Klingenberg wrote:
> > Thank you! Is floating point arithmetic also the reason why
> >
> > 1 %% 0.1
> >
> > gives the "surprising" answer 0.1 (because 0.1 cannot be written as a
> > fraction with denominator a power of 2, e.g. 1%%0.5 correctly gives 0).
> >
> > This seems to go a bit against the statement in the help for '%%', which
> > states "For real arguments, '%%' can be subject to catastrophic loss of
> > accuracy if 'x' is much larger than 'y', and a warning is given if this
> > is detected."
>
> I don't see the contradiction.  The statement is talking about one way
> to get imprecise results; you may have found another.
>
> However, I'm not sure if you can blame %% in your example:  the loss of
> precision probably came from the translation of "0.1" to the internal
> representation.  I think "0.1" ends up a little bit larger than 0.1
> after string conversion and rounding, so 1 %/% 0.1 should give 9, and 1
> %% 0.1 should give something very close to 0.1, as you saw.
>
> Duncan Murdoch
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help