From Ted.Harding at nessie.mcc.ac.uk  Wed May 11 21:24:52 2005
From: Ted.Harding at nessie.mcc.ac.uk ( (Ted Harding))
Date: Wed May 11 21:37:32 2005
Subject: [Rd] bug in modulus operator %% (PR#7852)
In-Reply-To: <x2ekcdpqh6.fsf@turmalin.kubism.ku.dk>
Message-ID: <XFMail.050511202452.Ted.Harding@nessie.mcc.ac.uk>

On 11-May-05 Peter Dalgaard wrote:
> kjetil@acelerate.com writes:
> 
>> The following can't be right,
>> first rw2010:
>> 
>>  > 1 %% 0.001
>> [1] 0.001
>> 
>> Then rw2001:
>> 
>>  > 1 %% 0.001
>> [1] -2.081668e-17
>>  >
>> 
>> and the last seems about right.  
> 
> A negative remainder? I don't think so. Presumably the result comes
> from
> 
>     o   %% now warns if its accuracy is likely to be affected by lack
>         of precision (as in 1e18 %% 11, the unrealistic expectation of
>         PR#7409), and tries harder to return a value in range when it
>         is.
> 
> So, not a bug.

Agreed! One should always be aware of such fuzzy edges in any case
where the mathematical result depends on mathematically exact
representation, as here.

In such cases what I often do is on the lines of

  ((1000*x)%%(1000*y))/1000

Using R-2.1.0beta, first of all I get the same as Kjetil:

  1 %% 0.001
  ## [1] 0.001

Secondly I get

  (1000*1)%%(1000*0.001)
  ## [1] 0

Although this trick does not guarantee the exact result, it
makes it more likely; and also, any little inexactness will
now show up more clearly since in the form

  ((BIG*x) %% (BIG*y))/BIG

the possible discrepancy before division by BIG is at most y
in magnitude. While the properties of this trick are not
entirely transparent, one can for instance compare the result
of using it with the result of not using it, and then come
to a decision as to which to use.

A further example on the same lines is

  1 %% (0.00001)
  #  [1] 1e-05

(Similar to Kjetil's first example), while

  ((1000*1) %% (1000*0.00001))/1000
  ## [1] -2.081668e-17

Any comments would be interesting!

Best wishes,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding@nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 11-May-05                                       Time: 20:13:22
------------------------------ XFMail ------------------------------


[Rd] bug in modulus operator %% (PR#7852)
 (Ted Harding