Hansy Kumaralal
Hansy Kumaralal

Reputation: 169

How to resolve integer overflow?

I have created a matrix (matA) of 1000 rows and 1000 columns, and I want to calculate powers of this matrix. It works very well up to calculating the third power of the matrix. But when I ask to calculate its fourth power, it gives a warning message saying,

In matA * matA * matA * matA : NAs produced by integer overflow

How can I resolve this problem?

Upvotes: 0

Views: 3255

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226057

Since you didn't give an example:

set.seed(101)
z <- matrix(rnorm(1e6),1e3)
z2 <- round(z)*1000000
storage.mode(z2) <- "integer"

If you really want a matrix power (as in z2 %*% z2 %*% z2 %*% z2), it's best to use the Matrix or expm package.

library(expm)
z4C <- z2 %^% 4

On the other hand, if you really want the elementwise product

z4D <- z2*z2*z2*z2
## Warning message "NAs produced"

All you need to do is convert to numeric.

storage.mode(z2) <- "numeric"
z4E <- z2*z2*z2*z2  ## fine

Upvotes: 4

Related Questions