Re: [Rd] Unexpected behaviour of seq(from,to,by) (PR#14057)

From: Petr Savicky <savicky_at_cs.cas.cz>
Date: Wed, 11 Nov 2009 13:29:50 +0100

> # Hi there.
> # I'm not sure whether or not this is a bug.

No, this is not a bug. See FAQ 7.31 at
  http://cran.r-project.org/doc/FAQ/R-FAQ.html and the comments below.

> # But it surely is an unexpected behaviour.
>
> V <- seq(from=0,to=1,by=0.1)
>
> # Should generate a sequence with a step of 0.1
>
> V==0
> # [1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> # Ok!
>
> V==0.1
> # [1] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> # Ok!
>
> V==0.6
> # [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> # None?
>
> V[7]
> # [1] 0.6
> V[7]==0.6
> # [1] FALSE
> # Rounding!?

Yes. The sequence of operations, which leads to V[7], produce slightly different rounding error than the direct conversion of 0.6 to binary representation. So, we have
  formatC(V[7], digits=20) # [1] "0.60000000000000008882"   formatC(0.6, digits=20) # [1] "0.5999999999999999778"

See
  http://wiki.r-project.org/rwiki/doku.php?id=misc:r_accuracy for more examples and explanations.

Petr Savicky.

> V[8]
> # [1] 0.7
> V[8]==0.7
> # [1] FALSE
> # Rounding!?
>
> V[9]
> # [1] 0.8
> V[9]==0.8
> # [1] TRUE
> # Back to normal
>
> # The generated sequence is fine for all values except for 0.6
> # and 0.7, which appear to be somewhat off the expected value.
>
> # According to the R manual the sequence is generated in the form:
> # from, from+by, ..., to
> # which is not the case.
>
> # Either the function or the documentation lead to an unexpected
> # behaviour of seq(from,to,by).
>
> # Thanks!
>
> ______________________________________________
> R-devel_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Wed 11 Nov 2009 - 12:35:11 GMT

This archive was generated by hypermail 2.2.0 : Wed 11 Nov 2009 - 14:40:23 GMT