Skip to content

Instantly share code, notes, and snippets.

@nanxstats
Created November 20, 2025 18:16
Show Gist options
  • Select an option

  • Save nanxstats/598d8cbda027959040da66be2a9ba095 to your computer and use it in GitHub Desktop.

Select an option

Save nanxstats/598d8cbda027959040da66be2a9ba095 to your computer and use it in GitHub Desktop.
Compare two floating point number equivalence testing methods
library(testthat)
# Method A: round to 6 significant digits, then compare with default tiny tolerance
equal_after_signif <- function(x, y) {
expect_equal(signif(x, digits = 6), signif(y, digits = 6))
}
# Method B: compare with relative/absolute tolerance = 1e-6
equal_with_tolerance <- function(x, y) {
expect_equal(x, y, tolerance = 1e-6)
}
test_that("Example 1: signif() says equal, tolerance says not equal", {
x <- 1.000003
y <- 1
# Method A should succeed
equal_after_signif(x, y)
# Method B should fail
expect_failure(equal_with_tolerance(x, y))
})
test_that("Example 2: tolerance says equal, signif() says not equal", {
x <- 7.000006
y <- 7
# Method A should fail
expect_failure(equal_after_signif(x, y))
# Method B should succeed
equal_with_tolerance(x, y)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment