I’m trying to work with big numbers in R, in my opinion they aren’t even that big. I asked R to return me the module of the division of 6001532020609003100 by 97, I got answer 1; when doing the same calculation in Python I got answer 66.
Can someone tell me what’s going on?
Advertisement
Answer
R doesn’t have the same kind of “magic”, arbitrary-length integers that Python does: its base integer type is 32 bit, which maxes out at .Machine$integer.max
== 2147483647. When confronted with a number greater than this value R automatically converts it to double-precision floating point; then the %%
operator gets messed up by floating-point imprecision. (If you try to insist that the input is an integer by entering 6001532020609003100L
(L
indicates integer) R still converts it to float, but warns you …)
@JonSpring is right that you can do completely arbitrary-length integer computation (up to your computer’s memory capability) with Rmpfr
, but you can
also use the bit64
package for 64-bit integers, which your example just fits into:
library(bit64) x <- as.integer64("6001532020609003100") x %% 97 ## [1] 66
But doubling this value puts you out of the integer-64 range: 2*x
gives an overflow error.
Honestly, if you want to do a lot of big-integer calculation I’d say that Python is more convenient …