rbigintegercomputation

What is this problem with computation of large integers?


The following equation is same as doing nothing to the integer

((as.bigz(27080235094679553)+1028)*2)/2 - 1028

However, the answer to this in console is 27080235094679552. To get the correct answer I need to subtract 1027 instead of 1028. What's the issue here?

I tried using the mfpr package as well but it did not work.


Solution

  • When you enter 27080235094679553 as a numeric constant as the argument to as.bigz, R first parses the number and stores it as a double-precision float. You need to enter the value as character so it doesn't get messed up:

    library(gmp)
    ((as.bigz("27080235094679553")+1028)*2)/2 - 1028
    ## Big Rational ('bigq') :
    ## [1] 27080235094679553
    

    As a further illustration:

    print(27080235094679553, digits = 22)
    ## [1] 27080235094679552
    

    The same issue would apply when using Rmpfr.

    (As pointed out in the comments, ?gmp::as.bigz has this note:

    x <- as.bigz(1234567890123456789012345678901234567890)
    will not work as R converts the number to a double, losing precision and only then convert[ing] to a ‘"bigz"’ object.

    Instead, use the syntax
    x <- as.bigz("1234567890123456789012345678901234567890")

    )