Skip to content

Commit

Permalink
Add handling and tests for floating-pointness
Browse files Browse the repository at this point in the history
  • Loading branch information
andrjohns committed Jun 7, 2024
1 parent 5aafeda commit 2df65c6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
6 changes: 5 additions & 1 deletion R/data.R
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,12 @@ process_data <- function(data, model_variables = NULL) {
if (!all(is_wholenumber(data[[var_name]]))) {
warning("A non-integer value was supplied for '", var_name, "'!",
" It will be truncated to an integer.", call. = FALSE)
mode(data[[var_name]]) <- "integer"
} else {
# Round before setting mode to integer to avoid floating point errors
data[[var_name]] <- round(data[[var_name]])
mode(data[[var_name]]) <- "integer"
}
mode(data[[var_name]]) <- "integer"
}
}
}
Expand Down
18 changes: 18 additions & 0 deletions tests/testthat/test-data.R
Original file line number Diff line number Diff line change
Expand Up @@ -384,3 +384,21 @@ test_that("process_data warns on int coercion", {
process_data(list(a = c(1, 2, 3)), model_variables = mod$variables())
)
})

test_that("Floating-point differences do not cause truncation towards 0", {
stan_file <- write_stan_file("
data {
int a;
real b;
}
")
mod <- cmdstan_model(stan_file, compile = FALSE)
a <- 10*(3-2.7)
expect_false(is.integer(a))
test_file <- process_data(list(a = a, b = 2.0), model_variables = mod$variables())
expect_match(
" \"a\": 3,",
readLines(test_file)[2],
fixed = TRUE
)
})

0 comments on commit 2df65c6

Please sign in to comment.