Re: [Rd] Dangerous Bug with IF function of R

From: Petr Savicky <savicky_at_cs.cas.cz>
Date: Mon, 18 Apr 2011 19:25:36 +0200

On Mon, Apr 18, 2011 at 09:12:41AM -0700, salmajj wrote:
> hi!
> there is a bug with the IF operator that is really dangerous!
> please try the code below and if someone could explain to me why when (q is
> equal to 0.8, 0.9 or 1) R do not print it?
>
> q=0
> for (j in 1:11){
>
> if ((q==1)){
> print(q)
> }
> q=q+0.1
> }
>
> so in this code q is incremented from 0 to 1.1. but R do not capture print
> the value 1, 0.8 and 0.9 !! try to change (q==0.4) it gonna print 0.4. but
> if you put q==0.8 or 0.9 or 1 it doesn't work!!!
> please try it it is amazing!!!

Incrementing a number by 0.1 produces numbers, which are not exactly representable in binary, so this operation involves a rounding error. Try the following

  q=0
  for (j in 1:11){
    if ((q==1)){

       print(q)
    }                             

    q=round(q+0.1, digits=7)
  }

Petr Savicky.



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Mon 18 Apr 2011 - 17:29:32 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 18 Apr 2011 - 18:40:47 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive