问题
I encountered a problem in R when it's performing simple arithmetic for big numbers incorrectly. Can someone explain what's happening, and how to work around?
> a <- 51569
> b <- a + 6924851946518374722
> b
[1] 6924851946518425600 # problem is visible here already
> c <- b - 6924851946518374722
> c
[1] 51200
So there's an error of 469 when adding the big number. Why?
回答1:
R uses double-precision floating-point to represent values. The precision depends on your machine. On my Intel machine with IEEE doubles, I get 52 bits of precision:
> options(digits=22)
> (0:1) + 2^52
[1] 4503599627370496 4503599627370497
> (0:1) + 2^53
[1] 9007199254740992 9007199254740992
回答2:
R has a package that wraps GMP, the gnu multiple precision library:
CRAN: R gmp manual
library(gmp)
a <- as.bigz("51569")
b <- a + as.bigz("6924851946518374722")
c <- b - as.bigz("6924851946518374722")
c
Big Integer ('bigz') :
[1] 51569
As pointed out in a comment, the quotes are necessary.
as.bigz(6924851946518374722) # Does not work as intended
Big Integer ('bigz') :
[1] 6924851946518374400
because otherwise R converts the argument to a double, losing precision before converting to bigz
.
Note also that R does not yet support 64 bit integers, e.g.
[1] 4294967296L
Warning message:
non-integer value 4294967296 qualified with L; using numeric value
来源:https://stackoverflow.com/questions/23600569/r-wrong-arithmetic-for-big-numbers