Last active
September 30, 2021 17:50
-
-
Save slwu89/e6c7559f8ad166b578af121e7af99a5a to your computer and use it in GitHub Desktop.
operator to check if floats are in sets of other floats, for R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# for more info on comparing floats, this blog post is very informative: https://bitbashing.io/comparing-floats.html | |
# for more info on how floating point mathematics compares to "real" mathematics, see https://www.tandfonline.com/doi/full/10.1080/10724117.2019.1611061 | |
# helper function for approximate equality between floats | |
approx_equal <- function(a, b, tol = sqrt(.Machine$double.eps)) { | |
abs(a - b) <= tol | |
} | |
# use instead of the %in% operator to check if floats are in sets of other floats | |
`%in_approx%` <- function(x, table) { | |
matches <- vapply(X = x, FUN = function(i) { | |
return(any(approx_equal(i, table))) | |
}, FUN.VALUE = logical(1)) | |
return(matches) | |
} | |
# test below. standard comparisons "fail", %in_approx% gets what we want | |
table <- c(0.95,0.96,0.97) | |
x <- sample(x = seq(from=0.9,to=1,by=0.01),size = 20,replace = T) | |
x %in% table | |
x[x %in% table] | |
x %in_approx% table | |
x[x %in_approx% table] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment