When creating the following code, the
seq1 <- seq(-1,0,0.1)
(-0.1) %in% seq1
I don’t understand why the output for this result is FALSE, when
-0.1 %in% c(-0.2, -0.1)
return an output of TRUE
Do you know why this behaviour?
>Solution :
This is due to floating point approximation. Any computer language that uses floating point hardware will use such appromiations. Print out the values using a large number of significant digits to see what the values are. There is more info at the R FAQ
seq1 <- seq(-1,0,0.1)
print(seq1, digits = 20)
## [1] -1.000000000000000000000 -0.900000000000000022204 -0.800000000000000044409 -0.699999999999999955591 -0.599999999999999977796 -0.500000000000000000000
## [7] -0.399999999999999911182 -0.299999999999999933387 -0.199999999999999955591 -0.099999999999999977796 0.000000000000000000000
print(-0.1, digits = 20)
## [1] -0.10000000000000000555
Try doing it this way:
(-1L/10) %in% (seq(-10L, 0L) / 10)
## [1] TRUE
or avoid floating point entirely by multipling both sides by 10
(-1L) %in% seq(-10L, 0L)
## [1] TRUE
Typically the way this is handled is to compare subject to a threshold:
eps <- 1e-5
any(abs(-0.1 - seq(-1, 0, 0.1)) < eps)
## [1] TRUE