Skip to content

Instantly share code, notes, and snippets.

@SteveBronder
Last active January 24, 2020 21:34
Show Gist options
  • Save SteveBronder/a6052a0c652a8994e91e1a76aced3a35 to your computer and use it in GitHub Desktop.
Save SteveBronder/a6052a0c652a8994e91e1a76aced3a35 to your computer and use it in GitHub Desktop.
test_x = runif(10000, min = 0, 1000)
test_x = test_x * 1e+10
orig_signif = function(x, digits = 1) {
xx = abs(x);
return(trunc((10^((floor(log10(x)) * -1) + digits - 1)) * x))
}
new_signif = function(x, digits = 1) {
xx = abs(x);
return(trunc(exp(log(10)*(-floor((log(xx)/log(10))) + digits - 1) + log(xx))))
}
# Yikes!
BenfordTests::signifd(100000000000)
#[1] 0
orig_signif(100000000000)
#[1] 0
# Good!
new_signif(100000000000)
#[1] 1
orig_x = orig_signif(test_x)
new_x = new_signif(test_x)
all(orig_x == new_x)
orig_x = orig_signif(test_x, 2)
new_x = new_signif(test_x, 2)
all(orig_x == new_x)
orig_x = orig_signif(test_x, 3)
new_x = new_signif(test_x, 3)
all(orig_x == new_x)
# patch
signifd = function(x = NULL, digits = 1) {
if (!is.numeric(x)) {
stop("x needs to be numeric.")
}
x <- abs(x)
return(trunc(exp(log(10)*(-floor((log(xx)/log(10))) + digits - 1) + log(xx))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment