Skip to content

Inaccuracy in seq() (PR#9189)

3 messages · kellymj1 at cf.ac.uk, Roger Bivand, Brian Ripley

#
Full_Name: Mark James Kelly
Version: 2.3.1
OS: Windows
Submission from: (NULL) (193.63.127.224)


Sequence produces slightly inaccurate results. 

#This (supposedely) creates a sequence 0.060,0.065,0.070.....0.30
thingnor=(seq(0.06,0.30,by=0.005))

#This does the same but rounds to three decimals
thingrou=round(seq(0.06,0.30,by=0.005),3)

#This is another vector, the same length as the two above, with 24 zeroes, then
0.070, then 24 zeroes
otherthing=c(rep(0,24),0.070,rep(0,24))


#This fails to select the entries equal to 0.070 
otherthing[otherthing==thingnor[3]]

#This gives the correct answer
otherthing[otherthing==thingrou[3]]


#This compares the two sequences (which should be identical)
(thingnor-thingrou)
#
On Wed, 30 Aug 2006 kellymj1 at cf.ac.uk wrote:

            
Not a bug, but a FAQ (7.31):

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

Try:

otherthing[25]==thingnor[3]
identical(otherthing[25], thingnor[3])
all.equal(otherthing[25], thingnor[3])

?all.equal

  
    
#
See the FAQ Q7.31: 0.07 is not exactly representable on your computer.

0.060 + 2*0.005 != 0.070 in computer arithmetic:
[1] 0.06
[1] 0.070000000000000007
[1] 0.06999999999999999
[1] -1.3877787807814457e-17
[1] 1.5543122344752193e-17
On Wed, 30 Aug 2006, kellymj1 at cf.ac.uk wrote:

            
sequence() is a different function in R.
Not according to FAQ Q7.31 and help("==").