[R] modulo operation

Duncan Murdoch murdoch.duncan at gmail.com
Thu Sep 9 14:10:12 CEST 2010


On 09/09/2010 7:56 AM, Barry Rowlingson wrote:
> 2010/9/9 "José M. Blanco Moreno" <jmblanco at ub.edu>:
>>  Dear R-users,
>> May be there is something that I am not understanding, missed or else...
>> Why do these operations yield these results?
>>> 25%/%0.2
>> [1] 124
>>> 25%%0.2
>> [1] 0.2
>>
>> I would expect (although I know that what I do expect and what is really
>> intended in the code may be different things)
>>> 25/0.2
>> [1] 125
>>> 25 - floor(25/0.25)*0.25
>> [1] 0
>>
>> (At least this second one is what I would expect from the code in
>> arithmetic.c, lines 168 to 178)
> 
> Did you read the documentation before you read the code?
> 
>      ‘%%’ and ‘x %/% y’ can be used for non-integer ‘y’, e.g. ‘1 %/%
>      0.2’, but the results are subject to rounding 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’.
> 
> I suspect that is relevant to your interests....
> 

Yes.  I think José is assuming that 25 %/% 0.2 and floor(25/0.2) are 
equal, but they are not, because rounding affects them differently. 
(The first is a single operation with no rounding except in the 
representation of 0.2; the second is two operations and is subject to 
another set of rounding.)

Duncan Murdoch



More information about the R-help mailing list