Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why %in% from R has this strange behaviour?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading