从.5向上舍入 [英] Round up from .5

查看:71
本文介绍了从.5向上舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Yes I know why we always round to the nearest even number if we are in the exact middle (i.e. 2.5 becomes 2) of two numbers. But when I want to evaluate data for some people they don't want this behaviour. What is the simplest method to get this:

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

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

to be 1,2,3,...,10 and not 0,2,2,4,4,...,10.

要澄清:四舍五入后,1.4999应该为1. (我认为这很明显)

To clearify: 1.4999 should be 1 after rounding. (I thought this would be obvious)

推荐答案

这不是我自己的功能,遗憾的是,我现在找不到我的位置(原为在 具有统计意义博客中的匿名评论),但是它应该可以帮助您满足您的需求.

This is not my own function, and unfortunately, I can't find where I got it at the moment (originally found as an anonymous comment at the Statistically Significant blog), but it should help with what you need.

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

x是要四舍五入的对象,而n是要四舍五入的位数.

x is the object you want to round, and n is the number of digits you are rounding to.

示例

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).)

(Thanks @Gregor for the addition of + sqrt(.Machine$double.eps).)

这篇关于从.5向上舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆