r - R中的round函数是否有错误?

标签 r rounding

这个问题在这里已经有了答案:





Round up from .5

(7 个回答)


5年前关闭。




round 函数似乎有错误。下面我希望它返回 6,但它返回 5。

round(5.5) 
# 5

除了 5.5,例如 6.5,4.5 返回 7、5,正如我们预期的那样。

有什么解释吗?

最佳答案

此行为在 ?round 的帮助文件中进行了解释。功能:

Note that for rounding off a 5, the IEC 60559 standard 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).


round( .5 + 0:10 )
#### [1]  0  2  2  4  4  6  6  8  8 10 10

Greg Snow 的另一个相关电子邮件交流:R: round(1.5) = round(2.5) = 2? :

The logic behind the round to even rule is that we are trying to represent an underlying continuous value and if x comes from a truly continuous distribution, then the probability that x==2.5 is 0 and the 2.5 was probably already rounded once from any values between 2.45 and 2.54999999999999..., if we use the round up on 0.5 rule that we learned in grade school, then the double rounding means that values between 2.45 and 2.50 will all round to 3 (having been rounded first to 2.5). This will tend to bias estimates upwards. To remove the bias we need to either go back to before the rounding to 2.5 (which is often impossible to impractical), or just round up half the time and round down half the time (or better would be to round proportional to how likely we are to see values below or above 2.5 rounded to 2.5, but that will be close to 50/50 for most underlying distributions). The stochastic approach would be to have the round function randomly choose which way to round, but deterministic types are not comforatable with that, so "round to even" was chosen (round to odd should work about the same) as a consistent rule that rounds up and down about 50/50.

If you are dealing with data where 2.5 is likely to represent an exact value (money for example), then you may do better by multiplying all values by 10 or 100 and working in integers, then converting back only for the final printing. Note that 2.50000001 rounds to 3, so if you keep more digits of accuracy until the final printing, then rounding will go in the expected direction, or you can add 0.000000001 (or other small number) to your values just before rounding, but that can bias your estimates upwards.

关于r - R中的round函数是否有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892999/

相关文章:

r - 饼图 - 如何在正确的位置获取百分比文本?

r - 有效地查找数据框中具有几乎相同值的行组

r - 评估 R nls 中多个因素的渐近线

r - 在 R 中,当从另一列中的分隔文本创建列名称时,新列名称仅从第一行分配

php - 将价格舍入到下一个 5 或 10 个百分点

c# - Math.Round for decimal

regex - 从 R 文本文件中删除特定行

舍入错误: Harmonic mean with exponent of small numbers

python - 为什么 round(2.49999999999999992) 返回 3

python-2.7 - 在OpenCV 3.2.0中是cv2.cv.Round吗?