Possible Duplicate:
Why are these numbers not equal?
I've come across a very bizarre situation. If I store a vector (sequence) in a text file with the following code:
fileConn<-file('test.txt')
sink(fileConn,append=T,split=T)
cat('sequence','\n')
cat(as.character(unlist(seq(0,1,0.1))),'\n')
sink()
close(fileConn)
And then load it again:
test=readLines('test.txt')
I then try and extract the same vector I've stored in the text file and compare to the original sequence using 2 "different" approaches:
sequence1=laply(strsplit(test[2]," ")[[1]],as.numeric)
sequence2=as.numeric(strsplit(test[2]," ")[[1]])
What's bizarre is that even though they look and (apparently) are the same type of vectors, R seems to think they're not!!!
cbind(seq(0,1,0.1),sequence1,sequence2)
sequence1 sequence2
[1,] 0.0 0.0 0.0
[2,] 0.1 0.1 0.1
[3,] 0.2 0.2 0.2
[4,] 0.3 0.3 0.3
[5,] 0.4 0.4 0.4
[6,] 0.5 0.5 0.5
[7,] 0.6 0.6 0.6
[8,] 0.7 0.7 0.7
[9,] 0.8 0.8 0.8
[10,] 0.9 0.9 0.9
[11,] 1.0 1.0 1.0
apply(cbind(seq(0,1,0.1),sequence1,sequence2),2,class)
sequence1 sequence2
"numeric" "numeric" "numeric"
apply(cbind(seq(0,1,0.1),sequence1,sequence2),2,nchar)
sequence1 sequence2
[1,] 1 1 1
[2,] 3 3 3
[3,] 3 3 3
[4,] 3 3 3
[5,] 3 3 3
[6,] 3 3 3
[7,] 3 3 3
[8,] 3 3 3
[9,] 3 3 3
[10,] 3 3 3
[11,] 1 1 1
sequence1==seq(0,1,0.1)
[1] TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE
sequence2==seq(0,1,0.1)
[1] TRUE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE
Does anybody have any clue why this happens and how I can prevent it from happening? Thanks very much!