R中的舍入错误? [英] Rounding error in R?

查看:54
本文介绍了R中的舍入错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下事项:

> x<-178379.4999999999999999999999999999999
> x
[1] 178379.5
> round(x)
[1] 178380

这似乎是一个基本的舍入错误.R 中是否存在已知的舍入误差?还是因为即使在工作记忆中,R 也最多只能处理 22 位数字?

This seems to be a basic rounding error. Are there known rounding errors in R? Or is it because even in working memory R can only process up to 22 digits?

推荐答案

这是两个非常常见的问题的组合.

This is a combination of two extremely Frequently A'd Qs.

  • 有限浮点精度:这个 R FAQ 7.31,参见例如为什么这些数字不相等?.该值四舍五入为 178379.5.如果您将 options(digits=22) 设置为将数字打印到更多小数位,则无济于事;精度已经丢失,因为(如您所建议的)R 仅存储高达 53 个二进制/22 位十进制数字的精度值.
  • 舍入到偶数:R舍入到偶数",参见 R 中的循环函数是否有错误? .这意味着该值将被四舍五入.
  • finite floating-point precision: this R FAQ 7.31, see e.g. Why are these numbers not equal? . The value gets rounded to 178379.5. It won't help if you set options(digits=22) to print numbers to more decimal places; the precision has been lost because (as you suggested) R only stores values up to 53 binary/22ish decimal digits of precision.
  • round to even: R "rounds to even", see Is there an error in round function in R? . That means the value will be rounded up.

这与打印精度无关.

如果您使用较少的 '9',您就会看到您所期望的(这将是 R 有限的打印 精度加上预期的四舍五入)

If you had used fewer '9's, you would have seen what you expected (which would be a combination of R's limited printing precision plus the expected rounding)

> x <- 178379.49
> 
> x
[1] 178379.5  ## prints as .5, but full precision is present
> round(x)
[1] 178379

这篇关于R中的舍入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆