[R] Rounding error in seq(...)

Duncan Murdoch murdoch at stats.uwo.ca
Wed Sep 30 21:04:47 CEST 2009


On 9/30/2009 2:50 PM, Michael Knudsen wrote:
> On Wed, Sep 30, 2009 at 8:44 PM, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> 
>> Why?  You asked for an increment of 1 in the second case (which is exactly
>> represented in R), then divided by 10, so you'll get the same as 0.3 gives
>> you.  In the seq() case you asked for an increment of a number close to but
>> not equal to 1/10 (because 1/10 is not exactly representable in R), so you
>> got something different.
> 
> Well, the problem is that I don't know how seq is implemented. I just
> assumed that it wouldn't behave like this.

It doesn't really matter how it is implemented:  if you ask to start at 
0.1 and increment by 0.1, you should expect the result to be the same as

0.1
0.1+0.1
0.1+0.1+0.1
etc.

and I think it is.  The problem is that 0.1+0.1+0.1 is not the same as 
0.3, due to rounding.  Neither 0.1 nor 0.3 can be represented exactly in 
the standard IEEE floating point formats that R uses.

Duncan Murdoch




More information about the R-help mailing list