为什么as.numeric转换字符时要加小数位?

Why does as.numeric add decimal places when converting a character?

第一行给出 0.1,第二行给出 0.10000000000000001。 为什么会这样?四舍五入是可行的解决方案吗?或者有更精确的解决方案吗? 我希望第一行是“0.1”,第二行是 0.1。

print(input[[nm]][[i+j]])
print(as.numeric(input[[nm]][[i+j]]))
[1] "0.1"
[1] 0.10000000000000001

这由您的选项中的 digits 设置控制。 options("digits") 将告诉您当前值,options(digits=8)(例如)将设置该值。最后的“额外”值是由于浮点错误(参见 The R Inferno or search Stack Overflow for question about floating point, e.g. this one 的第 1 章)。(请注意,这不会更改 基础值 ,只是它的打印方式。)

不可能用二进制浮点表示准确表达0.1。

这是使用不同数字设置打印的内容(看来您必须将 digits 设置为 17 ...)

x <- "0.1"
for (i in 1:20) print(c(i,as.numeric(x)), digits=i)
[1] 1.0 0.1
[1] 2.0 0.1
[1] 3.0 0.1
[1] 4.0 0.1
[1] 5.0 0.1
[1] 6.0 0.1
[1] 7.0 0.1
[1] 8.0 0.1
[1] 9.0 0.1
[1] 10.0  0.1
[1] 11.0  0.1
[1] 12.0  0.1
[1] 13.0  0.1
[1] 14.0  0.1
[1] 15.0  0.1
[1] 16.0  0.1
[1] 17.00000000000000000  0.10000000000000001
[1] 18.000000000000000000  0.100000000000000006
[1] 19.0000000000000000000  0.1000000000000000056
[1] 20.00000000000000000000  0.10000000000000000555

正如您在评论中所建议的那样,您可以使用 all.equal() 来测试 近似 相等性。 as.numeric(x)==0.1TRUEall.equal(as.numeric(x),0.1) 也是。您可以调整 all.equal():

的公差
z1 <- 0.1
z2 <- z1 + 1e-14
all.equal(z1,z2) ## TRUE
all.equal(z1,z2,tolerance=1e-15)
## [1] "Mean relative difference: 1.000589e-13"
isTRUE(all.equal(z1,z2,tolerance=1e-15)) ## FALSE