0

There are a number of threads about this question. None seems to answer the simple question: why does R round incorrectly and how can I let it round correctly?

Correct rounding to the i-th decimal x considers the i+1-th decimal. If it is 5 or larger then x is is set to x+1. If it is 4 or smaller then x is returned. For example 1.45 is rounded to the first decimal as 1.5. 1.44 is rounded 1.4. However, in R

> round(1.45,1)
[1] 1.4

But

> round(1.46,1)
[1] 1.5

So it changes the convention to 'if the i+1th decimal is 6 or larger, then x is set to x+1'. Why? And how can I change this to the convention I am familiar with?

tomka
  • 2,516
  • 7
  • 31
  • 45
  • 2
    "_Correct rounding_". Reference needed. The behaviour of `round` is described in the help text: "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_’. – Henrik Mar 01 '21 at 13:08
  • @Henrik I had no idea there was debate about how to round (but I am not a computer scientist). Thanks to anybody sharing the link to the answer. – tomka Mar 01 '21 at 13:14

1 Answers1

1

Most decimal fractions are not exactly representable in binary double precision

Learned here: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Round.html

Section "Warnings":

Rounding to decimal digits in binary arithmetic is non-trivial (when digits != 0) and may be surprising. Be aware that most decimal fractions are not exactly representable in binary double precision. In R 4.0.0, the algorithm for round(x, d), for d > 0, has been improved to measure and round “to nearest even”, contrary to earlier versions of R (or also to sprintf() or format() based rounding).

TarJae
  • 72,363
  • 6
  • 19
  • 66