[R] Inconsistency using seq

Petr Savicky savicky at cs.cas.cz
Tue Jun 19 07:12:43 CEST 2012


On Mon, Jun 18, 2012 at 12:58:13PM -0700, hamoreno wrote:
> Hi all,
> 
> Is there any problem of precision when using seq?. For example:
> 
> x<- seq(0,4,0.1)
> x[4]=0.3
> 
> BUT:
> 
> x[4]-0.3=5.551115e-17
> 
> It means when I use this condition within an if clause, it does not find
> values with 0.3 for x[4] as it is not precisely 0.3.

Hi.

Using round() is reasonably secure.

  x <- round(seq(0,4,0.1), digits=7)
  x[4] == 0.3
  [1] TRUE

None of the compared nunbers is 0.3, but they are both rounded
to the closest representable number to 0.3. 

  print(x[4], digits=20)

  [1] 0.2999999999999999889

  print(0.3, digits=20)

  [1] 0.2999999999999999889

See also

  http://rwiki.sciviews.org/doku.php?id=misc:r_accuracy

for some more hints related to this.

Petr Savicky.



More information about the R-help mailing list