[R] Rounding error in seq(...)
Duncan Murdoch
murdoch at stats.uwo.ca
Wed Sep 30 20:44:58 CEST 2009
On 9/30/2009 2:40 PM, Michael Knudsen wrote:
> Hi,
>
> Today I was flabbergasted to see something that looks like a rounding
> error in the very basic seq function in R.
>
>> a = seq(0.1,0.9,by=0.1)
>> a
> [1] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
>> a[1] == 0.1
> [1] TRUE
>> a[2] == 0.2
> [1] TRUE
>> a[3] == 0.3
> [1] FALSE
>
> It turns out that the alternative
>
>> a = (1:9)/10
>
> works just fine. Are there any good guides out there on how to deal
> with issues like this? I am normally aware of rounding errors, but it
> really surprised me to see that an elementary function like seq would
> behave in this way.
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.
Duncan Murdoch
More information about the R-help
mailing list