在this stackoverflow问题中,提供了一个函数的四舍五入功能,例如在matlab中。
round2 = function(x, n) {
posneg = sign(x)
z = abs(x)*10^n
z = z + 0.5
z = trunc(z)
z = z/10^n
z*posneg
}
我经常使用此功能,我一直认为它可以正常工作,直到测试以下代码:
round2((-10:10)+0.005,2)
具有以下结果:
-9.99 -8.99 -8.00 -7.00 -6.00 -5.00 -4.00 -3.00 -2.00 -1.00 0.01 1.00 2.01 3.01 4.01 5.01 6.01 7.01 8.01 9.01 10.01
前两个数字有误!
当我输入round2(c(-9,-8)+0.005,2)
并逐步执行该函数时,我看到在z=z+0.5
z = c(900,800)之后但在z = trunc(z)
z = c(899,800)之后。
可能是由于舍入错误,我已经尝试添加一个非常小的浮点数,例如:z = z + 0.5 + 2e-16
。这没用。该数字必须更高,例如:z = z + 0.5 + 1e-12
。
这是怎么回事?我必须添加多少个最小数字,或者有更好的解决方法?
sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Matrix products: default
locale:
[1] LC_COLLATE=Dutch_Netherlands.1252 LC_CTYPE=Dutch_Netherlands.1252 LC_MONETARY=Dutch_Netherlands.1252
[4] LC_NUMERIC=C LC_TIME=Dutch_Netherlands.1252
attached base packages:
[1] stats graphics grDevices datasets utils methods base
other attached packages:
[1] ggplot2_3.0.0 dplyr_0.7.6
loaded via a namespace (and not attached):
[1] Rcpp_0.12.18 withr_2.1.2 crayon_1.3.4 assertthat_0.2.0 plyr_1.8.4 grid_3.5.0 R6_2.2.2
[8] gtable_0.2.0 magrittr_1.5 scales_0.5.0 pillar_1.3.0 rlang_0.2.1 lazyeval_0.2.1 rstudioapi_0.7
[15] bindrcpp_0.2.2 tools_3.5.0 glue_1.3.0 munsell_0.5.0 purrr_0.2.5 yaml_2.2.0 compiler_3.5.0
[22] colorspace_1.3-2 pkgconfig_2.0.1 bindr_0.1.1 tidyselect_0.2.4 tibble_1.4.2