R中的天花板功能不正确(有时)

Khi*_*yen 3 r rounding ceil

我正在尝试将数字x取整以将其除以数字m。在SO的上一篇文章中使用以下功能:

roundUP = function(x,m) 
{
    return(m * ceiling(x/m))
}
Run Code Online (Sandbox Code Playgroud)

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

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

Ben*_*Ben 5

这个问题与浮点算法有关。您可以在此处找到有关此操作的一些详细信息。

仔细阅读下面的代码,它应该可以使您了解正在发生的事情。

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)))
}
Run Code Online (Sandbox Code Playgroud)

另外,请注意其中的“ 警告”部分?ceiling

计算机算法的现实情况可能会导致意外结果,尤其是在地板和天花板上。例如,我们“知道” x = 8的floor(log(x,base = 8))为1,但在R平台上看到0。通常必须使用公差。