无法索引使用 seq() 和 rep() 创建的向量的某些值

Cannot index certain values of vector created with seq() and rep()

我创建了一个包含从 0 到 1 的序列的向量 x,其中每个值都被复制 100 次。当我显示矢量时,它看起来很好。但是,索引不适用于 x 的所有唯一值。

x.seq <- seq(from = 0, to = 1, by = 0.01)
x <- rep(x.seq, each = 100)

x
x == 0.7
x == 0.70

x 显示预期结果,但是 x == 0.70 仅显示 FALSE。我很困惑,因为并非每个值都是如此。例如。尝试 x == 0.99,我得到了 100 TRUE 的预期结果。

令人惊讶的是,当我通过 unique() 尝试解决方法时,索引再次起作用:

unique(x)[71]     # as a workaround for x = 0.7
x == unique(x)[71]

有什么想法吗?

来自 help("==")

For numerical and complex values, remember == and != do not allow for the finite representation of fractions, nor for rounding error. Using all.equal with identical is almost always preferable. See the examples. (This also applies to the other comparison operators.)

我们 运行 遇到了一道数值题。

x.seq[71] - 0.7
# [1] 1.110223e-16

seq.default的来源来看,seq(from = 0, to = 1, by = 0.01)的第71个值是0 + 70 * 0.01,而70 * 0.01 == 0.7在我的机器上确实是FALSE