R: wrong arithmetic for big numbers

泄露秘密 提交于 2021-01-29 02:16:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!