Skip to content
Prev 55797 / 63424 Next

Modification-proposal for %% (modulo) when supplied with double

On 11/09/2018 11:23 AM, Emil Bode wrote:
I think this is a bad idea.  Your comments say "The 
\code{\link[base:Arithmetic]{`\%\%`}} operator calculates the modulo, 
but sometimes has rounding errors, e.g. "\code{(9.1/.1) \%\% 1}" gives ~ 
1, instead of 0."

This is false.  The %% calculation is exactly correct.  The rounding 
error happened in your input:  9.1/0.1 is not equal to 91, it is a 
little bit less:

 > options(digits=20)
 > 9.1/.1
[1] 90.999999999999985789

And %% did not return 1, it returned the correct value:

 > (9.1/.1) %% 1
[1] 0.99999999999998578915

So it makes no sense to change %%.

You might argue that the division 9.1/.1 is giving the wrong answer, but 
in fact that answer is correct too.  The real problem is that in double 
precision floating point the numbers 9.1 and .1 can't be represented 
exactly.  This is well known, it's in the FAQ (question 7.31).

Duncan Murdoch