Multiplication of large integers

2020-02-11 03:56发布

问题:

I tried to multiply 111111111*111111111, which is the same as 111111111^2, and got incorrect results. It should give 12345678987654321, but instead it gives a rounding error. Do I need to use some special variable type for long numbers or is this a bug with R?

回答1:

The 'gmp' package will allow you to do operations on values that large though.

> library(gmp)
> j <- 111111111
> k <- as.bigz(j)
> mul.bigz(k, k)
[1] "12345678987654321"


回答2:

It's not a limitation of R specifically, it's a limitation of double precision floating-point arithmetic. A standard double-precision floating-point number has around 16 decimal digits of accuracy. The answer to your sum requires 17. R does not have a variable type with greater precision, but neither do many other languages.



回答3:

Also, new package int64 from Romain Francois.