From savicky at cs.cas.cz  Wed Feb 25 18:08:25 2009
From: savicky at cs.cas.cz (Petr Savicky)
Date: Wed, 25 Feb 2009 18:08:25 +0100
Subject: [Rd] invalid comparison in numeric sequence (PR#13551)
In-Reply-To: <OF9C09A16C.3B7C2CC8-ON85257568.004C675A-85257568.004C676F@american.edu>
References: <20090224135524.0113D284A70B@mail.pubhealth.ku.dk>
	<OF9C09A16C.3B7C2CC8-ON85257568.004C675A-85257568.004C676F@american.edu>
Message-ID: <20090225170825.GA23092@cs.cas.cz>

> > seq(0,1,0.1)==0.4
>  [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
> > seq(0,1,0.1)==0.6
>  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> > seq(0,1,0.1)==0.8
>  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE
> 
> What is wrong with 0.6 ??? (TRUE is missing)
> I tried 3 differents computers (2 Ubuntu with R 2.8.1, and one Mac with R 2.8).

If you know that all the numbers in a sequence should have a given decimal
precision, then you obtain a better result using round(,digits=...).
For example,

  x <- round(seq(0,1,0.1), digits=1)
  rbind(x == 0.4, x == 0.6, x ==0.8)

produces

        [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10] [,11]
  [1,] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
  [2,] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
  [3,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE

This does not mean, that x[7] is now equal to 0.6, however both x[7] and 0.6
are represented by the same 53-bit floating point number

  formatC(x[7], digits=20) # "0.5999999999999999778"
  formatC(0.6, digits=20)  # "0.5999999999999999778"

Petr.



[Rd] invalid comparison in numeric sequence (PR#13551)
Petr Savicky