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?
Asked
Active
Viewed 3,043 times
7

Ben Bolker
- 211,554
- 25
- 370
- 453
-
1Searching for `[r] gmp` gives related answers such as http://stackoverflow.com/questions/6042728/nas-produced-by-integer-overflow-r-on-linux , http://stackoverflow.com/questions/2053397/long-bigint-decimal-equivalent-datatype-in-r – Ben Bolker Nov 18 '11 at 03:14
3 Answers
19
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"

Dason
- 60,663
- 9
- 131
- 148
7
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.

onestop
- 800
- 5
- 10