Skip to content
Prev 29084 / 63424 Next

significant digits (PR#9682)

On 6/3/2008 4:36 PM, Simon Urbanek wrote:
I think you skipped a step.  The correct answer is either 0.1234 or 
0.1235, not something 10000 times bigger.  The first important question 
is whether 0.12345 is exactly representable, and the answer is no.  The 
second question is whether it is represented by a number bigger or 
smaller than the real number 0.12345.  If it is bigger, the answer 
should be 0.1235, and if it is smaller, the answer is 0.1234.  My 
experiments suggest it is bigger.  Yours don't look relevant.  It 
certainly isn't exactly equal to 1234.5/10000, because that number is 
not representable.  It's equal to x/2^y, for some x and y, and it's a 
pain to figure out exactly what they are.

However, I am pretty sure R is representing it (at least on Windows) as 
the binary expansion

0.000111111001101001101011010100001011000011110010011111

while the true binary expansion (using exact rational arithmetic) starts 
out

0.00011111100110100110101101010000101100001111001001111011101...

If you line those up, you'll see that the first number is bigger than 
the second.  (Ugly code to derive these is down below.)

Clearly the top representation is the correct one to that number of 
binary digits, so I think Windows got it right, and all those other 
systems didn't.  This is probably because R on Windows is using extended 
precision (64 bit mantissas) for intermediate results, and those other 
systems stick with 53 bit mantissas.

Duncan Murdoch

# Convert number to binary expansion; add the decimal point manually

x <- 0.12345
while (x != 0) {
   cat(trunc(x))
   x <- x - trunc(x)
   x <- x * 2
}

# Do the same thing in exact rational arithmetic

num <- 12345
denom <- 100000
for (i in 1:60) {
   cat(ifelse(num > 100000, "1", "0"))
   num <- num %% 100000
   num <- 2*num
}

# Manually cut and paste the results to get these:

"0.000111111001101001101011010100001011000011110010011111"
"0.00011111100110100110101101010000101100001111001001111011101"