5

can any one please explain why this gives different outputs?

round(1.49999999999999)
1


round(1.4999999999999999)
2

I have read the round documentation but it does not mention anything about it there. I know that R represents numbers in binary form, but why does adding two extra 9's changes the result?

Thanks.

Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107
user557240
  • 273
  • 5
  • 15
  • See [this answer][1] about problems in R. [1]: http://stackoverflow.com/questions/1535021/whats-the-biggest-r-gotcha-youve-run-across/3398868#3398868 – John Oct 28 '11 at 16:42

3 Answers3

7

1.4999999999999999 can't be represented internally, so it gets rounded to 1.5.

Now, when you apply round(), the result is 2.

Dennis
  • 14,264
  • 2
  • 48
  • 57
2

Put those two numbers into variable and then print it - you'll see they are different.

Computers doesn't store this kind of numbers with this exact value, (They don't use decadic numbers internaly)

Hurda
  • 4,647
  • 8
  • 35
  • 49
  • 1
    You'd better set `options(digits=20)` before you print them, or they will **look** identical – Ben Bolker Oct 28 '11 at 15:57
  • As noted in other responses - the 1.4999999999999999 is stored as 1.5 so you wont get the same result! – Hurda Oct 30 '11 at 19:19
2

I have never used R, so I don't know is this is the issue, but in other languages such as C/C++ a number like 1.4999999999999999 is represented by a float or a double.

Since these have finite precision, you cannot represent something like 1.4999999999999999 exactly. It might be the case that 1.4999999999999999 actually gets stored as 1.50000000000000 instead due to limitations on floating point precision.

NickLH
  • 2,643
  • 17
  • 28