R: simple multiplication causes integer overflow

In a longer script, I need to multiply the length of the vector A (2614) with the row numbers of the data block B (1456000). If I do this directly using length(A) * nrow(B) , I get the message NAs produced by integer overflow , although there is no problem multiplying the same numbers:

 2614 * 1456000 [1] 3805984000 

The only way to get multiplication by work is round(length(A)) * nrow(B) or length(A) * round(nrow(B)) . But the numbers created by length and nrow must be integers as you like! Moreover, I checked this with the following function suggested on the help page for the is.integer function ...

 is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x-round(x)) < tol 

... and, of course, they are whole. So why do I need round crutches here? Very puzzling ... Does anyone have an idea what is going on in the background?

+8
r integer-overflow
source share
1 answer

Hopefully a graphical representation of what is happening ....

 2614 * 1456000 #[1] 3805984000 ## Integers are actually represented as doubles class( 2614 * 1456000 ) #[1] "numeric" # Force numbers to be integers 2614L * 1456000L #[1] NA #Warning message: #In 2614L * 1456000L : NAs produced by integer overflow ## And the result is an integer with overflow warning class( 2614L * 1456000L ) #[1] "integer" #Warning message: #In 2614L * 1456000L : NAs produced by integer overflow 

2614 * 1456000 is numeric because both operands actually have a class of numeric . The overflow occurs because both nrow and length return an integer , and therefore the result is an integer, but the result exceeds the maximum size represented by the integer class (+/- 2 * 10 ^ 9). A numeric or double may contain 2e-308 to 2e+308 . To solve your problem, simply use as.numeric(length(A)) or as.double(length(A)) .

+10
source share

All Articles