gpt4 book ai didi

从 0.5 向上舍入

转载 作者:行者123 更新时间:2023-12-03 05:53:37 25 4
gpt4 key购买 nike

是的,我知道为什么如果我们正好位于两个数字的中间(即 2.5 变成 2),我们总是四舍五入到最接近的偶数。但当我想评估某些人的数据时,他们不希望出现这种行为。获得此信息的最简单方法是什么:

x <- seq(0.5,9.5,by=1)
round(x)

为 1,2,3,...,10,而不是 0,2,2,4,4,...,10。

编辑:澄清一下:四舍五入后 1.4999 应为 1。 (我认为这很明显)

最佳答案

这不是我自己的函数,不幸的是,我现在找不到它的来源(最初是在 Statistically Significant blog 上作为匿名评论找到的),但它应该有帮助满足您的需求。

round2 = function(x, digits) {
posneg = sign(x)
z = abs(x)*10^digits
z = z + 0.5 + sqrt(.Machine$double.eps)
z = trunc(z)
z = z/10^digits
z*posneg
}

x 是要舍入的对象,digits 是要舍入的位数。

示例

x = c(1.85, 1.54, 1.65, 1.85, 1.84)
round(x, 1)
# [1] 1.8 1.5 1.6 1.8 1.8
round2(x, 1)
# [1] 1.9 1.5 1.7 1.9 1.8

(感谢 @Gregor 添加 + sqrt(.Machine$double.eps)。)

关于从 0.5 向上舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12688717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com