Skip to content

Dangerous Bug with IF function of R

6 messages · Brian Diggs, Petr Savicky, salmajj +2 more

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

--
View this message in context: http://r.789695.n4.nabble.com/Dangerous-Bug-with-IF-function-of-R-tp3457976p3457976.html
Sent from the R devel mailing list archive at Nabble.com.
#
On 4/18/2011 9:12 AM, salmajj wrote:
It is not a bug.  It a misunderstanding on your part of the limits of 
floating point arithmetic.  See FAQ 7.31 (and multiple previous 
discussions on this and the r-help list).

http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f

  
    
#
On Mon, Apr 18, 2011 at 09:12:41AM -0700, salmajj wrote:
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.
#
> Thanks a lot Petr it works!!!  
of course ..

    > You know for someone who is used to work with matlab it is not so obvious:)

well, what do you mean with that?

I'm intrigued. After such a blatantly wrong claim about a bug in
R...  what exactly are you claiming about Matlab here?
That it implements (software) decimal arithmetic on top of the
cpu-internal binary arithmetic ?   probably rather not ...

So?
#
Just for confirmation the same thing doesn't work in MATLAB as one would expect.

i=0;
for j=1:11
i=i+0.1;
if i==1
i
end
end