问题
Consider the following:
> x<-178379.4999999999999999999999999999999
> x
[1] 178379.5
> round(x)
[1] 178380
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?
回答1:
This is a combination of two extremely Frequently A'd Qs.
- 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.
This is not about printing precision.
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
回答2:
The problem is probably broader, due to floating-point representation in hardware.
Not sure if this website would be helpful, but it shows that the number that is stored when you write 178379.4999999999999999999999999999999 is actually 178379.5 (as per the IEEE-754 Floating-Point Standard):
回答3:
See ?print.default
for an explanation about digits greater than 15.
Large number of digits
Note that for large values of digits, currently for digits >= 16, the calculation of the number of significant digits will depend on the platform's internal (C library) implementation of sprintf() functionality.
See this question for more info on R's precision.
来源:https://stackoverflow.com/questions/51450396/rounding-error-in-r