gpt4 book ai didi

r - R 中的上限函数不准确(有时)

转载 作者:行者123 更新时间:2023-12-04 10:33:14 24 4
gpt4 key购买 nike

我正在尝试将数字 x 取整为可以被数字 m 整除。使用上一篇关于 SO 的帖子中的以下功能:

roundUP = function(x,m) 
{
return(m * ceiling(x/m))
}

但是,当我输入 x = 0.28m = 0.005 时,函数输出 0.285,而结果应为 0.28。

当我尝试 ceiling(0.28/0.005) 时,它输出 57,而结果应该是 56,因为 56 已经是一个整数。谁能解释这是否正在发生,这是 Ceiling 函数的错误吗?

最佳答案

这个问题与浮点运算有关。您可以找到关于此的一些详细信息 here .

浏览下面的代码,它应该会阐明正在发生的事情。

0.28/0.005  # Console displays 56
0.28/0.005 == 56 # returns FALSE. Why?
print(0.28/0.005, digits = 18) # 56.0000000000000071

# Solution?
roundUP = function(x, m)
{
return(m * ceiling(round(x/m, 9)))
}

另外,请注意 ?ceiling

中的 Warning 部分

The realities of computer arithmetic can cause unexpected results, especially with floor and ceiling. For example, we ‘know’ that floor(log(x, base = 8)) for x = 8 is 1, but 0 has been seen on an R platform. It is normally necessary to use a tolerance.

关于r - R 中的上限函数不准确(有时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52133800/

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