当我遇到函数产生的相当奇怪的差异时,我一直试图data.table通过将round函数添加到ITime类来为包做出贡献round。在幕后,类的对象ITime只是一个具有漂亮格式的整数向量,因此unclass(object)提供了一个整数向量。
将这个整数向量四舍五入到最接近的分钟可以这样完成:
x <- as.ITime(seq(as.POSIXct("2020-01-01 07:00:00"), as.POSIXct("2020-01-01 07:10:00"), "30 sec"))
round(unclass(x) / 60L) * 60L
# or
round(as.integer(x) / 60L) * 60L
Run Code Online (Sandbox Code Playgroud)
问题就在这里……
当我执行此操作时,我希望unclass(x) / 60以 0.5 结尾的任何实例都被四舍五入。然而,事实并非如此!
我已经在两台不同的计算机上的 Windows 和 Mac 上尝试了这个例子,结果相同。有没有人知道为什么会发生这种情况?
** 仅供参考,我知道这个特定问题可以用不同的方式解决:unclass(x) %/% 60L. 但我感兴趣的是为什么该round功能不能按预期工作。
?round:
Run Code Online (Sandbox Code Playgroud)‘round’ rounds the values in its first argument to the specified number of decimal places (default 0). See ‘Details’ about “round to even” when rounding off a 5.
[...]
Run Code Online (Sandbox Code Playgroud)Note that for rounding off a 5, the IEC 60559 standard (see also ‘IEEE 754’) is expected to be used, ‘_go to the even digit_’. Therefore ‘round(0.5)’ is ‘0’ and ‘round(-1.5)’ is ‘-2’. However, this is dependent on OS services and on representation error (since e.g. ‘0.15’ is not represented exactly, the rounding rule applies to the represented number and not to the printed number, and so ‘round(0.15, 1)’ could be either ‘0.1’ or ‘0.2’).