Exactly storing large integers

The reason you’re not getting your exact value of a is that R is storing it as a double instead of as an integer. Because a is very large, there is some rounding that takes place when you assign a.

Normally to store things as integers you would use L at the end of the numbers; something like:

a <- 12L
class(a)
# [1] "integer"

However your number is too large for a standard integer in R, and you’re forced to use the double representation:

a <- 123456789123456789123456789L
# Warning message:
# non-integer value 123456789123456789123456789L qualified with L; using numeric value 
class(a)
# [1] "numeric"

You will need multiple precision to exactly store an integer this large. One option would be the gmp package:

library(gmp)
a<-as.bigz("123456789123456789123456789")
a
# Big Integer ('bigz') :
# [1] 123456789123456789123456789

Other options for multi-precision arithmetic are available under the “Multi-Precision Arithmetic and Symbolic Mathematics” subheading of the numerical mathematics CRAN task view.

Leave a Comment