可能重复:
为什么这些数字不相等?
我遇到了一个非常奇怪的情况。如果我使用以下代码将向量(序列)存储在文本文件中:
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)
然后再次加载:
test=readLines('test.txt')
然后,我尝试提取存储在文本文件中的相同向量,并使用 2 种“不同”方法与原始序列进行比较:
sequence1=laply(strsplit(test[2]," ")[[1]],as.numeric)
sequence2=as.numeric(strsplit(test[2]," ")[[1]])
奇怪的是,即使它们看起来和(显然)是相同类型的向量,R 似乎认为它们不是!!!
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
有没有人知道为什么会发生这种情况以及我如何防止它发生?非常感谢!