2

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?

Lucas De Abreu Maia
  • 598
  • 2
  • 6
  • 19

3 Answers3

6

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
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • I don't see how R rounding to even is relevant in this particular case, as my whole confusion was that 178379.4999999999999999999999999999999 is less than 178379.5 and thus should be rounded down regardless of the particular criterium R uses to round .5. I accepted the answer anyway, thanks. – Lucas De Abreu Maia Jul 21 '18 at 19:39
  • 1
    It wasn't clear from your question that you understood the round-to-even behavior. – Ben Bolker Jul 21 '18 at 23:31
3

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):

178379.5 is what is stored when you write 178379.4999999999999999999999999999999

2

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.

Community
  • 1
  • 1
Anonymous coward
  • 2,061
  • 1
  • 16
  • 29