Exactly storing large integers

后端 未结 1 1984
别跟我提以往
别跟我提以往 2020-11-29 13:22

In R software

a <- 123456789123456789123456789
sprintf(\"%27f\",a)
#[1] \"123456789123456791337762816.000000\"

I got the wrong answer. I

相关标签:
1条回答
  • 2020-11-29 14:14

    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.

    0 讨论(0)
提交回复
热议问题