关于 r:使用上限函数舍入的不一致 | 珊瑚贝

Inconsistencies Rounding Up with Ceiling Function


我必须将数据框四舍五入到小数点后两位,而 1/100 的小数点总是需要四舍五入。但是,我看到我正在使用的上限函数有一些奇怪的行为。

1
2
3
4
5
6
7
8
9
10
11
a <- c(268.600, 268.700, 268.500)
b <- c(22.410, 653.423, 124.400)

df1 <- data.frame(a, b)

ceiling(df1 * 100)/100

       a      b
1 268.61  22.41
2 268.70 653.43
3 268.50 124.40

我希望 df1[1,1] 的输出为 268.60 .. 但我得到 268.61。我不确定为什么会这样; \\’a\\’ 中的其他数字给出了预期的输出。我正在使用 R 版本 3.5.3

编辑:

@Akrun 发现 col A 中的问题是浮点数的结果。

我现在正在寻求帮助的是一种将 10.032 之类的数字舍入到 10.04 的方法,同时还避免由于浮点问题而将 10.000 之类的数字舍入到 10.01。

现在我被 df1[1,1] 正确舍入或 df[2,2] 正确舍入,但不是两者兼而有之。

  • 原因是它是一个浮点数,而不是整数 (df1$a * 100) == 26860#[1] FALSE FALSE FALSE。或找出差异 (df1$a * 100)- 26860 [1] 3.637979e-12 1.000000e+01 -1.000000e+01#


它不完全是一个整数,所以它不是。等于 26860

1
2
(df1$a * 100)- 26860
#[1]  3.637979e-12  1.000000e+01 -1.000000e+01

与 ceiling

一起获得 round

为了避免这种情况,我们可以转换成 integer

1
2
ceiling(as.integer(df1$a * 100))/100
#[1] 268.6 268.7 268.5
  • 这解决了 col a 中浮点数的问题,但是它删除了我需要的影响 col b 的功能。例如,我需要 10.032 向上舍入到 10.04,但在过程中间使用 as.integer() 会删除我试图向上舍入的小数:e <- 10.032 f <- e * 100 g <- as .integer(f) h <- ceiling(g) i <- h/100 我想我需要找到像 ms Decimal 类型一样工作的东西:(
  • @JakeMercer。抱歉,这不是您最初的问题
  • @JakeMercer。你的问题现在还不清楚。如果您可以作为新问题发布(如果它完全不同)或更新帖子(如果它相似)。我花了一些时间在这
  • 感谢您的帮助。我试图澄清这个问题。
  • @JakeMercer。我无法重现该问题。你能提供一个例子 v1 <- c(10.032, 10.000, 10.0001); ceiling((v1 *100))# [1] 1004 1000 1001


来源:https://www.codenong.com/57312956/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9971.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?