3
options(digits = 18)
x <- 0.127272727272727287
str(x)
# num 0.127
x
#[1] 0.127272727272727287
as.character(x)
#[1] "0.127272727272727"
as.numeric(as.character(x))
[1] 0.12727272727272701

Where does the 01 come from? What's going on here?

user1320502
  • 2,510
  • 5
  • 28
  • 46
  • 3
    Because the closes floating point number that can represent `0.127272727272727` is `0.1272727272727270098062746228606556542217731475830078125` – juanpa.arrivillaga Aug 13 '17 at 18:17
  • 1
    And `as.character` represents real and complex numbers to 15 significant digits (from `?as.character`) – d.b Aug 13 '17 at 18:18
  • 2
    Essentially a duplicate of [Why are these numbers not equal?](https://stackoverflow.com/q/9508518/903061) – Gregor Thomas Aug 13 '17 at 18:19
  • 2
    If you really want to get into the weeds, read [this](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – juanpa.arrivillaga Aug 13 '17 at 18:22
  • happy to delete if the consensus is dupe. +1 responses – user1320502 Aug 13 '17 at 18:24
  • 5
    @user1320502 it's not really necessary to delete a duplicate. – juanpa.arrivillaga Aug 13 '17 at 18:24
  • 1
    Definitely don't delete - much better to leave this as a pointer to the other one. The answer is pretty much the same, but the question to get there is different. I'm not sure if it should be marked as a dupe (I didn't dupe-hammer close it). Let's see what answers come along and close it if nothing is substantially different. – Gregor Thomas Aug 13 '17 at 18:31

1 Answers1

3

This is hinted at in the help page ?options when you look at the section on digits. You can set the number of digits to any number up to 22, but that does not mean that R will accurately represent that many digits. R uses IEEE double-precision. Wikipedia tells us that this representation has

Sign bit: 1 bit
Exponent: 11 bits
Significand precision: 53 bits (52 explicitly stored)

So R is storing numbers to log(2^53, 10) = 15.95459 decimal digits accuracy. Anything you get beyond that is luck.

G5W
  • 36,531
  • 10
  • 47
  • 80