Created
November 20, 2025 18:16
-
-
Save nanxstats/598d8cbda027959040da66be2a9ba095 to your computer and use it in GitHub Desktop.
Compare two floating point number equivalence testing methods
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
| 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
Thanks for putting together this nice example @nanxstats! My takeaway from your code is that
signif()is sensitive to rounding.To confirm my understanding, I put together an example with many randomly generated numbers. The majority of the time the two approaches agree, and when they don't, it appears to be due to rounding.