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

Petr Savicky savicky at cs.cas.cz
Wed Nov 11 13:29:50 CET 2009


> # 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
>



More information about the R-devel mailing list