Casting numeric from character imprecision

前端 未结 1 701
天命终不由人
天命终不由人 2021-01-22 20:12

as.numeric(as.character(1363821605424526000)) results in 1363821605424526080.

Why and how do I prevent this?

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-22 20:49

    One solution is to use the gmp library (GNU Multiple Precision library) to create and do basic arithmetic with big integers...

    require(gmp)
    as.bigz("1363821605424526000")
    #Big Integer ('bigz') :
    #[1] 1363821605424526000
    

    Note the use of " round the number. This is to protect it from being parsed as a numeric data type by R which of course will not be able to represent this number exactly in the given data structures. " gets R to treat it as a character variable before as.bigz turns it into a big integer type.

    Examples

    as.bigz("1363821605424526000") + 1
    #Big Integer ('bigz') :
    #[1] 1363821605424526001
    
    as.bigz("1363821605424526000")^3
    #Big Integer ('bigz') :
    #[1] 2536720967038413127881466345733319337545403576000000000
    

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